From aa99659a0f3218c443a6fcbc17dbeb9e43537574 Mon Sep 17 00:00:00 2001 From: Sid Mohan <61345237+sidmohan0@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:00:49 -0800 Subject: [PATCH 1/5] Prepare directory candidate with pinned runtime and verified protection fixes --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 24 +- .github/workflows/ci.yml | 21 +- PRIVACY.md | 65 ++++ README.md | 164 ++++---- SECURITY.md | 20 + assets/datafog-icon-512.png | Bin 0 -> 13146 bytes docs/directory-submission.md | 96 +++++ docs/implementation-review.md | 16 + docs/readiness.md | 103 +++++ docs/release-notes-0.2.1.md | 34 ++ docs/release-verification-plan.md | 58 +++ .../verification/2026-11-18-host-readiness.md | 125 ++++++ docs/verification/host-readiness-results.json | 358 ++++++++++++++++++ docs/verification/interactive-2026-11-18.txt | 113 ++++++ docs/verification/marketplace-install.md | 46 +++ engine/datafog_guard/__init__.py | 6 +- engine/datafog_guard/ccperms.py | 25 ++ engine/datafog_guard/cli.py | 6 +- engine/datafog_guard/dependencies.py | 32 ++ engine/datafog_guard/hook.py | 10 +- engine/datafog_guard/mcp_server.py | 211 ++++++++--- engine/datafog_guard/shapes.py | 9 +- engine/datafog_guard/store.py | 10 + engine/datafog_guard/vault.py | 35 +- pyproject.toml | 4 +- scripts/bootstrap.sh | 31 +- scripts/datafog-guard | 5 +- scripts/verify-manifests.sh | 19 + tests/live/run_installed_readiness.py | 125 ++++++ tests/live/run_live.py | 7 +- tests/live/run_readiness.py | 170 +++++++++ tests/test_cli_and_plugin.py | 56 ++- tests/test_core_behaviour.py | 76 +++- tests/test_dependencies.py | 69 ++++ tests/test_fail_closed.py | 13 + tests/test_hook_protocol.py | 16 + tests/test_keystore.py | 80 ++++ tests/test_mcp.py | 184 +++++++++ 39 files changed, 2265 insertions(+), 179 deletions(-) create mode 100644 PRIVACY.md create mode 100644 SECURITY.md create mode 100644 assets/datafog-icon-512.png create mode 100644 docs/directory-submission.md create mode 100644 docs/implementation-review.md create mode 100644 docs/readiness.md create mode 100644 docs/release-notes-0.2.1.md create mode 100644 docs/release-verification-plan.md create mode 100644 docs/verification/2026-11-18-host-readiness.md create mode 100644 docs/verification/host-readiness-results.json create mode 100644 docs/verification/interactive-2026-11-18.txt create mode 100644 docs/verification/marketplace-install.md create mode 100644 engine/datafog_guard/dependencies.py create mode 100644 scripts/verify-manifests.sh create mode 100644 tests/live/run_installed_readiness.py create mode 100644 tests/live/run_readiness.py create mode 100644 tests/test_dependencies.py diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 6f529de..579a870 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." + "description": "Locally replaces detected personal data and selected credentials with reversible markers in Claude Code. See the README for coverage and platform limits." } ] } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8018264..a0d78b5 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. See the README for coverage and platform limits.", - "version": "0.2.0", + "description": "Locally replaces detected personal data and selected credentials with reversible markers in Claude Code files and tool output. Uses an encrypted local vault. Requires a supported Mac or Linux machine; coverage and failure-mode limits apply.", + "version": "0.2.1", "author": { "name": "DataFog", "url": "https://datafog.ai" @@ -10,7 +10,13 @@ "homepage": "https://datafog.ai", "repository": "https://github.com/DataFog/datafog-claude-plugin", "license": "Apache-2.0", - "keywords": ["privacy", "pii", "secrets", "redaction", "hooks"], + "keywords": [ + "privacy", + "pii", + "secrets", + "redaction", + "hooks" + ], "userConfig": { "keep_vault_on_uninstall": { "type": "boolean", @@ -22,7 +28,11 @@ "type": "string", "title": "Files that cannot be checked", "description": "What to do when Claude reads a file DataFog cannot check (images, PDFs, binary or very large files): ask you each time, deny the read, or allow it unchecked.", - "options": ["ask", "deny", "allow"], + "options": [ + "ask", + "deny", + "allow" + ], "default": "ask" }, "entities": { @@ -31,5 +41,9 @@ "description": "Comma-separated list, or empty for the default set (EMAIL, PHONE, SSN, CREDIT_CARD, API_KEY, BEARER_TOKEN, JWT, PRIVATE_KEY, CREDENTIAL_URI, US_ROUTING_NUMBER, NPI, ACCOUNT_NUMBER). Also available, noisy in code: DATE, IP_ADDRESS, ZIP_CODE, STREET_ADDRESS, UUID.", "default": "" } - } + }, + "documentationUrl": "https://github.com/DataFog/datafog-claude-plugin#readme", + "supportUrl": "https://github.com/DataFog/datafog-claude-plugin/issues", + "privacyPolicyUrl": "https://github.com/DataFog/datafog-claude-plugin/blob/main/PRIVACY.md", + "icon": "./assets/datafog-icon-512.png" } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30fc304..65075bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,8 +4,25 @@ on: push: branches: [main, "rebuild/**"] pull_request: + workflow_dispatch: + +permissions: + contents: read jobs: + manifests: + name: strict plugin and marketplace validation + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install the reviewed Claude Code validator + run: npm install --global @anthropic-ai/claude-code@2.1.327 + - name: Validate both manifests without model credentials + run: sh scripts/verify-manifests.sh + test: name: tests (${{ matrix.os }}, Python ${{ matrix.python }}) runs-on: ${{ matrix.os }} @@ -25,10 +42,10 @@ jobs: # 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 dbus gnome-keyring libsecret-tools + run: sudo apt-get update && sudo apt-get install -y zsh dbus gnome-keyring libsecret-tools libglib2.0-bin - 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" + run: python -m pip install "datafog-core==1.7.0" "datafog-fogvault==1.7.0" "pytest>=8" "ruff>=0.6" "mypy>=1.10" - name: Manifests and hook config parse run: | diff --git a/PRIVACY.md b/PRIVACY.md new file mode 100644 index 0000000..4361c09 --- /dev/null +++ b/PRIVACY.md @@ -0,0 +1,65 @@ +# Privacy and local data handling + +DataFog for Claude Code processes text locally to replace detected personal data and +selected credentials with reversible markers. This notice describes the plugin, not +Anthropic's services, your shell commands, or other installed tools. + +## What the plugin processes and stores + +The hooks examine supported file content, tool inputs/results and submitted prompts. +Detected values are stored in an encrypted local ApplicationVault so markers can be +restored. Processes temporarily hold decrypted values in memory. The encryption key is +stored in macOS Keychain or Linux Secret Service by default. Explicit `vault_key: file` +mode stores the key beside the vault and provides weaker protection. + +The vault is shared across projects. By default it lives at +`~/Library/Application Support/DataFog/vaults/claude-code` on macOS or +`${XDG_DATA_HOME:-~/.local/share}/datafog/vaults/claude-code` on Linux. Configuration can +change this location. The marker index, vault metadata and Bash restore-ticket signing +key are not encrypted. They do not contain the original value mapping. + +The plugin data directory also contains its Python environment, settings, tokenized +shadow copies and diagnostic logs. Configuration can contain user-entered allowlist +values in plaintext. Diagnostic event entries contain events, tool names, +entity types, counts and error codes, rather than prompt/file content or detected values. +The event log rotates after approximately 2 MB, keeping a previous log. The separate +bootstrap log appends installer output, which can include paths and error details; +it has no automatic rotation. Shadow copies retain +content that was not detected, so they must not be treated as fully anonymized files. +Session startup attempts to remove shadow copies not refreshed for a week; this is +best-effort cleanup, not a guaranteed deletion deadline. + +## Network activity and other software + +The plugin does not send scanned text or vault values to a DataFog service and has no +plugin analytics endpoint. Initial installation downloads dependencies through `uv` +or `pip`; package infrastructure receives ordinary download requests. GitHub supplies +the plugin source. Detection and vault operations run locally after installation. + +Claude Code communicates with its model provider. Its own settings govern transcripts, +prompt history, telemetry and retention. DataFog cannot guarantee that all personal data +is removed: unknown formats, unscanned content and post-tool hook failures can expose it. +Built-in Write/Edit/NotebookEdit and Grep/Glob inputs can contain restored values in +Claude Code's local records. Commands can transmit data, and explicit +`restore_in_mcp_input: true` can pass restored values to third-party MCP tools. + +## Retention and deletion + +By default the vault and its key survive plugin uninstall so markers in your files remain +recoverable. `/datafog:purge` requests confirmation; a successful purge deletes the vault, +its key and shadow copies. Partial deletion failures are reported and may require manual +cleanup. Purging permanently removes marker recovery; it does not erase values +already written to your files, external services, Claude records or backups. Diagnostic +logs and configuration are separate from the vault. The README explains the alternative +plugin-data storage option and its uninstall consequences. + +## Limits and support + +Encryption at rest does not prevent software running as your logged-in account from +accessing values. DataFog reduces accidental exposure; it is not a sandbox or a complete +secret scanner. See the README's coverage table, known gaps and configuration defaults. + +For non-sensitive questions, use the +[repository issue tracker](https://github.com/DataFog/datafog-claude-plugin/issues). +Do not include real credentials, personal data, vault files or unredacted transcripts. +For a vulnerability, follow [private security reporting](SECURITY.md). diff --git a/README.md b/README.md index 5842f5b..12966ab 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,8 @@ Linux needs a working Secret Service, or an explicit, weaker file-key setting. I 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. +**Version 0.2.1.** See [Known gaps](#known-gaps) and +[Verification and remaining checks](#verification-and-remaining-checks) before relying on it. ## Requirements @@ -37,9 +37,9 @@ key stores block tool calls. See [Supported machines](#supported-machines) for d - `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 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. + the DataFog core project: `datafog-core==1.7.0` (the detector) and + `datafog-fogvault==1.7.0` (the encrypted vault). Detection and storage are local; + scanned text and vault values are not sent to a DataFog service. ### Supported machines @@ -80,7 +80,7 @@ DataFog guard: on. Vault: user data folder (kept on uninstall), encrypted, key i 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). +you to allow access, see [Verification and remaining checks](#verification-and-remaining-checks). 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 @@ -140,6 +140,10 @@ the value). Digits written directly onto an address with no separator 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. +For unscannable files, the tested Claude Code 2.1.299 UI shows a generic Read permission +prompt and may omit DataFog's explanation. Approving an image or PDF read exposes that +content unchecked. Set `unscannable_policy: deny` if those reads must always be blocked. + ### Names and street addresses Adding these is worthwhile: names and ordinary mailing addresses are a large gap in @@ -183,6 +187,20 @@ output, tool output and files alike. `123-[01;31m45[m-6789` from `grep --color=always` becomes one marker, and writing that marker back restores the original bytes. +### Background commands and timeouts + +`background_bash: deny` blocks explicit `run_in_background: true` requests. It cannot +prevent Claude Code from moving a foreground command to the background when its timeout +expires. This occurred in the real-host 2.1.327 readiness check: the command continued +and completed its delayed write. Its output still passes through the DataFog runner. + +To make foreground timeouts stop commands, set `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1` +before starting Claude Code. This also disables other host background features; see +[Claude Code's timeout behavior](https://code.claude.com/docs/en/tools-reference#foreground-commands-that-move-to-the-background) +and [environment-variable reference](https://code.claude.com/docs/en/env-vars). +Do not treat a message saying a command moved to the background as a completed command +or a cancelled task. + ### Markers in Bash commands Swapping a marker for the real value inside a command is necessary for honest work @@ -198,7 +216,10 @@ vault does not know are always left as text. command. What it hands back to Claude Code is your command, wrapped, **with the markers still in it**, plus a ticket: a signature over exactly that command text, made with a key kept in the vault directory. So the permission prompt, the session transcript and the -record of a denied call show `grep -c [[EMAIL_7KQ4ZM]] notes.txt`, not the address. When +record of a denied call retain `grep -c [[EMAIL_7KQ4ZM]] notes.txt`, not the address. +In the tested interactive Claude Code 2.1.299 prompt, the command appears inside the +full runner wrapper, including paths and the restore ticket, with DataFog's explanation +and Yes/No choices. When the command runs, the plugin's runner opens the vault, checks the ticket, puts the values in, and passes the result to the child shell through a pipe. The restored command is never printed, logged, written to a file, placed in an environment variable or in the argument @@ -512,9 +533,10 @@ yet. This is the main source of extra prompts and is meant to be loosened later A deny rule that matches that text, such as `Bash(. *)` or `Bash(* && *)`, blocks every Bash command while the plugin is on. The plugin detects this for the rules it can read and says so in the denial instead of failing silently. -- **"Yes, and don't ask again" on a prompt** makes Claude Code save a rule for the - rewritten command, which the plugin does not use. Add a rule for the original command to - a settings file by hand. +- **Hook-required Bash confirmation has no persistent approval option in the tested + Claude Code 2.1.299 UI:** it offers Yes/No. Add a rule for the original command to a + settings file if appropriate; rules do not override the separate marker-restoration + confirmation policy. Other host permission prompts may behave differently. - With `bash_wrap: off` the command is not rewritten, the plugin returns no decision, and Claude Code applies your rules itself; markers are then never restored. @@ -527,6 +549,17 @@ Edit), which swaps the markers locally, applies the edit with Edit's "must match once" rule, and returns line numbers and counts only. Claude is told about it at session start. It refuses paths outside the project directory. +The marker-aware editor also enforces Read/Edit deny and ask rules from the settings +files the plugin can read. A matching ask rule is refused because this MCP tool cannot +open the required file-permission prompt; use the built-in file tools or change the rule +yourself. Unreadable settings or unsupported path rules cause refusal. + +An in-project symlink remains a symlink: the editor updates its resolved in-project +target. It refuses edits if the target or path changes while preparing the replacement, +and asks you to read the current file and retry. Advisory locking serializes cooperating +edits. It cannot guarantee atomic conflict detection against an unrelated writer racing +the final filesystem replacement. + ## Known gaps Ways a real value can still reach the model or leave a trace. @@ -579,7 +612,8 @@ Ways a real value can still reach the model or leave a trace. 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). -13. **File names and paths are never tokenized**, including in Glob and Grep results. +13. **File names, paths and resource-link URIs are never tokenized**, including in Glob + and Grep results. Human-readable resource-link names, titles and descriptions are scanned. 14. **Binary command output** is passed through; text inside it is tokenized, but a value split by invalid bytes is not found. 15. **A value over 32 KiB** cannot be stored; a file containing one cannot be read through @@ -590,18 +624,13 @@ 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. +18. **Joined Unicode email addresses may become one marker.** Core 1.7.0 can leave + the second domain exposed in text such as `alice@example.comとbob@example.net` + ([datafog-core #272](https://github.com/DataFog/datafog-core/issues/272)). The plugin + now validates an immediately stranded `@domain` with the core email detector and + covers the complete joined span with one reversible marker. This deliberately hides + connecting text too, rather than guessing address boundaries. Restoration preserves + the original bytes. The upstream boundary fix is merged but is not in core 1.7.0. 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 @@ -631,7 +660,8 @@ Behaviour worth knowing that is not a leak: What ends up in files that Claude Code itself writes (the session transcript under `~/.claude/projects/`, its debug log, the `permission_denials` list of a headless run) and -in what it shows you. The model's context holds markers in every row. +in what it shows you. Successfully protected paths replace detected values with markers; +unscanned content and the post-tool failure window remain exceptions. | Path | Real value in Claude Code's records? | | :- | :- | @@ -881,7 +911,7 @@ Release notes record the results of the release run. ### Distribution -Version 0.2.0 is distributed directly from this repository. A public plugin-directory +Version 0.2.1 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), @@ -908,7 +938,7 @@ More settings go in `config.json` in the plugin's data directory | `restore_on_write` | `DATAFOG_RESTORE_ON_WRITE` | `true` | `false`, or a list of path globs to restrict restoring to (`*.env,*.csv`). | | `bash_wrap` | `DATAFOG_BASH_WRAP` | `runner` | `off` runs commands unwrapped and leaves only the after-the-fact replacement, which is not fail-closed and does not cover failing commands. Markers in commands are then never restored, and Claude Code applies your permission rules itself. | | `restore_in_bash` | `DATAFOG_RESTORE_IN_BASH` | `ask` | Commands that contain markers: `ask` you first, `allow` (restore without asking), or `off` (never restore; markers stay as text). Values are put in by the runner, so this needs `bash_wrap: runner`. | -| `background_bash` | `DATAFOG_BACKGROUND_BASH` | `deny` | `allow` wraps background commands like any other. | +| `background_bash` | `DATAFOG_BACKGROUND_BASH` | `deny` | Blocks explicit background requests; `allow` wraps them like any other. Host auto-backgrounding at a timeout is separate; see above. | | `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. | @@ -920,48 +950,39 @@ More settings go in `config.json` in the plugin's data directory 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 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. - -- 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. -- **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 - markers, and what "Yes, and don't ask again" saves from it; - - that the record of a denied call (`permission_denials`) holds the marker command; - - `plan` mode: whether Claude Code would have run a command that the plugin makes ask; - - `auto` mode: that leaving the decision to Claude Code sends the rewritten command to - the classifier, how the classifier judges it, and that a hook `ask` forces a prompt; - - `dontAsk` mode: that a hook `allow` runs and that the plugin's `deny` reads well; - - `bypassPermissions` mode: **what a hook `ask` does there** (steps 3, 4, 5 and the `rm` - check rely on it prompting; the documentation says ask *rules* still prompt in this - mode and does not say it for hooks); - - that `permission_mode` reaches the hook with the documented values, also in subagents; - - whether Claude Code's own rule matching agrees with the plugin's for your rules (the - documented examples are tests; undocumented cases use the stricter reading); - - that `~/.claude.json` records trust under `projects[""].hasTrustDialogAccepted` - as documented, and where that file is when `CLAUDE_CONFIG_DIR` is set; - - whether Claude Code's `Read`/`Edit` path matching agrees with the plugin's beyond the - 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. -- **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. -- Behaviour when Claude Code's own Bash sandbox is enabled (the runner starts the command in a new session). -- Anything on Windows. +## Verification and remaining checks + +The released 0.2.0 automated and headless results are recorded in its release notes. +The 0.2.1 readiness work adds interactive and supplementary real-host evidence in +[the host verification report](docs/verification/2026-11-18-host-readiness.md). +Those observations used Claude Code 2.1.299 and 2.1.327 on macOS Apple Silicon; +see the report for which version exercised each case. Candidate certification requires +fresh results for the final code revision. + +Observed paths include allowed foreground Bash, marker approval and rejection, +interactive bypass-mode marker confirmation, blocked prompts, unscannable Read prompts, +Read/Bash/MCP-edit examples, built-in Edit result filtering, finite stdout/stderr +collection, explicit TaskStop cancellation and timeout termination with host background +features disabled. Default timeouts instead moved work to the background, as documented +above. The live driver's cwd check covers carry-over between commands. + +Still requiring separate evidence or explicitly outside the tested scope: + +- Further interactive plan/auto behavior, classifier handling of wrapped commands and + broader host permission-rule parity beyond the tested fixtures. +- Alternate configuration-root trust handling, server-managed policy and MDM. A policy + the plugin cannot read remains outside its permission matching. +- macOS Keychain locked/denied, SSH/login and rebuilt-interpreter access. The optional + live case covers creation, repeated reads, timing and purge, not every key-store state. +- KWallet and locked Linux keyrings beyond the private GNOME Keyring CI cases. +- Final cached-release startup, upgrade and host MCP project-directory handling. Local + directory loading and direct cached-launcher checks prove different parts of this path. +- Linux live UI and cancellation behavior, other terminal renderers and unsupported + hardware/OS runtime behavior. Windows is unsupported. + +See the [readiness inventory](docs/readiness.md) for gate-by-gate status. The live driver +loads its project/local fixture settings to avoid unrelated user hooks and plugins; +it retains the existing login and DataFog MCP tools. To run the live check on your machine (about 29 short headless `claude -p` runs in a throwaway temp project with a temporary vault whose key is a file in the temp directory; @@ -982,7 +1003,7 @@ Results land in `.live/results/results.md`. ## Development ```sh -uv venv && uv pip install "datafog-core>=1.7.0,<1.8" "datafog-fogvault>=1.7.0,<1.8" pytest ruff mypy +uv venv && uv pip install "datafog-core==1.7.0" "datafog-fogvault==1.7.0" 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 ``` @@ -1005,4 +1026,9 @@ All test data is synthetic (`ada.synthetic@example.com`, test card `4242 4242 42 ## License +See [Privacy and local data handling](PRIVACY.md) for storage, retention and network +behavior. For non-sensitive support, use the +[issue tracker](https://github.com/DataFog/datafog-claude-plugin/issues); do not attach +real credentials, vault files or unredacted transcripts. + Apache-2.0. See [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..d090ee2 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,20 @@ +# Reporting a vulnerability + +Report security vulnerabilities privately through +[GitHub's private vulnerability reporting](https://github.com/DataFog/datafog-claude-plugin/security/advisories/new). +Private reporting is enabled for this repository. Use public issues for non-sensitive +bugs and support questions only. + +Include the plugin version or commit, Claude Code version, operating system, relevant +configuration and a minimal reproduction using synthetic data. Describe the expected +behavior and what happened. Do not send real credentials, vault/key files, personal data +or unredacted transcripts. If a demonstration needs a sensitive artifact, describe it +first so a safe reproduction can be arranged. + +The current release is supported for fixes on the platforms listed in the README. +Older releases should be updated before retesting. No response-time guarantee is made. + +DataFog reduces accidental exposure of detected values. It is not a sandbox against +malicious agents or programs running as the same user. Read the README's known gaps +when evaluating a report; unexpected exposure on an advertised protected path is still +worth reporting. diff --git a/assets/datafog-icon-512.png b/assets/datafog-icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..4326ad46cad89a17f328f200dea418927da3eeba GIT binary patch literal 13146 zcmdtJ^;Z<$6E}VrL=*)KlyV6PK|(@6mo#XR1}OmnkrG5!atVDSN~b8T#7gYaouZ_K zQVU2*2}^ef``q<&zW>4Zm*+Wf4(!djGjnHNGk5l_)_rAK8WtJ=0IjOZT^#@@;J*~$ z#Bum%)1z-6{yF|gUHL8`k$=)^u`vK}0M)y<^gNQ5Mm>F!+%4zUR#rZkV0nhBoW4g3 zN=r?&z9iMr~kMTcse^3mndqS2zj7uB}a>gM@njywK6LJWK#OMdX23ICx$ zcl%tBX|RydJ8KiH6LLVdr(@%nyrV6$<(*RchrP~@4NuZ5!A_ZOMn&;%ci-+6PhTaz zt2i9)g0EszN~AN2+c`dNl+%I5`tR#vQtnc7&co!e3Tn5 zt}3*TGy5l660{a(M9E(E#E6x38~-9Qld_}Im8ngsPl?eeAQt~rgGS9aRyvGhSdi`}XAFm;5-MWQneU&wOu#jlEKrX4J&mB^phlrkzjJy2@;cObhi=lT9+=ru_($7H@T9M> zIMmq>Tx7q*%xv@mnVqBsiu(H8oNPYZ&x{s%)mtyWa||Tj16s`&xiMc^WY4JQ`#N}d zcr>BYbd(W;|7~w?-$f-<5STWe7tJPL+C((G^=$KP+THF=|4OM@MW>s?2biBMFW2>K z)Y7Z(zj50>Cj%7DilDe1jz;cw+A7hrr??`qv06Yly{@{N_i^W8b3(+Q#SRQm_$j6y zO^UCxmA@$}vRXvEp6O5F5;Yrsh~&I>crC9(K2mQ6MGq`=^D?M${VNglTk;F2d!p$e zskaV0_jtTFzik2AJ!(V`wAw>cVmH05ln?5C@k|pG0oQ<2vaI`q`Sa0Z)2LH`;~Jf@ zm9N9!C*ybUuNYz)F8UAP56j#4>jmcN2u1))}(mHCec2!JJ|H~ntP zPIYwccl1TzPia8E$4Mf*lrs_$p-RJ5SDOtSXbvpAy0uTD1r-^wh5LDr##&x_?O6=5 zpD-~o5n#wa!bTqoJ>H@O51Z`USvFQ$s1M{Wl<r$AOky=%PCR`8vP#KOf^wZQDwtg@J~dSr{klQKg%RK2ym?3|H=x6>s64s8`3&gEeDh=jgMOxE-_YyT>}jtZLBuGrz;=G&!Jik zVmpe;osizFL$-@d`0buDJpZF<@l{r8ub6DrvEX<`lm$owkUHfYWyJxr1ysETR3#eiSi zE6yjdo3g6q)m;>zf%h)=p`$+LaJsQ$^A^EUQb&&}?OAsUZ}(2!mH92Q{35BkTWgA| z>U`~dAMc+eSPtl3r%Ef$b--eOa79=4Km`M34Jxx;3stYb{q5-6F%7Cr`osq`WMz|6 zR%9=K5GFIBHA>3B+2P6i)MT$#bfo&ThrqbH>P3p|Zthp|0F3NQ0D;l%BK0=hW2X{dYt@Mppv>ZAO`qVx7P|iy<=rd?(T= zCD2>HW^J?Tmr(7V_h}R`?(SjQyOzvmE00J3Fr-vwX4P?`7%hInsxlhc7quac9K zO9RKA)t&OUO?U9K3`1?yu*2&V(|(@cQJi z?KkIr51thR&vK0Q|YL zMV)R(?S05zneqC1lLhg{M@>inX&Ds&!mB@L!sF!1`hN#N<97Cr}n$A$E&Naym-?tAj@b2XmY9plg|{L30W{QLrh1g7D8 z$~d!wr{9MLiZG8%+}*3U?qH&Et@=y=6yU#JNFh}P1O!YQNX2fQ@YnDrg}s8iQI+}) zB}B|Vx?>auO57J^C%k8s^ETnBzTlWV31M_>%j4}zMJ$L_*^QN(yOdz!?npan#bmTK z>r_MK$rJ8R(Jc^jI5<16ELOS;unxK*3hGGgWkq-3p6I&GpwZFMLdVqlY>FQPL(hXm zXN88APXjQ0Z>MPG(7sG_Ob=1ebERnXEWBw#0+^aotgW|XcV`8-?!G<3J+Cpecnpqi zlFZz4F7kZTOw}OX-i8i>I|k+Xmg1_td);R`Kf}R`E0O))#Wau$>-$a0*iwotJgdJ_H->T<2z-nzEWt7kD75=`8`vw1VBMfvBz#@D$%p?H5CVRlhHY4 z45#3h@jtuE7b_pRXVH%r044{yB51t<$M|KXqx$yEFT}C#dMC|p^uV9Wq;C+Ec|LyU zb8S>qRK&$TT^TP;F~NH9{bnb5-&O+;<}u`I5f@lmS~@9jEGnEWi5-Ib9zD?TbWoR8 zR#JLL@E){L296o)W|#gV0H3H5t#8TtQ5f5cA-E9f@FqQZq3&V7qMvt!J!#TPOG|IB z<-|l^-8e^PWt=VA!um5Q`}@(~=y46b+90x6Grvpi$8Gug&Qn-4t&%@4&5`Yn*>X@m zKY%h3Rdt`0h4!lzd$;GV-?po~j|Sp_8nJU^pAq=?*oMk^RHoKu0Vb=lsGYk2q@8){ zJY4JCo$0%pKw+VXfGzjl7tE3V!iF3Q7d+3Rzym>O?FyHGY%KYE6L7L)$U%c$B9J#P|LjW-iL0YEH5)A@j8uC{(}!5$kx z76^0g-rx8X?!5uix$9>j3G%s#U4HZPi>?8oa3`%J)G+iwKlUgrGKC3m;e;{f#CxM@ zkhlzW`~@h9_K-ODbZ$@bl~o&FM!_ZcfR*_*)s*aq3l%OJV?WYfBY)`|)@%G!(JOp%uh2uU*#pmonmVw<<>m2J zM)&pf6x~mi!@X^bLERM1j*GiMSX0w^(9>0*t={@s!n)+Ec(A8VVAQ#0z6w95)}WG7 z<07SyBIDJ}w?|h--~D5eXo>3| z+^yKB-^tEjdBb~!*G&1UJ&rRy@lgu?H0##g&_}PE?w|OVGC76{6HzeEH_!&$d5l>sik?VFCtZEC8Smj+l!xK2>dVV zX@qx`EQ^lef0S~;zY1gf%ME+HWab^hxOBc~fptN)2;wZI)WWO@-RGiDjp(GJvVw}w z%6_Y#Q#|+6eB|Fxh3Kcaxyxi!PjTvtrbL_*ch1bembsNYQ=)_adJIr;Xv%c=Zb?1N zmtOYB{k>K}yb&NKA(6S_bKt$OLUc!FTHKCaR`b}O4=%X6+YoV1YTg86CyK*He-T^{ zybZ&T+1ban#5(tETxk6C6k8um z7yHoI>N*GEc0Zc7ehPK><_YD?UgO<=W1m(p8F;c?F%MA`yx0r*hzks)3X9OJ2#*mL zV=6@ob*0-FQT$yjfOgujeO2s^Rmu6p@r`9;Wi7j|ZjhD-Q|UE+5qb%YP{g81>kEq(6pIjSy#stPYpMryF4r}X4oY1sY zhQFjODKF2hs!~(lr#4k?8DM#k*E#F{>*W zEg_+M+X5Gaa6&oRIH5LyW9ORxl-qL+w^_>{8^jlAKX3iRtk&>O8x&1@rpT?HV*jyh zR&A>Mg}1cix&Q;6!xNWQbZlrK&!LjjgHfM#>Jo8By?IEV4x;R(dyL?yC*fCr|Ij?@ zc+qCF)L0IybJZ7gXeg%QYM#K2UCR6lX|^8OXZW&VnlbI70%wvOvSQ{jL9{?|XT-bw z#j>M2(&`TNqm(hWxl9_<#aD4D_}>NuqbW0+n5zN;TPdkt@uyGa#MVSI_8j=m)&{pc z!l#=Wn5pas>HD-Jgqy^bNEN6&`?2ui+lax8^6{+~`rH**zskWfr^K=L?f*X&7a3@FE717PD$XyJ-jFh`;@Fz zoD1`_Op2bx9_~Z`Nsk>#zCQZiC%aN(GU@UR6TDlg_WCH`9;QMp?}l@CBGkmRpwaOm$Jok1O6&$}G;LxcLMEAmb!r=5JfBqH&h zNKb9-T&Ok>b6G+YTHi=bbKF>cP1$Am+(%dDn>lM_rnD93&s6a{h}H&)j=%JwIqhm& zn-ymLYX*;xD2;MAGZNE7DXd?*C(!l{4A{49FX64y{2%&#B_=IZ^H}#W{hm5iaKU-f z)jw1VNd73qenlT+cwlRY{Z#lS24mhf$Wvfr_+MC#2fx!Bih_V}*=jRog@C|2mP@!#k!fyzGj!uuCWd)SXreLPq?Jze%C+@ww00;?wc~sl$M;OX+VXF+7FIR zppIX9V&^2hD<^B!*RkivaRqhz(wJnU^Alu$zrNygD<%d5D=Vun&IdK4DotqdM`>=Q zufr-XT3{Ib(Rv03RpCJS)6dU2_Bk|F-Nq4`BnA9`JowK;Fos4(U4D3lZO`zJP3rj? zmVl(3488o2@+7p#Uv|erkD9cDsU91S@~bvx%6#^4v4VByfr)Oo_LE^oQ^5fGz6f5JzPaw}qqB2XoxEOEM5D;gr6A}_aH9Ge)?(yNv z<#T){{HnS&DFcd#!G_&$8E|ong-yFF2gv&y;Z)O&9>eXn$1LFbw5Mt5s>1>G{bW~N z;AQCfmBQ8XdXs}47wo!pQ)~i7ap{JnPe+??s=3WE&>Hxa|DihTN8o7j;;|AIPC`;r z&Du}fayy};a}oYRM6)S06o z)CF_Xdm(Q-6lQsQ4diDZvM{Fu$HtKlHxE~-BPzoKWIU%=*!Xiw+3)Ya(-d#u^|9ga z93@ExP!y=jd;L~TmTAKv+BN)0XSa}7Q#46)hvPQpQ-bG?IsTcE$h~sIsf-^Q4(KfR z7tAsG4h|0ZbPnZ#fq~5*QtYnCsb~XSKX$fPt&)y{p)fW>-eg+8$cVvTFeynUbH#Vg z5?UIr@x5(#331(;TsgW-AB<;|E}~(^$5XVkmQ<{OXzl6Ml*PTGrmqSQ5L&?O*~o6V zt&!aS&blTzBnGH^Jnbh)eGrJb0BySu@r$#A$D4i%_5L

}FU#<|{P14^&ehs${2X z-fR%y?deJFz*g8Qz2gHWk@vA%GuKFQyu4S;pkYt`kl4#8M^eOb$Kcbg9Xr)hWs0-T z@={SGY-Ns17iUpDq%(qy``Nx;B)8)ym%q05jG!I)u_==WGx^;72jnL~TheJvjkI=8 z?Ft{_M1i9Der=_MMv?36yZ>^CEWR!1H#+gg>e=Nxk=t&I1{xY+#2XJ<78mp6c5G7# z^S#T?JBhfAxD+*GvkMYA8==G-3b!;4-knQ=3Vca5Q^#wvDPGUq5Zj!kM0nWS)=_z?#Rn>?qn9|pw!;P`v*jJVP#V>v@HIHsWPtQ5NgWmmNnb~W%v^*$e zZ&ya1`0VjB^Iy_q3PE}s6+us zw5F?Ye=4t8>a5yp(4Yxw#7`Xyj_cQ?JGwi5u)I@hs+77`jh7T!U~3EQ^()!AH_p)Xi-=Q-kwZU$fMu6i|IFKb#kA$wCmw4z zKN}S(rOH<7%$Ahu%5L*(Saj@+$VM=QmV!p7M%CVIqFZOFp}@Jf72&$jXsIF>Fh-hk zdsfLw)`h&P!{@i%+#CPU{*1i5d7q)uMnJZ9foSsG4mtJOkm?q~g+n{)hrXeC=HY>N zNwt*}mb$2E(&9>mVQO)y61X^pfgiqw20CHms0gtrRqCMLY(PpnmHm$CzVb{QmYE!9^~=} zB&(@g)#b0n_D4zNPT2`$ZCCyS?f&n1jsXRr4Wa!B4)U7-;w~A>`}2|Gf-^8g^ar2d zzh@N4aS_EEGWP#}Xt35G+CMF%Wh%${vo2brH0NrrzLEaNC)aaaZU|b15QI*l_cW`BmU(b~Uc2m^!t0ZPE *d+=2#1(>)a#eia9#Qr zm}TXYJ`6h8`hDu!Gc}H&_i^ti-v<9Twm(qrx=QUYGe0z*E;X`!+>yOZQD*(97{Cc=Vh2FRm}UK)MP}(*9y)h-fiu z;q!tBXYq;kIy;CxCyF|k~F0ofP%F>sGcNLVbu8@kuim*jnK+u^TJ`A56_-91S-t409@m0c=9 zOOJexqy&)x=Ue!|hcsaQXLV9;&u;vmOz)?naC>{61X1$nJKxp6v#>l8hUxd>x;sG- zJHwzx;}0g=FjsYe8u&lDE{#!|nu@_&#h!)=na69m)e}dhA2XoR**$Sl z(Z$}chMHZ`(E3(e zk0%d;=(p_NzV-D~MDV3~$lztoy!-k`vpr;%|Jn4WCLScaTvobrP)Q?q{mV3PW5QEO zqq7r+sM_l4A&*YB!;G6~^kduZKhte7EJ)`5d0kyR7Zn{jMjSXGIjXjFOE0H7|M3!@5|Y_SqX6o+=ZvpQw;wc_ah~! z)c=3_^C6#b5dh9pl4}9}uL1&=1jI||s68&@gYO1DT6_Pf@G}g2YqV5SY^Ry`nO(bg zFcAA@_SQwWWf&N|E3K*dl-a}sn+R)w;RID$!|fDo!mx3F-@xah939SxS28r;H)K3h zuqte>Shl}W=1=;G70(ThVk zvQ?*vbPv;zW>Eij-PPx=9QK%h^fx9n-M6V{Xf)b&RXMG1pzm|BL&R-MIc1OuQyGeD zcW)<~c{7Bs^1hi+eYEDkL zGUxGS)N%jQ&>r%$MdW6~dJQ-n!e;&ym5OkL1tm1B_72W*qRr%XW~&khL+K5K|K%0| zxAO}N3wqkx&|_+Ck`ecH*QTW$=0E9DXf47-MWT zaMB2CjCuplAPnPkg{3lM!dd@ln^0{e4+|d(x@E}L$q zTZm$MaML5`04iWghB7XW0dO$pJdmg4yGow++s7W^`Y|V`9eoTirhz;tai-$V@|rXG{AmwX?M;J9@#oc%Iqzlefi&Etu4Ilo6*P8 zGI$IPOB1XqILM1JzfVlmz1lgWu2A;a_Avw!F67*d&p2Uo-i{#ZA1xuRjsU^5Pi0o5%w^z9lMX+X`eh?(u`uzMPwNQq$mko;kWjYZ*XI6Z0nx^VGQ&(UD={(ceOxS zt8s4B`SgSjmR~rI5!%&szTRo6FyYm@-H4}*eYL^Uu!Cb^Sukrs(AeAA%`bjQr7HH1 zZakqt7Zw(7=jay7sdcP*@q;)E%ca=~`dAJn;Ob~^Z`@|BBkf)$a0v#=l+%G*7?{L= zVjrw87NBEeEbYBpkwE=XO9kG}oKXWJv?03c5bq$7y)Yd@Q$hV|*5<+mAsL=eXRF1bvwPxK=(gOq${3hJdo2YG!W&3T=$l)NHeTC$A;R zgy7?t@*FlW$$h=FrN(^@nolCx{dIKYL6P5FrL=iNF`**EW~ku=4Wxsf_AO?A@46L- zXO^m`LN*c-6AAXN{m@u?T0?>jctp)cIlDJvRk$HYz7W#FKXB!h?P3wN% z^nqPwkKIs7|AMhjTbw@BwK!9w$#VuAHwGG`qZvRs)UDsYFFRl<0gX+6Ov!H)^t*hY zGu)pZBZtq*Ju%-#Wnf_aPG3_AYlekwRB@Zr4n1fXXlrSSr<^6bX^z64SX&!@@`Shj zcHKn@$;k_v(LF`o6igtp)|!y4nmM#3V)f3^_)QIX==JaR3xkDsrm70Sz0;>_1nnB_AYzD=SGtx&>ZzXi zWzfU*^c;C&@oZe~QH>!XFVnRY)$H#IWS14S21q$CO=ZkD~&HK zEt%Es{)!g@TwJxi0}BB))bMDYR+;rReLL4o0C!vQ5vkSWG92x^@o~Dxp^M~@P9cJl zS9q@*ay?h4S&g8fIYg;ksQw>9N38W7ZDli?>op-oC<6H6!q0;52+T#X`2O$d+ z@F(V_;}0fZQ&~7VI;!?yUD?Pr1`!f|q9P)ZH6syHY=}tfPh;$=#;yOPAf>cjOgxl< zTYBxT#^xOf+Ga!DI%1N&32R;cdeOIi21yv}{dzUy?}{);iBzuJ>rkR^s{o-$S+7Q8 zjNSK-aJ*b6PXE7a(g&oP4rRb?L_93ZAdK9H@6rq>t&VoG$Hr*qmYi~+_}SUY#5y2j z({A9}@Q2TM=|}Vskr}HAzJ@(KD_5bim=@88($cYYPe&yRgDdwp!;IcaKnC+krX0Qs zWl!kb#?6r!Rc(trAu+8XK`qCRr*v+9`RKS^AR=3hoVI?7YPHH)if0^s!v(kKmdiOOyi_)k5gmN zkgT6yxW*&<@0bk1C+)##YULp6l##`lGCj~GM!MZ&W5@~#^R&XP`AR2Vc`R{q_4Y=w zt}cA&GyFah&tO)~2bJv}J`0dX` zlzjKE?TymO@2keu+ecw}o|*wWuriB(uX)gdgxNE-zP9ol2>;G+O0VabZ=zU%^(s1| zXSNLGV^=P`IAsRha?0H~kpr5lD5F0ZN}x4;QPy*Xm5nW>b0?hUA>g(vs`vZRUZdOd zGUO0;|K}rcFd6mbD-|=3yAJI2DOh2)>cB)BnAyPl@PKJPz4F1#HC?J|nh70PqxU+8 zxIkSga|WDwqLj+Ux=4D!={{cq{w&S}Tr+@$cs#YEh}{g znLfBz)I5h$HWKv`OA4+%toVA;FJ5PpN+J5<<1BguDM!Df5wXUz1W#xnen<_Ri#lkg zewgqaIsJ%d*%xK36_OXrV`_4dwUH`6kR zrjSDu=khYfk&yXF!mR;aSGWhcwh8C;Gv6f;3awSpc!-|SRlnXb?%O5*kj}0yd`I^^ zOkovS*UEH+#GvC5n`o}d2iP$H~Ze#!I4XM8@xo4f-!$~*BEV0 zVQFd`Jjv`do&4PwPqh+XE3Sk9kHWFRx7gaRI#%#6( zOQ<={D1~j-!C{)I0u(%%f=WQRZ=ip}(qU_yN52vtl+VP^>eHC=|BAJ_O>7JScedS5 zoh+xOd1Rrp3oP)}GI)pUa1N*6KKw}JFwwt=1;S+>kL_O=nrzG&>iFvQu&T|!RtEl` zw%$j%uMAp@OTkjwz@kft3N4eCF@jO|fo|Kw6>=dlcc;+@%}}_|vuuq`6HTLVVEV-O zh1Vx+@l^LkgMo`Yqr&`)sPi!8>~n|ruxkw(S^lQCzC`|mv;L<_|7Tk4RH@1AXDH=# z*mRguJ|H!tBYjTlA#SvkptpQljSo{Y9uq8KY4tZj)$Mwv!+w&Oj7-gMl!hEtAyA1< zNWkMx>*Ia&dg`MXo+nd-iP*TG=51NN7)O`Y3Zh8hnL!GdhYrf!zQp+$r78ls0{lFE z`-Z%zq{wO>kt2{{7xtSd?+6WS9K~dmlXZpfO$%n6R1Vz+Poak>8D|8sNjI4>#*$mgw?2%-^V2wk$7GURD34Uq zY?n$k%01z?r{}!#l6a#DhS{oHqoWd{L`=i(z72Ej7@7?<2y`*!Ui&^w5=Hq;-y~T6 zixP&Vx7lE2l6Pj*R~6ygA}qz!%&@w!!{p#+Eat8{JPCyw8^FkY z5Ggu#r}I}1o3zL3L;_qloFdZvq551M(Pqgk#df)9VC*XYZwMx1{l7+I8kuD6Z_ie9 z9Ui9RDdSk-*C?FE%kxpu*UP;)y^Bk?{WB7oIl&nZ16?t%Tg{hZe_GY`XhIyB{2r-h>jpqSIMe~rN}@z%+|bU{>Q1w63p7Sw{@a~ zpD*7~XeHIaFJHU}lBxgYk=4|G-NYd=%rV{Cm`B$kZhw=G`&A0MLBLjV8( literal 0 HcmV?d00001 diff --git a/docs/directory-submission.md b/docs/directory-submission.md new file mode 100644 index 0000000..18f0871 --- /dev/null +++ b/docs/directory-submission.md @@ -0,0 +1,96 @@ +# Public directory submission preparation + +Audit date: 2026-11-18. Candidate baseline: `3c41b49` / v0.2.0; subsequent workspace changes require fresh verification. No directory submission or publication was performed by this audit. Publish only after Sid gives the word. + +## Route and old submission + +Submit the repository root of `DataFog/datafog-claude-plugin` as a **Plugin bundle** at . This plugin has a local stdio MCP server, not a remote connector. + +The existing submission is already in the current portal: [DataFog review](https://claude.ai/directory/manage/plugins/b9ad3ff1-41bf-4162-9a1b-7feb8a4a6d36?tab=feedback), ID `b9ad3ff1-41bf-4162-9a1b-7feb8a4a6d36`. Read-only inspection on 2026-11-18 found submission date July 2, status **Needs changes**, and an October 5 reviewer rejection of v0.1.0 / `7a154b2`. The reviewer required exact dependency versions, explaining: “That code can change after review.” The page offers **Resubmit for review** and is no longer scanning commits. Resume this submission; migration or a duplicate submission is unnecessary. + +The September 23 check also reported warnings for publisher-name similarity, missing icon, a README download-and-run command, and hook usage. These are historical findings against the old commit, not results for today's candidate. + +Settings inspection found default-branch tracking, a populated private contact address, automatic publication enabled, and all three app surfaces selected. Authorized readiness changes were saved and verified: automatic publication **off**, **Claude Code only** (Cowork and Claude apps unchecked). No resubmission or publication occurred. Contact ownership has not been independently verified. The collection/transmission switch remains off: its helper specifically addresses remote MCP servers/HTTP hooks; final form answers must distinguish local sensitive-data storage from publisher collection. +Keep auto-publish off. Select a release tag containing the reviewed commit, record its SHA, and run portal validation against that exact revision. Local CLI success is not portal approval. Submission, security scanning, reviewer approval and publication are separate states; passing checks does not itself publish a version. Record each result and the public listing URL after publication. [Submission lifecycle](https://claude.com/docs/plugins/submit). + +## Repository evidence + +- Repository is public (verified with `gh repo view`). +- Initial Claude Code 2.1.299 strict validation passed separately for `.claude-plugin/plugin.json` and `.claude-plugin/marketplace.json`. Validating `.` initially reported only the marketplace manifest, so both explicit checks are retained. Final local CLI reported 2.1.327 and strict plugin validation additionally ran a directory subset with no findings; safety scan and policy review remain portal-only. +- Baseline tracked tree: 62 regular files, 802,853 bytes total; largest file 77,973 bytes. No tracked symlinks or submodules. README and Apache-2.0 LICENSE exist. +- Plugin files live at the repository root; hook/MCP entry points reference `${CLAUDE_PLUGIN_ROOT}`. +- Three slash commands, four hook events, two local MCP tools, Python engine, shell launcher and bootstrap are bundled. +- Exact-pin validation: 24 CLI/plugin tests passed with one network test skipped; that network bootstrap case then passed separately with `DATAFOG_TEST_NETWORK=1`. Ruff and `git diff --check` passed. +- Bootstrap now pins `datafog-core==1.7.0` and `datafog-fogvault==1.7.0`, matching engine constants, pyproject, CI and documented install commands. This directly addresses the prior reviewer request; final portal confirmation remains necessary. +- CI parses JSON and runs shell parsing, Ruff, mypy and pytest on macOS/Linux with Python 3.10/3.12. A new isolated strict-manifest job uses Claude Code 2.1.327; local execution passed, but the changed CI workflow still needs a candidate run. See [verification and homepage plan](release-verification-plan.md). + +## Directory-specific remaining gates + +| ID | Remaining work | Completion evidence | +| --- | --- | --- | +| D01 | Existing submission found; resume it rather than migrate or duplicate. Reconfirm push access at resubmission. | Portal ID/status recorded above; no migration needed. | +| D02 | PRIVACY.md and manifest link added locally; publish with reviewed release. | Public policy URL must resolve after push and match final behavior. | +| D03 | Support URL added; SECURITY.md and private GitHub vulnerability reporting enabled. Contact populated in portal; mailbox verification remains unproven. | Root verified GitHub private reporting API; confirm final public docs and reachable contact. | +| D04 | Provide three runnable synthetic reviewer examples. | Read/tokenization, Bash output filtering, marker-aware edit; expected output and disk-state assertions. | +| D05 | MCP annotations added by implementation workstream. | Focused MCP tests pass; final integrated suite still required. | +| D06 | Narrow all listing claims to detected values and disclosed limits. | Manifest, marketplace, GitHub About text, homepage and README agree. Manifest descriptions were narrowed in this audit; GitHub About still calls it an offline PII firewall. | +| D07 | Portal now restricted to Claude Code; keep unsupported app claims out of listing. | Settings saved and verified Code on, Cowork/apps off. | +| D08 | Run a clean cached marketplace install, upgrade and uninstall scenario. | Exact release installed outside source checkout; hooks and MCP start; settings and vault retention behave as documented. | +| D09 | Establish dependency provenance/reproducibility and bootstrap failure coverage. | Exact resolved distributions, source/index behavior and network needs recorded; cold install succeeds on both supported platforms. | +| D10 | Assess permission/sandbox integration against directory policy. | Interactive verification report and reviewer explanation for wrapper behavior; no claim of sandbox compatibility without testing. | +| D11 | Portal validation of final pushed release; address every blocking result. | Saved finding report tied to SHA, including any reviewer holds and responses. | +| D12 | Refresh release version and final CI/live evidence after fixes. | Tag/SHA, green checks and release evidence all describe the same candidate. | +| D13 | Submit after readiness gates; track review; publish only on Sid's explicit authorization. | Recorded submission/review status and, finally, reachable public listing. | + +D02–D05 reflect policy requirements for privacy, contact/support, sample use cases and MCP metadata. Review also needs to address the policy's restrictions on sensitive context access and interference with other tools: DataFog deliberately scans user-requested operations and blocks some calls as its advertised function. Explain that scope explicitly; do not represent local testing as a compliance ruling. No DataFog cloud account exists for this plugin, so provide synthetic fixtures and installation instructions instead of inventing test credentials. [Directory policy](https://support.claude.com/en/articles/13145358-anthropic-software-directory-policy). + +## Portal scanner preflight + +Check the final archive for valid portable names, ordinary files, contained paths, supported readable file types, no OS junk or rewriting Git attributes, and size/count limits (50 MiB archive, 256 MiB unpacked, fewer than 10,000 entries; individual files under 5 MiB). Reviewer thresholds include 512 files and 256 KiB non-image/font files. Verify unique name, manifest, README, license, component schemas, front matter and absence of real credentials. Launchers require exact package pins; registry overrides and opaque execution can block or hold review. [Official checklist](https://claude.com/docs/plugins/pre-submission-checklist). + +**Expected holds, not confirmed portal findings:** the MCP command uses `sh`; its launcher invokes another shell file and Python; bootstrap installs registry packages. The launcher derives its root using `dirname/..`, which could trigger a containment finding even though the computed root is inside the plugin. Do not redesign working bootstrapping merely to suppress an inferred hold: run the portal validator and resolve its actual result. Prepare a readable entry-point/dependency explanation for reviewers. + +Hooks are ignored in chat; local MCP servers also do not run there. Cowork supports hooks/local servers in supported sessions, but DataFog's OS assumptions, environment variables and permission semantics have only been targeted at Claude Code. The portal derives supported surfaces from components. This creates a concrete listing/compatibility risk to resolve, not evidence that Cowork works. [App support matrix](https://claude.com/docs/plugins/platform-support). + +## Brand asset + +Bundled `assets/datafog-icon-512.png` is the 512×512 PNG linked by the official DataFog homepage, downloaded from `https://datafog.ai/datafog-icon-512.png` on 2026-11-18. The manifest now references it, addressing the old missing-icon warning. No new branding was invented. + +## Draft listing + +**Name:** DataFog (`datafog`). + +**Short description:** Locally replaces detected personal data and selected credentials with reversible markers in Claude Code files and tool output. Uses an encrypted local vault. Requires a supported Mac or Linux machine; coverage and failure-mode limits apply. + +**Source:** `https://github.com/DataFog/datafog-claude-plugin`; plugin path: repository root; branch/tag: final verified release tag, not selected yet. + +**Documentation:** `https://github.com/DataFog/datafog-claude-plugin#readme`. + +**Support:** `https://github.com/DataFog/datafog-claude-plugin/issues`; do not put personal data or credentials in public issues. Private security reports: `https://github.com/DataFog/datafog-claude-plugin/security/advisories/new` (enabled and verified by the root workstream). Portal contact is populated; mailbox ownership remains unverified. + +**Privacy policy:** `https://github.com/DataFog/datafog-claude-plugin/blob/main/PRIVACY.md` (authored locally; URL becomes live after push). **License:** Apache-2.0. + +**Supported environment:** Claude Code 2.1.295+, macOS 11+ Apple Silicon, Linux x86_64 glibc 2.38+ with usable Secret Service or explicit weaker file-key mode. Reconfirm minimum version with final tests. Do not advertise protection in chat, Cowork, Windows, Intel macOS or unsupported Linux. + +**Reviewer caveats:** selected structured entity detection only; no general name detector; ordinary unlabeled addresses and many secret formats are missed. Post-tool hard failures can expose raw results. Built-in file-tool restoration may enter local Claude records. This is accidental-exposure reduction, not a boundary against malicious agents or same-user programs. + +## Draft data-handling answers + +These describe repository behavior, not final legal acknowledgements. + +- **Reads personal data:** yes. It scans prompts, requested text files and tool output locally to detect configured entity types; marker-aware writes restore saved values locally. +- **Stores personal data:** yes. Detected original values persist in the encrypted vault so markers can be restored. The default key is in macOS Keychain/Linux Secret Service. Explicit file-key mode stores the key beside the vault and weakens protection. +- **Retention:** the vault persists until explicit purge; the default retains it across uninstall. Configuring plugin-data storage changes uninstall behavior. Purge deletes the vault and its key; it cannot erase restored data in project files or Claude-managed records. +- **Other local records:** marker index, encrypted vault metadata, restore-ticket key, tokenized shadow files, diagnostic counts/logs and the private Python environment. Inventory and exact retention must be reconciled against the final privacy document. +- **Data sent elsewhere:** DataFog detection/storage has no hosted service. Bootstrap downloads dependencies; user-requested shell commands and tools may communicate externally. Third-party MCP restoration is disabled by default and can expose restored inputs when enabled. Claude itself processes the filtered context; do not claim that all user data can never leave the machine. +- **Under-18 audience:** intended for developers, not specifically designed for minors; final portal answer must reflect publisher intent rather than an invented age restriction. + +## Reviewer examples to verify + +Use only a throwaway project/vault and the committed synthetic fixtures. + +1. Ask Claude to read `tests/live/fixtures/customers.csv` and report the rows without guessing marker values. Confirm recognized sensitive fields become markers while row structure remains usable. +2. Ask Claude to print `tests/live/fixtures/config.env` through Bash. Confirm supported detected credential formats are replaced in successful and failing output; record expected undetected formats rather than implying complete secret coverage. +3. Ask Claude to use `edit_with_markers` to change a non-sensitive field on a row identified by a marker. Confirm the real original value remains on disk and the tool result contains only line numbers/counts. + +Release evidence should attach concrete prompts, observed outputs and assertions for these examples, plus interactive permission and cancellation results tracked by the verification workstream. diff --git a/docs/implementation-review.md b/docs/implementation-review.md new file mode 100644 index 0000000..88c3e73 --- /dev/null +++ b/docs/implementation-review.md @@ -0,0 +1,16 @@ +# Independent candidate diff review + +Reviewed 2026-11-18 while preparing 0.2.1. Scope: joined-email mitigation in `vault.py`, resource-link metadata in `shapes.py`, exact-file permission checks in `ccperms.py`, and descriptor-based MCP editing in `mcp_server.py`. This is a focused review, not proof that every repository behavior is verified. + +## Findings resolved during review + +1. **Repeated email-tail scans could time out hooks.** A joined sequence of 1,000 addresses (~20 KB) produced 500 overlapping expanded spans and took 0.793 seconds; 100 addresses took 0.010 seconds. The initial mitigation repeatedly scanned already covered tails. After tracking covered email ranges, the same 1,000-address case produced one span in 0.0045 seconds; 10,000 addresses (~200 KB) took 0.0437 seconds. A deterministic detector-call-count regression now bounds repeated probes, avoiding machine-dependent timing assertions. +2. **Alias retargeting could evade a file deny rule.** A temporary-project reproduction changed `alias.txt` from `safe.txt` to `denied.txt` immediately after `check_file_path` returned. The earlier server then captured the new realpath and edited the denied file. The revised server captures its target before authorization, checks both alias and captured path, and refuses if the alias changes before reading or replacing. The same reproduction now raises a path-change error; both files remain unchanged. + +## Verification and limits + +- Independently ran the core-behavior, hook-protocol and MCP suites successfully after these fixes. The implementation workstream separately ran the broader permission/MCP/core set. Final full-suite and platform CI evidence must refer to the committed release candidate. +- Resource-link tests check display-text tokenization while preserving response shape and identity fields. Resource URIs deliberately remain untouched; README and privacy disclosures now say so. +- Editor tests cover effective file rules, ask/deny, alias and real-target policies, permissions/CRLF, changed files/parents, bounded reads, FIFO refusal and cooperating-editor locking. Full-server race reproduction was independently exercised, not merely inferred from the helper class. +- The editor does not provide an atomic filesystem compare-and-swap against noncooperating writers between its final identity check and rename. It also cannot enforce server/MDM policies unavailable to the plugin. Those are explicit boundaries, not closed verification gates. +- No further blocking defect was found in this focused diff review after the two fixes. This does not waive outstanding interactive, Linux, release or portal gates. diff --git a/docs/readiness.md b/docs/readiness.md new file mode 100644 index 0000000..78d1ab8 --- /dev/null +++ b/docs/readiness.md @@ -0,0 +1,103 @@ +# Public plugin directory readiness + +Working inventory, 2026-11-18. Baseline: released v0.2.0, commit 3c41b49. +This is a live work list, not a claim that the release is ready. Submission and +publication require Sid's explicit go-ahead. Preparation and verification proceed now. + +## Implementation and release gates + +| ID | Gap / required outcome | Status and evidence | +| --- | --- | --- | +| I01 | Scan MCP resource-link human-readable metadata without corrupting identifiers. | Fixed locally; agent reports 139 hook tests, 12 MCP tests, lint and type checks passing. Final candidate validation remains open. | +| I02 | Resolve adjacent Unicode email domain leak. | Local mitigation covers the joined span using core-validated trailing domains. 99 core/vault/stream tests and 90 additional Unicode/domain combinations passed; final integrated validation pending. | +| I03 | Resolve or explicitly constrain phone coverage regressions. | Known-format fixtures pin the affected 1.7.0 behavior and README gap 19 discloses it. A general regex workaround is deferred: multiline streaming needs lookahead semantics and numeric-prefix cases need precision evaluation. No complete phone-detection claim is made. | +| I04 | Align all public claims with actual coverage. | Manifest/marketplace/repository descriptions must not imply complete secret detection or an egress firewall. Audit pending. | +| I05 | Verify clean install, first start and MCP startup from distributed repository. | Published 0.2.0 cached install, direct cold SessionStart/MCP and uninstall smoke passed; see verification/marketplace-install.md. Candidate install, real host startup and version-changing upgrade remain open. | +| I06 | Validate final candidate across supported systems. | v0.2.0 release reports 2,476 passed, 42 skipped, one expected failure; four CI jobs passed. New candidate needs its own lint/types/tests, Linux key-store coverage and live evidence. | +| I07 | Package the reviewed candidate consistently. | Manifest/version/dependency agreement, strict plugin validation, release notes and exact tested revision must agree before submission. | +| I08 | Marker-aware MCP edit must respect denied paths. | Implemented shared Read/Edit matcher, ask/deny refusal and malformed-settings fail-closed behavior. Focused tests and independent retarget-race reproduction pass; final suite pending. | +| I09 | Characterize concurrent edits and symlink handling in MCP edit. | Implemented bounded descriptor reads, advisory lock, pinned target and identity/version checks. Independent review passes; final-check/rename race against noncooperating writers remains explicitly disclosed. | +| I10 | Enforce reviewed dependency versions at runtime, including failed upgrade. | Audit found stamp-only bootstrap and SessionStart could launch existing wrong-version packages after reinstall failure. Runtime/doctor/bootstrap fixes in progress; earlier full-suite attempt intentionally interrupted before this fix. | + +## Runtime verification gates + +| ID | Behavior requiring evidence | Status | +| --- | --- | --- | +| V01 | Runner preserves cwd; collects complete stdout/stderr; cancellation and timeout stop descendants. | L04 covers cwd. Real 2.1.327 collected 100 lines per stream; TaskStop and timeout with host background disabled prevented delayed effects. Default timeout auto-backgrounds; docs corrected. Repeat candidate cases after freeze. | +| V02 | Hook allow executes rewritten command without extra prompt in interactive and headless sessions. | Observed default-mode interactive allow on 2.1.299; headless fixture allows pass. | +| V03 | Hook ask displays markers; approve/deny works; persistent approval saves a safe rule; denied-call records retain marker command. | Real UI approve/deny passed; marker remained inside visible wrapper. Tested hook prompt has Yes/No only, no persistent approval. Four headless denial modes preserve marker and no raw value. | +| V04 | Plan, auto, dontAsk and bypassPermissions modes obey documented decisions. | Verify each separately; especially hook ask under bypassPermissions and auto classifier behavior. | +| V05 | Actual permission_mode hook values, including subagents. | Observer captured dontAsk/plan/bypassPermissions/auto; parent and subagent acceptEdits with child agent_id. See host report. | +| V06 | Claude rule matching agrees with plugin for Bash and Read/Edit paths; unknown cases remain conservative. | Unit coverage exists; live parity beyond documented examples remains open. | +| V07 | Trust location and CLAUDE_CONFIG_DIR behavior. | Verify against isolated configuration; do not alter real user trust/settings. | +| V08 | Managed settings from file versus server/MDM. | Cannot infer effective server policy from a file; document supported boundary and verify available cases. | +| V09 | macOS Keychain locked/denied, SSH, login, and interpreter rebuild/update access. | Happy-path creation/read/purge already reported passing; other states remain unverified. | +| V10 | Linux Secret Service: KWallet and locked session keyring. | Private GNOME Keyring CI exists; other providers/states remain unverified. | +| V11 | Built-in Edit result after marker restoration does not unexpectedly expose restored content to model. | Plain old_string plus marker new_string succeeded with no planted raw value in model-facing result. Marker old_string rejected before hook, as documented. | +| V12 | First-install MCP project directory and startup. | Requires actual installed plugin evidence. | +| V13 | Blocked prompt and unscannable-file ask user experience. | Observed blocked prompt + sanitized resubmission and generic unscannable Read prompt. UI omission of unscannable warning documented. | +| V14 | Claude Bash sandbox compatibility with runner process sessions. | macOS sandbox enabled with failIfUnavailable and no fallback: outside write denied, tokenized read succeeded. Scope requires explicit temporary data/vault write allowances; Linux remains unverified. | +| V15 | Unsupported platforms fail with actionable messaging. | Windows, Intel Mac, ARM/musl/older-glibc Linux are unsupported; do not imply runtime support from mocked checks. | + +## Product limits requiring accurate disclosure + +These are not automatically bugs that can be fixed inside a hook. Closure means +evidence, accurate claims and appropriate defaults; unsupported protection is not promised. + +1. Unknown values: names, ordinary unlabelled addresses, missing credential formats, + and detector false negatives. A future local model needs accuracy and latency evaluation. +2. Encoded/transformed values, hashes, partial output and command-based inference. +3. PostToolUse crash/timeout window for output-only tools. +4. Deliberate same-user recovery, Linux `/proc` output bypass, indirect vault access. +5. Unscanned images/PDFs and unrecognised `@` mention syntax. +6. Claude telemetry and local prompt history outside the plugin's control. +7. Restored Write/Edit/NotebookEdit and Grep/Glob input in local transcripts; + optional third-party MCP restoration also sends real values away. +8. Paths, filenames and resource URIs are identifiers, not scanned prose. +9. Binary output with invalid-byte splits; huge values/commands; vault capacity limits. +10. Writes by other tools may leave markers; unknown markers remain unchanged. +11. Restored Bash arguments may appear in process lists or be interpreted as options. +12. Vault encryption does not resist programs running as the logged-in user; + explicit file-key mode exposes values if the whole directory is copied. +13. Permission rules unavailable to the plugin and indirect file access cannot be + represented as complete enforcement of host policy. +14. Shell state/aliases/functions differ from ordinary Claude Bash sessions; + multiline values can change shadow-file line counts. +15. Core ApplicationVault API/filesystem limitations tracked in core #275, + including whole-vault cost and finite revision/value capacity. + +## Submission gates + +Detailed policy sources and reviewer copy belong in `directory-submission.md`. + +The directory audit adds explicit gates D01–D13 there: old submission ownership, +privacy-policy URL, verified support/security contact, three runnable examples, MCP +annotations, accurate public claims, Code-only surface support, install/upgrade/uninstall, +dependency provenance, permission/sandbox review, portal validation, final release evidence, +and authorized submission/publication. These are part of this inventory, not optional +follow-up work. A local privacy notice and narrower manifests are now drafted; they are +not yet publicly published or portal-validated. + +- Existing submission located in the authenticated portal: submitted July 2, marked + **Needs changes** October 5. Reviewer rejected v0.1.0 (`7a154b2`) because package + execution was not exactly pinned. Exact dependency pins are therefore a confirmed + blocker, not just a reproducibility preference. The existing entry offers resubmission; + no duplicate or migration is needed. See D01/D09 and the portal link in the submission doc. +- Portal auto-publish was enabled and all app surfaces were selected. Both are corrected: + auto-publish is now OFF, support is Claude Code only; no resubmission occurred. +- GitHub private vulnerability reporting is enabled and verified. `SECURITY.md` and + `PRIVACY.md` are local candidate documents awaiting release publication. +- Verify current portal eligibility, automated checks and manual-review requirements + for shell hooks, local MCP, Python and first-start dependency installation. +- Supply accurate description, support/security contact, privacy information, + reproducible reviewer examples, platform constraints and installation guidance. +- Resolve portal checks against the final repository revision and inspect rendered listing. +- Obtain explicit publication instruction, then submit and retain confirmation/status. + Review acceptance is external; submission alone does not prove listing publication. + +## Evidence discipline + +Record command, revision, environment, result and limitations for every closed gate. +Do not count a synthetic unit test as proof of host UI behavior or a release's old +test results as proof of a changed candidate. Keep synthetic fixtures and temporary +vaults separate from real user data. Never commit login material or raw user transcripts. diff --git a/docs/release-notes-0.2.1.md b/docs/release-notes-0.2.1.md new file mode 100644 index 0000000..5442e57 --- /dev/null +++ b/docs/release-notes-0.2.1.md @@ -0,0 +1,34 @@ +# DataFog for Claude Code 0.2.1 — candidate + +Not released or submitted. Final commit, CI and live results must be attached before +using these notes for a release or directory review. + +This candidate addresses the directory reviewer's exact-version requirement and fixes +two cases where readable tool content could escape tokenization. It pins the detector +and encrypted vault to version 1.7.0, scans MCP resource-link names/titles/descriptions, +and hides stranded email-domain tails in joined Unicode text. Joined addresses may +become one marker; restoration remains byte-exact. + +The manifest now provides privacy, documentation and support links, accurate coverage +language and the official DataFog icon. MCP tools declare their effects. A separate +CI job validates both plugin and marketplace manifests with an exact Claude Code version. +Privacy and security reporting documentation explain local storage and remaining limits. + +MCP edit permission and concurrent-file safety changes are under final verification; +their behavior and results must be included here after review. + +## Validation to attach + +- Exact candidate commit and version agreement. +- Full Python suite, lint, types, shell parsing and strict manifests. +- Linux/macOS CI matrix, including private Secret Service tests on Linux. +- Real Claude Code read, Bash and marker-aware edit examples. +- Interactive permission behavior, host modes and runner lifecycle evidence. +- Candidate cached install, version-changing upgrade and uninstall retention. + +## Remaining product boundaries + +Detection is selective; names, ordinary unlabelled addresses and several phone/secret +formats remain unsupported. Post-tool hard failures can expose raw output. Built-in +file-tool restoration can enter local Claude records. DataFog is not a sandbox against +a manipulated agent or same-user software. The README contains the full coverage limits. diff --git a/docs/release-verification-plan.md b/docs/release-verification-plan.md new file mode 100644 index 0000000..adc0606 --- /dev/null +++ b/docs/release-verification-plan.md @@ -0,0 +1,58 @@ +# Release verification and public-page follow-through + +Evidence checked 2026-11-18. This plan does not claim the current working tree has passed CI, and makes no website or directory publication. + +## Strict manifest verification + +Run `sh scripts/verify-manifests.sh`. It validates the plugin and marketplace manifests separately with `--strict`, in a temporary Claude configuration directory. It needs no model credentials and does not install the plugin or execute hooks. `CLAUDE_BIN` can select a particular Claude executable. Local run passed with Claude Code 2.1.327. + +The added `manifests` CI job installs `@anthropic-ai/claude-code@2.1.327` through npm on Ubuntu 24.04 / Node 22, then runs the same script. The exact version exists in the publisher's npm registry; observed package integrity is `sha512-QToNtikIupqVMsxRUdDHUP0nS/uv3Wc43vcbT8YNRo7FtQOE9MvYLqPLQPoVhJ2DQQVPOFMB5PkaBNJbnNYeVg==`. This is development verification tooling, not a runtime plugin dependency. The publisher documents npm installation in its [Claude Code repository](https://github.com/anthropics/claude-code). + +## Runtime dependency provenance + +The rejected directory submission required exact package versions. Both runtime packages are now fixed to 1.7.0. Installed wheel metadata and the public PyPI release JSON agree: + +- `datafog-fogvault==1.7.0` has no `Requires-Dist` dependencies. +- `datafog-core==1.7.0` has only dependencies conditional on the optional `gliner2` extra. The plugin requests no extras, so none of them resolve or install. +- Therefore the normal plugin runtime currently has two Python distributions and no transitive Python dependency tree to pin. This does not mean the compiled libraries contain no third-party Rust/native code; the pinned wheel captures that compiled artifact. +- Python, uv/pip, OS libraries and the system key store remain environmental dependencies. Pinning package versions alone is not a fully hermetic build. + +Sources: [core release metadata](https://pypi.org/pypi/datafog-core/1.7.0/json), [vault release metadata](https://pypi.org/pypi/datafog-fogvault/1.7.0/json). Registry source overrides remain possible through the user's package-manager environment; this should be disclosed and evaluated separately from exact version selection. + +Selected platform wheel SHA-256 values recorded for provenance (bootstrap does not yet enforce these hashes): + +| Distribution | Supported platform wheel | SHA-256 | +| --- | --- | --- | +| core 1.7.0 | cp310-abi3 macosx_11_0_arm64 | `ba8c3fc0817fecc7cb153dea7b219dc4bcff10696195c063d88917621f31a8fc` | +| core 1.7.0 | cp310-abi3 manylinux_2_28_x86_64 | `bae450c6360f9e942d72fedfa6645a9be92deafae276a2ba3ab0aa84027caa15` | +| fogvault 1.7.0 | cp310-abi3 macosx_11_0_arm64 | `a945828c4875d4dafe61ede042df12dcbca2858788369e6238d01884929f3c91` | +| fogvault 1.7.0 | cp310-abi3 manylinux_2_38_x86_64 | `5daffe08633bbdc04de6a35a4a25acd702cbb8a9ed5afd3657d2b100fbdc8892` | + +The directory checklist describes registry dependency execution as potentially requiring reviewer inspection; it does not make a lockfile proof of approval. The actual prior reviewer request and final portal result remain authoritative for this submission. See [submission preparation](directory-submission.md). + +## Linux CI execution plan + +Read-only GitHub checks confirmed repository admin/push permission for the current account, Actions enabled with all actions allowed, and no self-hosted runners. Repository secret listing returned no secrets. No credential values were read or uploaded. The existing four-way test matrix uses GitHub-hosted Linux/macOS runners and needs no Claude model credentials. + +1. Finish and review the candidate, then commit the exact intended tree to `directory-readiness`. +2. Push that branch and create a PR; the existing `pull_request` trigger runs the four test jobs plus the new strict-manifest job. A branch push alone does not trigger this workflow, because its push filter only covers `main` and `rebuild/**`. +3. Verify the run's `headSha` matches the candidate; inspect every job, including Linux private Secret Service coverage and network bootstrap. Do not use the existing green run for `3c41b49` as evidence for new code. +4. Download or inspect logs on failure, fix and rerun only the changed candidate as appropriate. Record run URL and exact versions in release evidence. +5. An authenticated real Claude Linux session is a separate gate: there is no existing repo secret for it. Do not copy a developer's credential into CI. Use an explicitly authorized Linux Claude session or report that gate as unverified; pytest/manifest success does not prove live interactive Linux behavior. + +`workflow_dispatch` was added for future deliberate reruns once the workflow is available on the default branch. No run was dispatched and no branch was pushed by this workstream. + +## Public homepage audit and proposed copy + +The live [DataFog homepage](https://datafog.ai/) was inspected on 2026-11-18. Its Claude Code card still says “In development · 0.2.0-dev” and redirects people seeking a released workflow to DataFog MCP. The repository already has v0.2.0 published. This is stale distribution copy; it does not imply that the public directory listing is live. + +Draft card change, to apply only after the final release decision: + +- Badge: **Claude Code plugin · v[final release version]**. +- Heading: **DataFog for Claude Code**. +- Body: **Replace detected personal data and selected credentials with reversible markers in files and tool output. Detection and the encrypted vault stay local. Supported on Apple Silicon macOS and selected Linux x86_64 systems; see coverage and platform limits.** +- Primary link: **Install from GitHub** → `https://github.com/DataFog/datafog-claude-plugin#install`. +- Secondary link: **Coverage and limitations** → `https://github.com/DataFog/datafog-claude-plugin#known-gaps`. +- After a verified public listing exists, add **Open in Claude directory** using its observed public URL. Do not invent the URL or announce directory availability early. + +Keep the existing DataFog MCP card separate: it is a different product and release track. Do not imply that Claude chat or Cowork receives this plugin's protection. Also update any matching homepage structured metadata/release snapshot when changing the card. No homepage source file was edited or deployed here. diff --git a/docs/verification/2026-11-18-host-readiness.md b/docs/verification/2026-11-18-host-readiness.md new file mode 100644 index 0000000..8769efe --- /dev/null +++ b/docs/verification/2026-11-18-host-readiness.md @@ -0,0 +1,125 @@ +# Host verification, 18 November 2026 + +This records observed behavior, not a final-candidate certification. Tests ran on +macOS Apple Silicon against the working tree based on `3c41b49` while other +readiness fixes were being developed. Repeat the relevant probes against the +frozen candidate. Synthetic fixtures, temporary file-key vaults and fixture-only +Claude settings were used. Real user vaults and key-store entries were not used. + +Claude Code updated itself during verification: the first interactive process +remained **2.1.299**; subsequent headless and bypass-mode interactive processes +reported **2.1.327**. Do not merge these into a single-version claim. + +## Interactive observations + +The real CLI ran in a PTY with `--ax-screen-reader --setting-sources project,local` +and `--plugin-dir` pointing at this checkout. See the redacted excerpts in +[interactive-2026-11-18.txt](interactive-2026-11-18.txt). + +| Gate | Evidence | Scope / remaining work | +| --- | --- | --- | +| V02 | On 2.1.299, default-mode `pwd` matched a local allow rule and ran without a command approval prompt. | Workspace trust was separately accepted for the synthetic fixture. | +| V03 | A `grep -cxF` call containing the hostile synthetic value's marker prompted. Yes returned the exact-match count `1`; repeating the call prompted again; No interrupted it. | Prompt shows the rewritten shell wrapper, paths and restore ticket, with marker retained. It does not show the raw value. | +| V03 | Hook-generated Bash ask offered only Yes and No. | No persistent “don't ask again” option existed in this tested UI; do not claim a saved-rule flow was tested. | +| V04 | On 2.1.327, interactive `bypassPermissions` still prompted for the marker call. No interrupted it. | Only this marker-ask path was tested interactively in bypass mode. | +| V07 | Accepting fixture trust wrote `projects[canonical_fixture_path].hasTrustDialogAccepted=true` in `~/.claude.json`. | `CLAUDE_CONFIG_DIR` behavior remains unverified. No existing project trust was changed. | +| V13 | Submitting a synthetic email prompt showed “your prompt was not sent,” entity count and sanitized replacement text. | The raw text remained in the local input box, consistent with documented local-history limits. | +| V13 | Reading an unscannable synthetic image asked permission; No interrupted it. | The screen-reader UI showed a generic Read approval with the file path, **not** DataFog's unscannable warning. Do not imply the host always explains that approval reveals unscanned content. | + +The original interactive log is retained locally under the printed temporary +fixture directory, rather than committed as a full host transcript. + +A separate 2.1.327 PTY launched with a fresh `CLAUDE_CONFIG_DIR` created +`/.claude.json`, then required login before showing workspace trust. +The probe stopped at login and copied no credentials. The relocated config-file +location is observed; the relocated project-trust field remains unverified. + +## Additional real-host probes + +Run `python3 tests/live/run_readiness.py` for the bounded supplementary suite, or +pass individual case names. It prints its temporary evidence directory and writes +`log/readiness.json` plus host stream-json transcripts. It uses the existing +Claude login and therefore consumes normal Claude usage. This complements +`tests/live/run-live.command`; simulator results do not prove host behavior. + +Observed on **2.1.327**: + +| Probe | Result | +| --- | --- | +| `reviewer-read` | PASS: Read result contained markers; no planted sentinel in model-facing tool results. | +| `reviewer-bash` | PASS: allowed `cat notes.txt` returned markers; no planted sentinel in tool results. | +| `reviewer-mcp-edit` | PASS: DataFog MCP edit ran; exact real email plus suffix was on disk; no marker on disk or sentinel in tool results. | +| `built-in-edit-marker-old-string` | Verified documented host limitation: marker-bearing old_string was rejected before plugin restoration; file unchanged. | +| `built-in-edit-marker-new-string` | PASS: plain old_string and marker-bearing new_string updated the real file; the model-facing Edit result contained no planted sentinel. | +| `runner-complete-output` | PASS: all 100 numbered stdout lines and all 100 stderr lines reached the tool result. This is a finite collection check, not unlimited-output coverage. | +| Default foreground timeout | **Finding:** timeout 1000 ms and `run_in_background=false` still moved the command into the background; its delayed side effect occurred. The timeout is a host background threshold by default. | +| `runner-timeout-no-background` | PASS with `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1`: host reported timeout and the delayed descendant side effect remained absent after six seconds. | +| `runner-cancel` | PASS: TaskStop stopped an auto-backgrounded command; its ten-second delayed side effect remained absent after a twelve-second observation. | +| `mode-marker-dontAsk`, `mode-marker-plan`, `mode-marker-bypassPermissions`, `mode-marker-auto` | PASS: actual Bash call attempted and denied, denial record retained a marker, no raw synthetic value in denial. These headless sessions explicitly had no approval surface. | +| Mode observation hooks | A read-only fixture hook recorded actual `permission_mode`: `dontAsk`, `plan`, `bypassPermissions`, `auto`, and `acceptEdits` matched the requested modes. It saved only tool name/id, mode and agent metadata. | +| `subagent-mode` | PASS: parent Agent and a general-purpose subagent's actual Read both received `acceptEdits`; child hook input included its own agent ID/type. Other subagent modes remain untested. | +| `sandbox-bash`, `sandbox-boundary` | PASS: macOS sandbox enabled with `failIfUnavailable=true`, `allowUnsandboxedCommands=false`, and explicit writes allowed to temp plugin data/vault. A protected fixture write was refused with an operation-not-permitted error and no file created, while the same runner returned tokenized notes. No tool requested a sandbox bypass. | + +The first supplementary run intentionally exposed two failed expectations: +marker old_string Edit support and hard termination on default Bash timeout. +Neither was “fixed” by changing the product. Later probes separate the documented +Edit restriction, default host auto-background behavior, explicit TaskStop and +the host's disable-background setting. Keep these distinctions in release copy. + +The underlying source logs are in the local temp directories named in +`host-readiness-results.json`; the checked-in summary preserves their case names, +version and assertions without full host transcripts. Initial logs were produced +before the supplement began recording provenance hashes, so they prove these +observations but do not certify the final source revision. + +## Still unverified + +- Interactive plan and auto behavior beyond marker asks; auto classifier handling + of the rewritten command; dontAsk allow path. +- `default` hook input value and other permission modes inside subagents (the + observed child used `acceptEdits`). +- Additional Bash and Read/Edit rule parity beyond existing documented fixtures. +- Alternate configuration-root trust handling, server-managed policy and MDM. +- Locked/denied macOS Keychain, SSH/login/rebuilt-interpreter access; KWallet and + locked Linux keyrings. Happy-path vault tests do not prove these states. +- Actual installed marketplace startup, upgrade and MCP project-directory behavior + (the above loads the plugin by local directory). +- Other sandbox configurations/providers, including a vault outside the sandbox's + allowed write paths. The macOS probe explicitly allowed its temporary data/vault. +- Unsupported hardware/OS runtime behavior beyond mocked platform checks. +- Other terminal renderers/accessibility modes, other host versions, larger output + and platform-specific cancellation semantics. + +## Reviewer examples + +Use a fresh synthetic fixture folder and file-key vault as created by the +supplementary driver. `notes.txt` starts with `Primary contact:` followed by the +synthetic email, and other synthetic test values. Marker suffixes vary per vault; +never hard-code them in a reviewer instruction. + +1. **Read** — Prompt: `Use Read on notes.txt and report the Primary contact line.` + Expected: the tool result and answer contain an `[[EMAIL_…]]` marker rather than + the original address. Independently compare the on-disk fixture, which remains + unchanged. Automated assertion: `reviewer-read`. +2. **Bash output** — Prompt: `Run exactly this Bash command: cat notes.txt. Report + its output.` The fixture's local settings allow `Bash(cat *)`. Expected: a real + Bash call succeeds and its output contains markers. Automated assertion: + `reviewer-bash`. +3. **MCP marker edit** — Prompt: `Use Read on notes.txt. Append " (verified)" to + the Primary contact line using only DataFog edit_with_markers, with the exact + full line as old_string. Do not use built-in Edit.` Expected: the MCP tool runs, + the disk line contains the original address plus the suffix, and no marker is + left on disk. Tool results contain no planted raw value. Automated assertion: + `reviewer-mcp-edit`. + +These three examples passed on 2.1.327. Repeat them after the final marketplace +install to close the distribution path separately from the local plugin path. + +## Harness validation + +`ruff check tests/live/run_readiness.py tests/live/run_live.py` passed. Four +existing non-network live-driver tests passed, covering temp confinement, version +rejection and fixture-settings isolation. The new supplementary probes use the +real host directly; their successful observations are listed above rather than +inferred from simulator behavior. Sandbox options follow the official +[settings reference](https://code.claude.com/docs/en/settings-reference). diff --git a/docs/verification/host-readiness-results.json b/docs/verification/host-readiness-results.json new file mode 100644 index 0000000..150b2f9 --- /dev/null +++ b/docs/verification/host-readiness-results.json @@ -0,0 +1,358 @@ +[ + { + "case": "reviewer-read", + "checks": { + "Read returned markers": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/01-reviewer-read.jsonl" + }, + { + "case": "reviewer-bash", + "checks": { + "Bash returned markers": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/02-reviewer-bash.jsonl" + }, + { + "case": "reviewer-mcp-edit", + "checks": { + "MCP edit called": true, + "real value restored on disk": true, + "no marker on disk": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/03-reviewer-mcp-edit.jsonl" + }, + { + "case": "built-in-edit-marker", + "checks": { + "Edit called": true, + "real value restored on disk": false, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/04-built-in-edit-marker.jsonl" + }, + { + "case": "runner-complete-output", + "checks": { + "all stdout lines collected": true, + "all stderr lines collected": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/05-runner-complete-output.jsonl" + }, + { + "case": "runner-timeout", + "checks": { + "requested short timeout used": true, + "host reported timeout": false, + "descendant side effect absent": false, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/06-runner-timeout.jsonl" + }, + { + "case": "mode-marker-dontAsk", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/07-mode-marker-dontAsk.jsonl" + }, + { + "case": "mode-marker-plan", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/08-mode-marker-plan.jsonl" + }, + { + "case": "mode-marker-bypassPermissions", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/09-mode-marker-bypassPermissions.jsonl" + }, + { + "case": "mode-marker-auto", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.4j4tc34d/log/runs/10-mode-marker-auto.jsonl" + }, + { + "case": "built-in-edit-marker-old-string", + "checks": { + "Edit called": true, + "host rejects marker old_string before hook": true, + "file unchanged": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.jhxqw07_/log/runs/01-built-in-edit-marker-old-string.jsonl" + }, + { + "case": "built-in-edit-marker-new-string", + "checks": { + "Edit called": true, + "real value restored on disk": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.jhxqw07_/log/runs/02-built-in-edit-marker-new-string.jsonl" + }, + { + "case": "runner-cancel", + "checks": { + "TaskStop called": true, + "host confirmed stop": true, + "descendant side effect absent": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.a3ny1fev/log/runs/01-runner-cancel.jsonl" + }, + { + "case": "runner-timeout-no-background", + "checks": { + "requested short timeout used": true, + "host reported timeout": true, + "descendant side effect absent": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.iu7b80wn/log/runs/01-runner-timeout-no-background.jsonl" + }, + { + "case": "mode-marker-dontAsk", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.l3pz6ig5/log/runs/01-mode-marker-dontAsk.jsonl", + "observed_hook_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_016LqncoxEZwZfbaWbDatFkt", + "permission_mode": "dontAsk", + "agent_id": null, + "agent_type": null + } + ], + "provenance": { + "revision": "3c41b497bba83c0a98cc6edb876946e7d187d4a6", + "tracked_diff_sha256": "ea295d2f638e37313e8a55ebe7dfbf79c0ab1f54d5ecdf2be0e27140954dfb14", + "dirty": true + } + }, + { + "case": "mode-marker-plan", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.l3pz6ig5/log/runs/02-mode-marker-plan.jsonl", + "observed_hook_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01QWanFKqmD7BJ6VLzTUmPpL", + "permission_mode": "plan", + "agent_id": null, + "agent_type": null + } + ], + "provenance": { + "revision": "3c41b497bba83c0a98cc6edb876946e7d187d4a6", + "tracked_diff_sha256": "ea295d2f638e37313e8a55ebe7dfbf79c0ab1f54d5ecdf2be0e27140954dfb14", + "dirty": true + } + }, + { + "case": "mode-marker-bypassPermissions", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.l3pz6ig5/log/runs/03-mode-marker-bypassPermissions.jsonl", + "observed_hook_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01T2m21PzJpEvv1529em4gjF", + "permission_mode": "bypassPermissions", + "agent_id": null, + "agent_type": null + } + ], + "provenance": { + "revision": "3c41b497bba83c0a98cc6edb876946e7d187d4a6", + "tracked_diff_sha256": "ea295d2f638e37313e8a55ebe7dfbf79c0ab1f54d5ecdf2be0e27140954dfb14", + "dirty": true + } + }, + { + "case": "mode-marker-auto", + "checks": { + "Bash attempted": true, + "host denied call": true, + "denied command retains marker": true, + "denial contains no raw value": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.l3pz6ig5/log/runs/04-mode-marker-auto.jsonl", + "observed_hook_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01RDLkqqX1LbbuqGVUxwb1tv", + "permission_mode": "auto", + "agent_id": null, + "agent_type": null + } + ], + "provenance": { + "revision": "3c41b497bba83c0a98cc6edb876946e7d187d4a6", + "tracked_diff_sha256": "ea295d2f638e37313e8a55ebe7dfbf79c0ab1f54d5ecdf2be0e27140954dfb14", + "dirty": true + } + }, + { + "case": "subagent-mode", + "checks": { + "subagent Read observed": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.l3pz6ig5/log/runs/05-subagent-mode.jsonl", + "observed_hook_inputs": [ + { + "tool_name": "Agent", + "tool_use_id": "toolu_01VdxuNDfRHSDJhLEURSGv5M", + "permission_mode": "acceptEdits", + "agent_id": null, + "agent_type": null + }, + { + "tool_name": "Read", + "tool_use_id": "toolu_01GAi4VUoEXhDd2mu3vbjDTa", + "permission_mode": "acceptEdits", + "agent_id": "a3e1789b33946604b", + "agent_type": "general-purpose" + } + ], + "provenance": { + "revision": "3c41b497bba83c0a98cc6edb876946e7d187d4a6", + "tracked_diff_sha256": "ea295d2f638e37313e8a55ebe7dfbf79c0ab1f54d5ecdf2be0e27140954dfb14", + "dirty": true + } + }, + { + "case": "sandbox-bash", + "checks": { + "Bash returned markers": true, + "no tool requested sandbox bypass": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.20ul20yu/log/runs/01-sandbox-bash.jsonl", + "observed_hook_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01R2EhopPvTXQ8Diw759xLrZ", + "permission_mode": "acceptEdits", + "agent_id": null, + "agent_type": null + } + ], + "provenance": { + "revision": "3c41b497bba83c0a98cc6edb876946e7d187d4a6", + "tracked_diff_sha256": "ea295d2f638e37313e8a55ebe7dfbf79c0ab1f54d5ecdf2be0e27140954dfb14", + "dirty": true + } + }, + { + "case": "sandbox-boundary", + "checks": { + "Bash returned markers": true, + "sandbox blocked protected write": true, + "host output reports denied operation": true, + "no tool requested sandbox bypass": true, + "successful host process": true, + "no sentinel in model tool results": true + }, + "version": "2.1.327", + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-readiness.z4ur_11w/log/runs/01-sandbox-boundary.jsonl", + "observed_hook_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01GQ5TyaTFZJ8iEU3tu3QmWd", + "permission_mode": "acceptEdits", + "agent_id": null, + "agent_type": null + } + ], + "provenance": { + "revision": "3c41b497bba83c0a98cc6edb876946e7d187d4a6", + "tracked_diff_sha256": "ea295d2f638e37313e8a55ebe7dfbf79c0ab1f54d5ecdf2be0e27140954dfb14", + "dirty": true + } + } +] diff --git a/docs/verification/interactive-2026-11-18.txt b/docs/verification/interactive-2026-11-18.txt new file mode 100644 index 0000000..97b151f --- /dev/null +++ b/docs/verification/interactive-2026-11-18.txt @@ -0,0 +1,113 @@ +Observed Claude Code 2.1.299 screen-reader PTY excerpts. Paths and restore ticket redacted. Synthetic fixtures only. + +Permission Required: Accessing workspace: +/project +Quick safety check: Is this a project you created or one you trust? (Like your +own code, a well-known open source project, or work from your team). If not, +take a moment to review what's in this folder first. +Claude Code'll be able to read, edit, and execute files here. +warning: This folder pre-approves 9 tool permissions in .claude/settings.json +and .claude/settings.local.json: + Bash(wc *), Bash(cat *), Bash(grep *), Bash(ls *), Bash(cd *), Bash(pwd), +Bash(./argdump *), Bash(sh break-step.sh), and 1 more +These will apply without asking. Only proceed if you trust this configuration. +Security guide +y. Yes, I trust this folder +n. No, exit +Enter y/n: +Enter to confirm · + +--- + +Permission Required: Bash command +> Count lines in nasty.txt exactly matching the API key +> . /scripts/wrap.sh && +> __datafog_run +> /scripts/datafog-guard +> / +> data +> / +> vault 'grep -cxF '"'"'[[API_KEY_FFE1WT]]'"'"' nasty.txt' +> +> Hook PreToolUse:Bash requires confirmation for this command: +> DataFog: this command contains markers (1 API_KEY). If you approve, the real +> values are put in when it runs; its output is still filtered, but a command +> can transform a value (encode it, count it) in ways the filter cannot +> recognise. +settings.json to update hooks +Do you want to proceed? +1. Yes +2. No +Select with numbers [1-2]. Then Enter to submit or Escape to cancel: + + +--- + +Permission Required: Bash command +> Count lines in nasty.txt exactly matching the API key +> . /scripts/wrap.sh && +> __datafog_run +> /scripts/datafog-guard +> / +> data +> / +> vault 'grep -cxF '"'"'[[API_KEY_FFE1WT]]'"'"' nasty.txt' +> +> Hook PreToolUse:Bash requires confirmation for this command: +> DataFog: this command contains markers (1 API_KEY). If you approve, the real +> values are put in when it runs; its output is still filtered, but a command +> can transform a value (encode it, count it) in ways the filter cannot +> recognise. +settings.json to update hooks +Do you want to proceed? +1. Yes +2. No +Select with numbers [1-2]. Then Enter to submit or Escape to cancel: + + +--- + +Permission Required: Read file +> Read(/project/image.png) +Do you want to proceed? +1. Yes +2. Yes, and switch to accept edits (auto-approve file edits and common file +commands) for this session +3. No +Select with numbers [1-3]. Then Enter to submit or Escape to cancel: + + +--- + +UserPromptSubmit operation blocked by hook: +DataFog: your prompt was not sent because it contains 1 EMAIL. Claude Code does +not let a plugin rewrite a prompt, so submit this version instead (each marker +stands for your value and is swapped back locally when Claude writes it): + +Reply with this synthetic test email: [[EMAIL_26YVPG]] + + +--- + +Observed 2.1.327, bypassPermissions mode: + +Permission Required: Bash command +> Count exact-line matches of the marker value in nasty.txt +> . /scripts/wrap.sh && +> __datafog_run +> /scripts/datafog-guard +> / +> data +> / +> vault 'grep -cxF '"'"'[[API_KEY_FFE1WT]]'"'"' nasty.txt' +> +> Hook PreToolUse:Bash requires confirmation for this command: +> DataFog: this command contains markers (1 API_KEY). If you approve, the real +> values are put in when it runs; its output is still filtered, but a command +> can transform a value (encode it, count it) in ways the filter cannot +> recognise. [plugin:datafog] +plugin hooks.json to update hooks +Do you want to proceed? +1. Yes +2. No +Select with numbers [1-2]. Then Enter to submit or Escape to cancel: diff --git a/docs/verification/marketplace-install.md b/docs/verification/marketplace-install.md new file mode 100644 index 0000000..feb8f5b --- /dev/null +++ b/docs/verification/marketplace-install.md @@ -0,0 +1,46 @@ +# Cached marketplace installation check + +Observed 2026-11-18 on macOS Apple Silicon. This checks the currently published +**v0.2.0**, not the uncommitted directory-readiness candidate. Repeat against the final +release before closing D08. Claude Code auto-updated during the broader audit, so this +check must not be used to establish minimum-version compatibility. + +An isolated `CLAUDE_CONFIG_DIR` and throwaway project were used. The vault override +pointed at a temporary directory and used explicit file-key mode. No real user vault, +plugin installation or key-store entry was used. Local raw evidence is under +`/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-install-audit-_n8jeu21`. + +| Check | Result | +| --- | --- | +| `claude plugin install datafog --marketplace DataFog/datafog-claude-plugin --json` | Exit 0; installed `datafog@datafog` into isolated cache at version 0.2.0. Three unset options reported; defaults available. | +| Invoke cached launcher `session-start` with a SessionStart hook payload | Exit 0; private environment bootstrapped and status reported guard on, temporary file-key vault, Bash filtering, marker restoration ask. | +| Invoke cached launcher `mcp` over JSON-RPC | Initialize, tools/list and protection_status each returned a result; process exited 0. | +| `claude plugin update datafog@datafog --json` | Exit 0; correctly reported already at 0.2.0. This is not evidence of a version-changing upgrade. | +| `claude plugin uninstall datafog@datafog --json` | Exit 0; plugin data directory removed, separately configured temporary vault retained. | + +Limitations: hook and MCP launch were exercised directly from the cached installation, +not through a model session. This verifies packaged paths and cold bootstrap but does +not prove host MCP environment interpolation or first-session startup ordering. The +retention result applies to an explicit external vault override; default OS-vault and +plugin-data-vault retention need separate checks. A version-changing upgrade and the +final candidate's cache remain open gates. + +## Local candidate upgrade and retention + +A subsequent isolated local Git marketplace used a baseline 0.2.0 snapshot and then +the 0.2.1 workspace snapshot. The CLI installed 0.2.0, refreshed the marketplace and +reported a successful **0.2.0 → 0.2.1** update. Cached SessionStart and Read hooks ran +after both versions. The same synthetic address retained exactly the same marker across +the upgrade, and the new private environment stamp contained both exact 1.7.0 pins. +Uninstall removed plugin data while preserving the explicitly external temporary vault. + +A second candidate install configured `keep_vault_on_uninstall=false`. The cached +SessionStart hook received that option, created a file-key vault inside plugin data, +and CLI uninstall removed both data and vault. This does not test OS key-store cleanup: +the README correctly states that uninstall leaves a key-store entry unless purged first. + +Both checks passed. Local evidence directory: +`/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-upgrade-audit-axnii59g`. +These remain direct cached-hook checks, not model sessions, and precede the later runtime +version-enforcement fix. Final-release host startup and updated-candidate certification +are still required. diff --git a/engine/datafog_guard/__init__.py b/engine/datafog_guard/__init__.py index c655568..5e8f19d 100644 --- a/engine/datafog_guard/__init__.py +++ b/engine/datafog_guard/__init__.py @@ -5,11 +5,11 @@ to the real values locally when the agent writes. """ -__version__ = "0.2.0" +__version__ = "0.2.1" # 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" +CORE_REQUIREMENT = "datafog-core==1.7.0" # 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" +VAULT_REQUIREMENT = "datafog-fogvault==1.7.0" APP_ID = "claude-code" diff --git a/engine/datafog_guard/ccperms.py b/engine/datafog_guard/ccperms.py index 768ee74..aa5c1b9 100644 --- a/engine/datafog_guard/ccperms.py +++ b/engine/datafog_guard/ccperms.py @@ -1058,6 +1058,31 @@ def __init__(self): self.unsure = "" # why a path rule may apply although no named path matches +def check_file_path(rules: RuleSet, path: str, cwd: str, project_dir: str = "") -> PathFinding: + """Apply Read/Edit restrictions to an exact file used by the marker-aware MCP editor. + + Unlike a shell command, this tool names one known file. Keep the same path matcher and + conservative settings handling without guessing which command arguments could be paths. + """ + finding = PathFinding() + if len(path) > MAX_PATH_LENGTH or path.count("/") > MAX_PATH_SEGMENTS or "\x00" in path: + finding.unsure = "the path cannot be checked against your Read and Edit rules" + return finding + cwds = list(dict.fromkeys([os.path.abspath(cwd), os.path.abspath(project_dir or cwd)])) + try: + joined = path if os.path.isabs(path) else os.path.join(cwd, path) + paths = [os.path.normpath(joined), os.path.realpath(joined)] + finding.deny = _rule_for(rules, paths, "deny", cwds) + finding.ask = _rule_for(rules, paths, "ask", cwds) + except (OSError, ValueError): + finding.unsure = "the path could not be resolved for your Read and Edit rules" + if rules.problems: + finding.unsure = "a Claude Code settings file could not be read completely" + elif any(rule.unsupported for rule in rules.paths): + finding.unsure = "a Read or Edit rule uses a path pattern the plugin cannot interpret" + return finding + + def _texts_of(text: str) -> list[str]: """What in one word may be a path: the word, what follows ``=`` ``:`` ``,`` ``@`` in it, and every tail of a short-option cluster (``-fPATH``, ``-hfPATH``, ``-nfPATH``).""" diff --git a/engine/datafog_guard/cli.py b/engine/datafog_guard/cli.py index 9a324d5..6234982 100644 --- a/engine/datafog_guard/cli.py +++ b/engine/datafog_guard/cli.py @@ -156,7 +156,8 @@ def check(name: str, ok, detail: str = "") -> None: started = time.perf_counter() from importlib.metadata import version - import datafog_core + from .vault import _core + datafog_core = _core() check(f"detector library ({CORE_REQUIREMENT})", True, f"datafog-core {version('datafog-core')}, import {1000 * (time.perf_counter() - started):.1f} ms") missing = [name for name in settings.entities if name not in datafog_core.capabilities()["entities"]] @@ -167,7 +168,8 @@ def check(name: str, ok, detail: str = "") -> None: started = time.perf_counter() from importlib.metadata import version - import datafog_fogvault # noqa: F401 + from .store import _fogvault + _fogvault() 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: diff --git a/engine/datafog_guard/dependencies.py b/engine/datafog_guard/dependencies.py new file mode 100644 index 0000000..10296be --- /dev/null +++ b/engine/datafog_guard/dependencies.py @@ -0,0 +1,32 @@ +"""Check reviewed dependency versions before calling detector or vault code. + +This detects stale or accidentally upgraded environments; version labels are not a +cryptographic integrity check against another program running as the same user. +""" +from __future__ import annotations + +from functools import lru_cache + +from .errors import EngineUnavailable + + +@lru_cache(maxsize=2) +def reviewed_version(requirement: str) -> str: + from importlib.metadata import PackageNotFoundError, version + + name, expected = requirement.split("==", 1) + try: + installed = version(name) + except PackageNotFoundError: + raise EngineUnavailable("reviewed dependency metadata is missing; run the bootstrap command " + "shown at session start", "dependency_version_unavailable") from None + if installed != expected: + raise EngineUnavailable(f"the installed dependency must match {requirement}; run the bootstrap " + "command shown at session start", "dependency_version_mismatch") + return expected + + +def check_module(module, requirement: str) -> None: + if getattr(module, "__version__", None) != reviewed_version(requirement): + raise EngineUnavailable(f"the loaded dependency must match {requirement}; run the bootstrap " + "command shown at session start", "dependency_version_mismatch") diff --git a/engine/datafog_guard/hook.py b/engine/datafog_guard/hook.py index 2512f88..4e5e88a 100644 --- a/engine/datafog_guard/hook.py +++ b/engine/datafog_guard/hook.py @@ -52,7 +52,9 @@ "print the original value, and never ask the user for it. (3) The built-in Edit tool cannot " "match a line that contains a marker: to change such a line use the tool " f"{EDIT_TOOL} (same arguments as Edit). (4) Markers sent to web or third-party MCP tools " - "are NOT swapped back. (5) Background Bash commands are refused; run commands in the foreground. " + "are NOT swapped back. (5) Explicit background Bash requests require background_bash: allow; " + "otherwise request foreground commands. " + "Claude Code may still move a timed-out command to the background; that does not mean it stopped. " "(6) Each Bash command runs in a fresh shell: `cd` carries over to the next command, but variables, " "functions and aliases do not." ) @@ -236,9 +238,9 @@ def pre_bash(session: Session, tool_input: dict, record: dict, permission_mode: if not isinstance(command, str) or not command.strip(): return None if tool_input.get("run_in_background") and settings.background_bash != "allow": - return deny("DataFog: background commands are refused because their output is read later, outside " - "the output filter. Run the command in the foreground (set background_bash to allow to " - "change this).") + return deny("DataFog: explicit background commands are refused by your background_bash policy. " + "Request the command in the foreground (set background_bash to allow to change this). " + "Claude Code's automatic backgrounding at a timeout is a separate host setting.") if _mentions_vault(command, settings): return deny("DataFog: commands that name the vault directory are refused; it holds the real values.") if _names_own_config(command, settings): diff --git a/engine/datafog_guard/mcp_server.py b/engine/datafog_guard/mcp_server.py index 605353b..6f5944e 100644 --- a/engine/datafog_guard/mcp_server.py +++ b/engine/datafog_guard/mcp_server.py @@ -18,15 +18,18 @@ import json import os +import secrets import stat import sys -from . import __version__, config, files, log +from . import __version__, ccperms, config, files, log from .errors import GuardError, safe_code TOOLS = [ { "name": "edit_with_markers", + "annotations": {"title": "Edit with DataFog markers", "readOnlyHint": False, + "destructiveHint": True, "idempotentHint": False, "openWorldHint": False}, "description": ( "Edit a file when old_string or new_string contains DataFog markers such as [[EMAIL_ABC123]]. " "Works like the built-in Edit tool: old_string must match the file exactly once unless " @@ -46,7 +49,10 @@ }, { "name": "protection_status", - "description": "Show what DataFog guard protects in this session: entity types and counts only.", + "annotations": {"title": "DataFog protection status", "readOnlyHint": False, + "destructiveHint": False, "idempotentHint": True, "openWorldHint": False}, + "description": ("Show what DataFog guard protects in this session: entity types and counts only. " + "May initialize the local encrypted vault and its key on first use."), "inputSchema": {"type": "object", "properties": {}}, }, ] @@ -56,6 +62,114 @@ class ToolError(Exception): pass +class EditableFile: + """A bounded snapshot and pinned directory for one local edit. + + Advisory locking serializes cooperating editors. A final identity/version check catches + intervening saves by other programs; it is not a filesystem compare-and-swap against a + writer racing the final rename. No directory or final-file symlink is followed on open. + """ + def __init__(self, path: str, project: str, max_bytes: int): + self.requested = path + self.path = os.path.realpath(path) + self.project = os.path.realpath(project) + self.max_bytes = max_bytes + self.directory = self.fd = -1 + self.name = os.path.basename(self.path) + + def __enter__(self): + import fcntl + + if not files.is_inside(self.path, self.project): + raise ToolError("Refused: the path is outside the project directory.") + try: + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + self.directory = os.open(self.project, flags) + relative = os.path.relpath(os.path.dirname(self.path), self.project) + for part in ([] if relative == "." else relative.split(os.sep)): + next_directory = os.open(part, flags, dir_fd=self.directory) + os.close(self.directory) + self.directory = next_directory + self.fd = os.open(self.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=self.directory) + self.info = os.fstat(self.fd) + if not stat.S_ISREG(self.info.st_mode): + raise ToolError("The path is not a regular file.") + if self.info.st_size > self.max_bytes: + raise ToolError("The file is too large to edit with this tool.") + try: + fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise ToolError("The file is being edited by another process; retry after it finishes.") from None + return self + except FileNotFoundError: + self.close() + raise ToolError("The file does not exist.") from None + except BaseException: + self.close() + raise + + def close(self): + for name in ("fd", "directory"): + descriptor = getattr(self, name) + if descriptor >= 0: + os.close(descriptor) + setattr(self, name, -1) + + def __exit__(self, *args): + self.close() + + @staticmethod + def version(info): + return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_mode) + + def check_unchanged(self): + try: + current = os.stat(self.name, dir_fd=self.directory, follow_symlinks=False) + parent = os.stat(os.path.dirname(self.path), follow_symlinks=False) + pinned = os.fstat(self.directory) + same = (self.version(current) == self.version(self.info) + and self.version(os.fstat(self.fd)) == self.version(self.info) + and (parent.st_dev, parent.st_ino) == (pinned.st_dev, pinned.st_ino) + and os.path.realpath(self.requested) == self.path) + except OSError: + same = False + if not same: + raise ToolError("The file or its path changed while preparing the edit; nothing was replaced. " + "Read the current file and retry.") + + def read(self) -> bytes: + self.check_unchanged() + chunks, size = [], 0 + while size <= self.max_bytes: + chunk = os.read(self.fd, min(65536, self.max_bytes + 1 - size)) + if not chunk: + break + chunks.append(chunk) + size += len(chunk) + if size > self.max_bytes: + raise ToolError("The file is too large to edit with this tool.") + self.check_unchanged() + return b"".join(chunks) + + def replace(self, data: bytes): + temp = f".{self.name}.datafog-{secrets.token_hex(8)}.tmp" + descriptor = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, dir_fd=self.directory) + try: + with os.fdopen(descriptor, "wb") as handle: + handle.write(data) + handle.flush() + os.fchmod(handle.fileno(), stat.S_IMODE(self.info.st_mode)) + os.fsync(handle.fileno()) + self.check_unchanged() + os.replace(temp, self.name, src_dir_fd=self.directory, dst_dir_fd=self.directory) + finally: + try: + os.unlink(temp, dir_fd=self.directory) + except FileNotFoundError: + pass + + class Server: def __init__(self): self._vault = None @@ -89,50 +203,53 @@ def edit_with_markers(self, arguments: dict) -> str: path = files.original_of(settings.shadow_dir, path) or path if not os.path.isabs(path): path = os.path.join(self.project_dir(), path) - if files.is_inside(path, settings.vault_dir) or files.is_inside(path, settings.data_dir): + target = EditableFile(path, self.project_dir(), settings.max_scan_bytes) + if files.is_inside(target.path, settings.vault_dir) or files.is_inside(target.path, settings.data_dir): raise ToolError("Refused: the path is inside DataFog's own storage.") - if not files.is_inside(path, self.project_dir()): + if not files.is_inside(target.path, self.project_dir()): raise ToolError("Refused: the path is outside the project directory.") + rules = ccperms.load(self.project_dir()) + for permission_path in (path, target.path): + restrictions = ccperms.check_file_path(rules, permission_path, + os.getcwd(), self.project_dir()) + if restrictions.deny: + raise ToolError(f"Refused: a {restrictions.deny.tool} deny rule covers this file.") + if restrictions.ask: + raise ToolError(f"Refused: a {restrictions.ask.tool} ask rule covers this file. " + "This MCP tool cannot request the required file permission; use Claude Code's " + "built-in file tools or change the rule yourself.") + if restrictions.unsure: + raise ToolError("Refused: " + restrictions.unsure + ". Check /datafog:doctor before editing.") if not old: raise ToolError("old_string is empty. Use the Write tool to create a file.") - try: - info = os.stat(path) - except OSError: - raise ToolError("The file does not exist.") from None - if not stat.S_ISREG(info.st_mode): - raise ToolError("The path is not a regular file.") - if info.st_size > settings.max_scan_bytes: - raise ToolError("The file is too large to edit with this tool.") - vault.health() old_real = vault.restore(old) new_real = vault.restore(new) if old_real.text == new_real.text: raise ToolError("old_string and new_string are the same; nothing to change.") - with open(path, "rb") as handle: - raw = handle.read() - try: - content = raw.decode("utf-8") - except UnicodeDecodeError: - raise ToolError("The file is not UTF-8 text.") from None - count = content.count(old_real.text) - if count == 0: - hint = "" - if old_real.unknown: - hint = f" {old_real.unknown} marker(s) in old_string are not known to the vault." - raise ToolError("old_string was not found in the file." + hint) - if count > 1 and not replace_all: - raise ToolError(f"old_string matches {count} places in the file. Add surrounding text to make it " - "unique, or set replace_all to true.") - lines, position = [], 0 - for _ in range(count if replace_all else 1): - position = content.index(old_real.text, position) - lines.append(content.count("\n", 0, position) + 1) - position += len(old_real.text) - updated = content.replace(old_real.text, new_real.text) if replace_all \ - else content.replace(old_real.text, new_real.text, 1) - self._write(path, updated.encode("utf-8"), info.st_mode) - + with target: + raw = target.read() + try: + content = raw.decode("utf-8") + except UnicodeDecodeError: + raise ToolError("The file is not UTF-8 text.") from None + count = content.count(old_real.text) + if count == 0: + hint = "" + if old_real.unknown: + hint = f" {old_real.unknown} marker(s) in old_string are not known to the vault." + raise ToolError("old_string was not found in the file." + hint) + if count > 1 and not replace_all: + raise ToolError(f"old_string matches {count} places in the file. Add surrounding text to make it " + "unique, or set replace_all to true.") + lines, position = [], 0 + for _ in range(count if replace_all else 1): + position = content.index(old_real.text, position) + lines.append(content.count("\n", 0, position) + 1) + position += len(old_real.text) + updated = content.replace(old_real.text, new_real.text) if replace_all \ + else content.replace(old_real.text, new_real.text, 1) + target.replace(updated.encode("utf-8")) restored = old_real.restored + new_real.restored unknown = old_real.unknown + new_real.unknown log.write(settings.log_path, event="McpEdit", replacements=len(lines), restored=dict(restored), @@ -144,26 +261,6 @@ def edit_with_markers(self, arguments: dict) -> str: summary += f" {unknown} marker-like string(s) were not known to the vault and were used as written." return summary - @staticmethod - def _write(path: str, data: bytes, mode: int) -> None: - """Replace the file in one step, keeping its permission bits.""" - directory = os.path.dirname(path) - temp = os.path.join(directory, f".{os.path.basename(path)}.datafog-{os.getpid()}.tmp") - fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, stat.S_IMODE(mode)) - try: - with os.fdopen(fd, "wb") as handle: - handle.write(data) - handle.flush() - os.fsync(handle.fileno()) - os.chmod(temp, stat.S_IMODE(mode)) - os.replace(temp, path) - except BaseException: - try: - os.unlink(temp) - except OSError: - pass - raise - def protection_status(self, arguments: dict) -> str: from .cli import status_report return status_report(for_model=True) diff --git a/engine/datafog_guard/shapes.py b/engine/datafog_guard/shapes.py index 1d6b40c..70f489a 100644 --- a/engine/datafog_guard/shapes.py +++ b/engine/datafog_guard/shapes.py @@ -40,7 +40,7 @@ "speed", "inference_geo"}, } KEEP["Task"] = KEEP["Agent"] -_BINARY_ITEM_TYPES = {"image", "audio", "resource_link"} +_BINARY_ITEM_TYPES = {"image", "audio"} def _keep_for(tool: str) -> set: @@ -61,6 +61,13 @@ def _walk(node, keep: set, tool: str, leaves: list, key: str | None = None, pare if isinstance(node, dict): if node.get("type") in _BINARY_ITEM_TYPES and (tool.startswith("mcp__") or tool in ("Agent", "Task")): return + if node.get("type") == "resource_link" and (tool.startswith("mcp__") or tool in ("Agent", "Task")): + # A resource link has readable metadata, not a binary payload. Its URI is + # an identifier (like a file path); names, titles and descriptions are content. + for name, value in node.items(): + if name not in ("type", "uri", "mimeType"): + _walk(value, keep, tool, leaves, name, node) + return if tool == "Bash" and node.get("isImage") is True: for name, value in node.items(): if name != "stdout": diff --git a/engine/datafog_guard/store.py b/engine/datafog_guard/store.py index 0905eb1..52498b9 100644 --- a/engine/datafog_guard/store.py +++ b/engine/datafog_guard/store.py @@ -170,6 +170,15 @@ def __exit__(self, *exc) -> None: def _fogvault(): + from . import VAULT_REQUIREMENT + from .dependencies import check_module, reviewed_version + try: + reviewed_version(VAULT_REQUIREMENT) # reject unreviewed distributions before importing their code + except EngineUnavailable: + from .support import UNSUPPORTED, platform_problem + if platform_problem(): + raise EngineUnavailable(UNSUPPORTED, "unsupported_platform") from None + raise try: import datafog_fogvault except Exception as error: # no wheel for this machine, or a broken install @@ -178,6 +187,7 @@ def _fogvault(): 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 + check_module(datafog_fogvault, VAULT_REQUIREMENT) return datafog_fogvault diff --git a/engine/datafog_guard/vault.py b/engine/datafog_guard/vault.py index 2554a36..d6a3e8a 100644 --- a/engine/datafog_guard/vault.py +++ b/engine/datafog_guard/vault.py @@ -48,6 +48,11 @@ # characters) the values are first narrowed to those whose first characters occur in the text. PREFILTER_WORK = 50_000_000 GRAM = 4 +# Core 1.7.0 can absorb the next mailbox's local part into an email domain in +# unspaced Unicode prose, leaving its @domain behind. Validate only that tail +# with the same detector and cover the joined addresses as one reversible value. +_EMAIL_TAIL = re.compile(rb"@[^\s@]*") +_EMAIL_PROBE = "datafog-probe" # Characters a terminal does not show, or that move the cursor. A value split by one of them @@ -130,10 +135,14 @@ def flush(): def _core(): + from . import CORE_REQUIREMENT + from .dependencies import check_module, reviewed_version + reviewed_version(CORE_REQUIREMENT) # reject unreviewed distributions before importing their code try: import datafog_core except Exception as error: # missing, wrong architecture, broken install raise EngineUnavailable("the datafog-core library cannot be loaded") from error + check_module(datafog_core, CORE_REQUIREMENT) return datafog_core @@ -196,12 +205,36 @@ def spans(self, text: str) -> list[Span]: except UnicodeError as error: raise TokenizeError("the text is not valid Unicode", "undecodable_text") from error spans = [] + data = None + covered_email = (0, 0) for finding in findings: if finding.matched_text in self.allowlist: continue - spans.append(Span(finding.byte_range.start, finding.byte_range.end, finding.entity_type)) + start, end = finding.byte_range.start, finding.byte_range.end + if finding.entity_type == "EMAIL": + if covered_email[0] <= start and end <= covered_email[1]: + continue # the first joined-address span already covers this finding and its tail + data = data if data is not None else text.encode("utf-8") + end = self._cover_email_tail(data, end) + if data[start:end].decode("utf-8") in self.allowlist: + continue + covered_email = (start, end) + spans.append(Span(start, end, finding.entity_type)) return spans + @staticmethod + def _cover_email_tail(data: bytes, end: int) -> int: + while tail := _EMAIL_TAIL.match(data, end): + probe = _EMAIL_PROBE + tail.group().decode("utf-8") + findings = _core().scan(probe, {"entities": ["EMAIL"]}) + match = next((finding for finding in findings + if finding.entity_type == "EMAIL" and finding.byte_range.start == 0 + and finding.byte_range.end > len(_EMAIL_PROBE)), None) + if match is None: + break + end += match.byte_range.end - len(_EMAIL_PROBE) + return end + def self_test(self) -> None: """Fail if the configuration is unusable or the detector does not find a value it must find.""" self.config() diff --git a/pyproject.toml b/pyproject.toml index a2b3bdb..102ca1c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,10 +1,10 @@ [project] name = "datafog-guard" -version = "0.2.0" +version = "0.2.1" description = "Engine of the DataFog Claude Code plugin" requires-python = ">=3.10" license = "Apache-2.0" -dependencies = ["datafog-core>=1.7.0,<1.8", "datafog-fogvault>=1.7.0,<1.8"] +dependencies = ["datafog-core==1.7.0", "datafog-fogvault==1.7.0"] [dependency-groups] dev = ["pytest>=8", "ruff>=0.6", "mypy>=1.10"] diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index dd31c5b..f9facb7 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -4,14 +4,14 @@ # bootstrap.sh [--force] # bootstrap.sh --platform only check that this machine is supported # -# 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. +# Idempotent. Fast path: the stamp, installed versions and import probe all pass. +# Uses uv when it is installed, otherwise python -m venv and pip. # 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' +CORE_REQUIREMENT='datafog-core==1.7.0' +VAULT_REQUIREMENT='datafog-fogvault==1.7.0' 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.' @@ -46,7 +46,24 @@ venv_python() { fi } -if [ "$FORCE" != "--force" ] && [ -n "$(venv_python)" ] && [ "$(cat "$STAMP" 2>/dev/null)" = "$REQUIREMENT" ]; then +verified_environment() { + [ -n "$(venv_python)" ] || return 1 + "$(venv_python)" -I -c ' +from importlib.metadata import version +import sys +for requirement in sys.argv[1:]: + name, expected = requirement.split("==", 1) + if version(name) != expected: + raise SystemExit(1) +import datafog_core, datafog_fogvault +if datafog_core.__version__ != sys.argv[1].split("==", 1)[1] or datafog_fogvault.__version__ != sys.argv[2].split("==", 1)[1]: + raise SystemExit(1) +datafog_core.scan("probe") +datafog_fogvault.ApplicationVault +' "$CORE_REQUIREMENT" "$VAULT_REQUIREMENT" 2>/dev/null +} + +if [ "$FORCE" != "--force" ] && [ "$(cat "$STAMP" 2>/dev/null)" = "$REQUIREMENT" ] && verified_environment; then exit 0 fi @@ -65,7 +82,7 @@ done trap 'rmdir "$LOCK" 2>/dev/null' EXIT INT TERM # Another session may have finished the install while we waited. -if [ "$FORCE" != "--force" ] && [ -n "$(venv_python)" ] && [ "$(cat "$STAMP" 2>/dev/null)" = "$REQUIREMENT" ]; then +if [ "$FORCE" != "--force" ] && [ "$(cat "$STAMP" 2>/dev/null)" = "$REQUIREMENT" ] && verified_environment; then exit 0 fi @@ -101,7 +118,7 @@ else [ "$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_fogvault; datafog_core.scan("probe"); datafog_fogvault.ApplicationVault' 2>/dev/null; then +if [ "$ok" = 1 ] && verified_environment; then printf '%s' "$REQUIREMENT" > "$STAMP" echo "datafog bootstrap: ready" exit 0 diff --git a/scripts/datafog-guard b/scripts/datafog-guard index b21b41a..c5d5752 100755 --- a/scripts/datafog-guard +++ b/scripts/datafog-guard @@ -38,10 +38,11 @@ case "$1" in # for the engine; the installer's output goes to a log file so it cannot disturb the # hook's JSON output. mkdir -p "$DATA/log" 2>/dev/null - sh "$ROOT/scripts/bootstrap.sh" "$DATA" >"$DATA/log/bootstrap.log" 2>&1 + BOOTSTRAP_OK=1 + sh "$ROOT/scripts/bootstrap.sh" "$DATA" >"$DATA/log/bootstrap.log" 2>&1 || BOOTSTRAP_OK=0 PY="$DATA/venv/bin/python" [ -x "$PY" ] || PY="$DATA/venv/Scripts/python.exe" - if [ ! -x "$PY" ]; then + if [ "$BOOTSTRAP_OK" != 1 ] || [ ! -x "$PY" ]; then cat >/dev/null if UNSUPPORTED=$(sh "$ROOT/scripts/bootstrap.sh" --platform 2>/dev/null); then :; else printf '{"systemMessage": "%s"}\n' "$UNSUPPORTED" diff --git a/scripts/verify-manifests.sh b/scripts/verify-manifests.sh new file mode 100644 index 0000000..2e33ed0 --- /dev/null +++ b/scripts/verify-manifests.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Validate both manifests explicitly: validating the repository directory may select +# only its marketplace. This does not execute plugin hooks or require model login. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +CLAUDE_BIN=${CLAUDE_BIN:-claude} +if ! command -v "$CLAUDE_BIN" >/dev/null 2>&1; then + echo 'Claude Code is required. CI uses @anthropic-ai/claude-code@2.1.327.' >&2 + exit 1 +fi +# Isolate validation from a developer's installed plugins/settings. Keep credentials +# out of CI: schema/directory-subset checks do not need an authenticated model call. +VALIDATION_CONFIG=$(mktemp -d) +trap 'rm -rf "$VALIDATION_CONFIG"' EXIT HUP INT TERM +export CLAUDE_CONFIG_DIR="$VALIDATION_CONFIG" +export DISABLE_AUTOUPDATER=1 +"$CLAUDE_BIN" --version +"$CLAUDE_BIN" plugin validate --strict "$ROOT/.claude-plugin/plugin.json" +"$CLAUDE_BIN" plugin validate --strict "$ROOT/.claude-plugin/marketplace.json" diff --git a/tests/live/run_installed_readiness.py b/tests/live/run_installed_readiness.py new file mode 100644 index 0000000..e326e36 --- /dev/null +++ b/tests/live/run_installed_readiness.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Test a cached project/local install using the existing Claude login. + +Creates a uniquely named temporary local marketplace containing a source snapshot. +Only that marketplace and its local-scope installation are removed afterwards. +Does not copy credentials, set CLAUDE_CONFIG_DIR, or use --plugin-dir. +Run after freezing the candidate: python3 tests/live/run_installed_readiness.py +""" +import hashlib +import json +import pathlib +import shutil +import subprocess +import tempfile +import uuid + +import run_live as live + + +def main(): + source = pathlib.Path(live.REPO) + work = pathlib.Path(tempfile.mkdtemp(prefix="datafog-installed.")) + snapshot = work / "marketplace" + snapshot.mkdir() + marketplace = "datafog-readiness-" + uuid.uuid4().hex[:12] + plugin_id = "datafog@" + marketplace + names = subprocess.check_output(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], cwd=source).decode().split("\0") + hashes = {} + for name in filter(None, names): + path = source / name + if not path.is_file(): + continue + if path.is_symlink(): + raise SystemExit("Snapshot refuses symlinks: " + name) + destination = snapshot / name + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, destination) + hashes[name] = hashlib.sha256(path.read_bytes()).hexdigest() + catalog_path = snapshot / ".claude-plugin/marketplace.json" + catalog = json.loads(catalog_path.read_text()) + catalog["name"] = marketplace + catalog_path.write_text(json.dumps(catalog, indent=2)) + provenance = {"revision": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=source, text=True).strip(), + "source_sha256": hashes, "marketplace": marketplace, + "snapshot_change": "Only marketplace.name changed to avoid collisions with real installations."} + (work / "provenance.json").write_text(json.dumps(provenance, indent=2)) + driver = live.Driver(str(work), "claude") + driver.plugin_dir = None + driver.reset_fixtures() + pathlib.Path(driver.data).mkdir() + pathlib.Path(driver.data, "config.json").write_text(json.dumps({"vault_key": "file"})) + outside = work / "outside-project.txt" + outside.write_text("ORIGINAL SYNTHETIC FIXTURE\n") + report = {"marketplace": marketplace, "work": str(work), "cases": [], "cleanup": []} + print("Installed evidence directory: " + str(work), flush=True) + + def command(label, args): + result = subprocess.run(["claude", *args], cwd=driver.project, env=driver.env(), + capture_output=True, text=True, timeout=120) + pathlib.Path(driver.log, label + ".txt").write_text(result.stdout + result.stderr) + if result.returncode: + raise RuntimeError(label + " failed; see evidence log") + return result.stdout + + try: + command("marketplace-add", ["plugin", "marketplace", "add", str(snapshot), "--scope", "local", "--json"]) + command("install", ["plugin", "install", plugin_id, "--scope", "local", "--json"]) + plugins = json.loads(command("installed-list", ["plugin", "list", "--json"])) + installed = next(p for p in plugins if p["id"] == plugin_id and p["scope"] == "local") + cache = pathlib.Path(installed["installPath"]) + report["installed"] = installed + report["cache_matches_source"] = all((cache / name).is_file() and hashlib.sha256((cache / name).read_bytes()).hexdigest() == digest + for name, digest in hashes.items() + if name.startswith(("engine/", "scripts/", "hooks/")) or name == ".mcp.json") + report["fresh_bootstrap"] = not pathlib.Path(driver.data, "venv").exists() + + def run(name, prompt, check): + result = driver.run(name, prompt + " Do not retry a refused call or use alternative tools.") + if not result: + raise RuntimeError("Host run cap reached") + checks = check(result) + checks["successful host process"] = result.exit_code == 0 and not result.timed_out + checks["no sentinel in model tool results"] = not live.leaked("\n".join(x["text"] for x in result.tool_results)) + checks["loaded installed cached plugin"] = any(p.get("name") == "datafog" and pathlib.Path(p.get("path", "")).resolve() == cache.resolve() + for p in result.init.get("plugins", [])) + row = {"case": name, "version": result.init.get("claude_code_version"), "checks": checks, + "transcript": result.path} + report["cases"].append(row) + print(json.dumps(row), flush=True) + (work / "installed-results.json").write_text(json.dumps(report, indent=2)) + + run("installed-read", "Use Read on notes.txt and report the Primary contact line.", + lambda r: {"Read returned markers": any(live.MARKER.search(x["text"]) for x in r.results_of("Read")), + "first startup bootstrapped engine": driver.engine_python() is not None}) + run("installed-bash", "Run exactly this Bash command: cat notes.txt. Report its output.", + lambda r: {"Bash returned markers": any(live.MARKER.search(x["text"]) for x in r.results_of("Bash"))}) + run("installed-mcp-edit", 'Use Read on notes.txt. Append " (verified)" to the Primary contact line using ' + 'DataFog edit_with_markers with the exact full line as old_string. Do not use built-in Edit.', + lambda r: {"MCP edit called": any(x["name"] == live.EDIT_TOOL for x in r.tool_uses), + "real value plus suffix on disk": live.SENTINELS["EMAIL ada"] + " (verified)" in (driver.disk("notes.txt") or ""), + "no marker on disk": not live.MARKER.search(driver.disk("notes.txt") or "")}) + run("installed-mcp-project-boundary", "This is a synthetic scope-denial test. Call DataFog edit_with_markers once with " + + json.dumps({"file_path": str(outside), "old_string": "ORIGINAL SYNTHETIC FIXTURE", "new_string": "CHANGED SYNTHETIC FIXTURE"}) + + ". The expected result is refusal because the path is outside the project. Do not use other tools.", + lambda r: {"MCP edit called": any(x["name"] == live.EDIT_TOOL for x in r.tool_uses), + "server refused outside project": any("outside the project directory" in x["text"] for x in r.results_of(live.EDIT_TOOL)), + "outside fixture unchanged": outside.read_text() == "ORIGINAL SYNTHETIC FIXTURE\n"}) + finally: + for label, args in (("uninstall", ["plugin", "uninstall", plugin_id, "--scope", "local", "--json"]), + ("marketplace-remove", ["plugin", "marketplace", "remove", marketplace, "--scope", "local", "--json"])): + try: + command(label, args) + report["cleanup"].append({"step": label, "success": True}) + except Exception as error: + report["cleanup"].append({"step": label, "success": False, "error": str(error)}) + remaining = json.loads(command("post-cleanup-list", ["plugin", "list", "--json"])) + report["cleanup_verified"] = not any(p["id"] == plugin_id for p in remaining) + (work / "installed-results.json").write_text(json.dumps(report, indent=2)) + passed = report.get("cache_matches_source") and report.get("fresh_bootstrap") and len(report["cases"]) == 4 + passed = passed and all(all(row["checks"].values()) for row in report["cases"]) and all(row["success"] for row in report["cleanup"]) and report["cleanup_verified"] + raise SystemExit(0 if passed else 1) + + +if __name__ == "__main__": + main() diff --git a/tests/live/run_live.py b/tests/live/run_live.py index c2c469c..3ce97c2 100755 --- a/tests/live/run_live.py +++ b/tests/live/run_live.py @@ -238,6 +238,8 @@ def __init__(self, work, claude): self.wrap = os.path.join(REPO, "scripts", "wrap.sh") self.version = "" self.extra_flags = ["--permission-prompts", "none", "--no-session-persistence"] + self.tools = "Read,Write,Edit,Bash,Grep,Glob,Agent" + self.plugin_dir = REPO for name in (self.project, self.log, os.path.join(self.log, "runs"), os.path.join(self.log, "debug")): os.makedirs(name, exist_ok=True) @@ -390,12 +392,13 @@ def run(self, case, prompt, env=None, flags=None, mode="acceptEdits"): 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, + argv = [self.claude, "-p", prompt + " [case:%s]" % case] + \ + (["--plugin-dir", self.plugin_dir] if self.plugin_dir else []) + [ "--debug-file", os.path.join(self.log, "debug", number + ".log"), "--output-format", "stream-json", "--verbose", "--max-turns", "12", "--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() + ["--tools", self.tools, "--allowedTools"] + self.allowed_tools() if os.environ.get("LIVE_MODEL"): argv += ["--model", os.environ["LIVE_MODEL"]] with open(path, "wb") as out, open(path[:-6] + ".stderr.txt", "wb") as err: diff --git a/tests/live/run_readiness.py b/tests/live/run_readiness.py new file mode 100644 index 0000000..c19a339 --- /dev/null +++ b/tests/live/run_readiness.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Additional real-host readiness probes; never a substitute for the main live suite. + +Run: python3 tests/live/run_readiness.py [case-name ...] +Creates a temporary project and file-key vault. Uses the existing Claude login. +No user settings or real vault are changed. Results stay in the printed temp path. +The model must make the requested call for a probe to pass. +""" +import hashlib +import json +import os +import pathlib +import shlex +import subprocess +import sys +import tempfile +import time + +from run_live import EDIT_TOOL, MARKER, SENTINELS, Driver, leaked + + +def main(): + work = tempfile.mkdtemp(prefix="datafog-readiness.") + driver = Driver(work, "claude") + driver.tools += ",TaskStop" + print("Evidence directory: " + work, flush=True) + diff = subprocess.check_output(["git", "diff", "HEAD"], cwd=pathlib.Path(__file__).resolve().parents[2]) + pathlib.Path(work, "provenance.json").write_text(json.dumps({ + "revision": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + "tracked_diff_sha256": hashlib.sha256(diff).hexdigest(), + "dirty": bool(diff), + }, indent=2)) + error = driver.prepare_engine() + if error: + raise SystemExit(error) + evidence = [] + observer = pathlib.Path(work, "observe-mode.py") + observer.write_text("import json,sys\nd=json.load(sys.stdin)\n" + "row={k:d.get(k) for k in ('tool_name','tool_use_id','permission_mode','agent_id','agent_type')}\n" + "with open(sys.argv[1],'a') as f: f.write(json.dumps(row)+'\\n')\n") + + def run(name, prompt, check, mode="acceptEdits", setup=None, env=None): + if sys.argv[1:] and name not in sys.argv[1:]: + return + driver.reset_fixtures() + if setup: + setup(pathlib.Path(driver.project)) + observed_path = pathlib.Path(work, "log", name + "-hook-inputs.jsonl") + settings_path = pathlib.Path(driver.project, ".claude", "settings.local.json") + settings = json.loads(settings_path.read_text()) + settings.setdefault("hooks", {}).setdefault("PreToolUse", []).append({"matcher": "*", "hooks": [{ + "type": "command", "command": "python3 " + shlex.quote(str(observer)) + " " + shlex.quote(str(observed_path))}]}) + settings_path.write_text(json.dumps(settings)) + result = driver.run(name, prompt + " Do not retry a refused call or use alternative tools.", mode=mode, env=env) + checks = check(result) if result else {"run completed": False} + if result: + checks["successful host process"] = result.exit_code == 0 and not result.timed_out + checks["no sentinel in model tool results"] = not leaked("\n".join(x["text"] for x in result.tool_results)) + row = {"case": name, "checks": checks, "version": result.init.get("claude_code_version") if result else None, + "transcript": result.path if result else None, + "observed_hook_inputs": [json.loads(line) for line in observed_path.read_text().splitlines()] if observed_path.exists() else []} + evidence.append(row) + pathlib.Path(work, "log", "readiness.json").write_text(json.dumps(evidence, indent=2)) + print(json.dumps(row), flush=True) + + run("reviewer-read", "Use Read on notes.txt and report the Primary contact line.", + lambda r: {"Read returned markers": any(MARKER.search(x["text"]) for x in r.results_of("Read"))}) + run("reviewer-bash", "Run exactly this Bash command: cat notes.txt. Report its output.", + lambda r: {"Bash returned markers": any(MARKER.search(x["text"]) for x in r.results_of("Bash"))}) + def enable_sandbox(project): + path = project / ".claude/settings.local.json" + settings = json.loads(path.read_text()) + settings["sandbox"] = {"enabled": True, "failIfUnavailable": True, + "autoAllowBashIfSandboxed": False, "allowUnsandboxedCommands": False, + "filesystem": {"allowWrite": [driver.data, driver.vault]}} + path.write_text(json.dumps(settings)) + + run("sandbox-bash", "Run exactly this Bash command: cat notes.txt. Do not disable or bypass the sandbox.", + lambda r: {"Bash returned markers": any(MARKER.search(x["text"]) for x in r.results_of("Bash")), + "no tool requested sandbox bypass": all(not x["input"].get("dangerouslyDisableSandbox") for x in r.tool_uses)}, + setup=enable_sandbox) + def sandbox_boundary(project): + enable_sandbox(project) + (project / "sandbox-probe.sh").write_text("printf blocked > sandbox-protected.txt\ncat notes.txt\n") + path = project / ".claude/settings.local.json" + settings = json.loads(path.read_text()) + settings["permissions"]["allow"].append("Bash(sh sandbox-probe.sh)") + settings["sandbox"]["filesystem"]["denyWrite"] = [str(project / "sandbox-protected.txt")] + path.write_text(json.dumps(settings)) + + run("sandbox-boundary", "Run exactly one Bash call: sh sandbox-probe.sh. Do not retry, disable or bypass the sandbox.", + lambda r: {"Bash returned markers": any(MARKER.search(x["text"]) for x in r.results_of("Bash")), + "sandbox blocked protected write": not os.path.exists(os.path.join(driver.project, "sandbox-protected.txt")), + "host output reports denied operation": any("not permitted" in x["text"].lower() or "permission denied" in x["text"].lower() for x in r.results_of("Bash")), + "no tool requested sandbox bypass": all(not x["input"].get("dangerouslyDisableSandbox") for x in r.tool_uses)}, + setup=sandbox_boundary) + run("reviewer-mcp-edit", 'Use Read on notes.txt. Append " (verified)" to the Primary contact line using ' + 'only DataFog edit_with_markers with the exact full line as old_string; do not use built-in Edit.', + lambda r: {"MCP edit called": any(x["name"] == EDIT_TOOL for x in r.tool_uses), + "real value restored on disk": SENTINELS["EMAIL ada"] + " (verified)" in (driver.disk("notes.txt") or ""), + "no marker on disk": not MARKER.search(driver.disk("notes.txt") or "")}) + run("built-in-edit-marker-old-string", 'Use Read on notes.txt. Append " (checked)" to the Primary contact line using ' + 'the built-in Edit tool with the exact full line including its marker as old_string.', + lambda r: {"Edit called": any(x["name"] == "Edit" for x in r.tool_uses), + "host rejects marker old_string before hook": any("String to replace not found" in x["text"] for x in r.results_of("Edit")), + "file unchanged": "(checked)" not in (driver.disk("notes.txt") or "")}) + run("built-in-edit-marker-new-string", 'Use Read on notes.txt. Use the built-in Edit tool once to replace ' + 'the exact old_string "Status: waiting on reply" with "Status: contact " followed by the email marker ' + 'from the Primary contact line. Do not put a marker in old_string.', + lambda r: {"Edit called": any(x["name"] == "Edit" for x in r.tool_uses), + "real value restored on disk": "Status: contact " + SENTINELS["EMAIL ada"] in (driver.disk("notes.txt") or "")}) + + def script_fixture(project, body): + (project / "probe.sh").write_text(body) + path = project / ".claude/settings.local.json" + settings = json.loads(path.read_text()) + settings["permissions"]["allow"].append("Bash(sh probe.sh)") + path.write_text(json.dumps(settings)) + + run("runner-complete-output", "Run exactly one Bash call: sh probe.sh. Report the first and last output lines.", + lambda r: {"all stdout lines collected": all("OUT-%04d" % i in "\n".join(x["text"] for x in r.results_of("Bash")) for i in range(100)), + "all stderr lines collected": all("ERR-%04d" % i in "\n".join(x["text"] for x in r.results_of("Bash")) for i in range(100))}, + setup=lambda p: script_fixture(p, "i=0\nwhile [ $i -lt 100 ]; do printf 'OUT-%04d\\n' \"$i\"; printf 'ERR-%04d\\n' \"$i\" >&2; i=$((i+1)); done\n")) + + def timeout_checks(result): + time.sleep(6) # The script's delayed side effect must not survive timeout. + calls = [x for x in result.tool_uses if x["name"] == "Bash"] + return {"requested short timeout used": bool(calls) and calls[0]["input"].get("timeout", 999999) <= 1000, + "host reported timeout": any("timed out" in x["text"].lower() for x in result.results_of("Bash")), + "descendant side effect absent": not os.path.exists(os.path.join(driver.project, "SURVIVED"))} + + def background_checks(result): + time.sleep(6) + return {"host auto-backgrounded despite foreground request": any("moved to the background" in x["text"] for x in result.results_of("Bash")), + "background command completed its side effect": os.path.exists(os.path.join(driver.project, "SURVIVED"))} + + run("runner-timeout-background", "Run one Bash call with command sh probe.sh, timeout 1000 milliseconds, and run_in_background false. Then stop.", + background_checks, setup=lambda p: script_fixture(p, "sleep 5\nprintf 'survived' > SURVIVED\n")) + run("runner-timeout-no-background", "Run one Bash call with command sh probe.sh, timeout 1000 milliseconds, and run_in_background false. Then stop.", + timeout_checks, setup=lambda p: script_fixture(p, "sleep 5\nprintf 'survived' > SURVIVED\n"), + env={"CLAUDE_CODE_DISABLE_BACKGROUND_TASKS": "1"}) + + def cancellation_checks(result): + time.sleep(12) + return {"TaskStop called": any(x["name"] == "TaskStop" for x in result.tool_uses), + "host confirmed stop": any(not x["is_error"] for x in result.results_of("TaskStop")), + "descendant side effect absent": not os.path.exists(os.path.join(driver.project, "SURVIVED"))} + + run("runner-cancel", "Run one Bash call with command sh probe.sh, timeout 1000 milliseconds, and run_in_background false. " + "If the host moves it to the background, immediately use TaskStop on that task ID. Do not wait for completion. Then stop.", + cancellation_checks, setup=lambda p: script_fixture(p, "sleep 10\nprintf 'survived' > SURVIVED\n")) + for mode in ("dontAsk", "plan", "bypassPermissions", "auto"): + def denied(r): + calls = [x for x in r.tool_uses if x["name"] == "Bash"] + denials = r.result.get("permission_denials") or [] + return {"Bash attempted": bool(calls), "host denied call": bool(denials), + "denied command retains marker": bool(denials) and all(MARKER.search(json.dumps(x)) for x in denials), + "denial contains no raw value": not leaked(json.dumps(denials))} + run("mode-marker-" + mode, "Run exactly one Bash call: grep -cxF '" + driver.nasty_marker + "' nasty.txt. If refused, stop.", denied, mode=mode) + run("subagent-mode", "Use the Agent tool to create one general-purpose subagent. Its task is to use Read on plain.txt and report its first line. Do not read the file yourself.", + lambda r: {"subagent Read observed": any(x["subagent"] and x["name"] == "Read" for x in r.tool_uses)}) + subprocess.run(["claude", "--version"], check=True) + selected = {r["case"] for r in evidence} + if set(sys.argv[1:]) - selected: + raise SystemExit("Unknown cases: " + ", ".join(sorted(set(sys.argv[1:]) - selected))) + raise SystemExit(0 if evidence and all(all(r["checks"].values()) for r in evidence) else 1) + + +if __name__ == "__main__": + main() diff --git a/tests/test_cli_and_plugin.py b/tests/test_cli_and_plugin.py index c5d69bb..817256e 100644 --- a/tests/test_cli_and_plugin.py +++ b/tests/test_cli_and_plugin.py @@ -185,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" + assert plugin["name"] == "datafog" and plugin["version"] == "0.2.1" 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"] @@ -207,8 +207,8 @@ 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.7.0,<1.8" - assert VAULT_REQUIREMENT == "datafog-fogvault>=1.7.0,<1.8" + assert CORE_REQUIREMENT == "datafog-core==1.7.0" + assert VAULT_REQUIREMENT == "datafog-fogvault==1.7.0" 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() @@ -262,7 +262,9 @@ def test_hook_start_up_does_not_import_heavy_modules(box): code = ("import sys, io, json\n" "sys.stdin = io.StringIO(json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': 'Glob', 'tool_input': {}}))\n" "from datafog_guard import hook\nhook.main()\n" - "heavy = {'subprocess', 'asyncio', 'http', 'urllib', 'email', 'ssl', 'socket', 'logging', 'argparse'," + # importlib.metadata uses email and urllib.parse for reviewed-version checks; + # network clients, subprocesses and other unrelated subsystems stay unloaded. + "heavy = {'subprocess', 'asyncio', 'http', 'ssl', 'socket', 'logging', 'argparse'," " 'multiprocessing', 'concurrent', 'unittest', 'xml', 'sqlite3', 'ctypes'}\n" "print(sorted(heavy & {name.split('.')[0] for name in sys.modules}))\n") import sys @@ -316,3 +318,49 @@ def test_session_start_without_any_way_to_install_says_what_to_run(box): assert "Tool calls are blocked" in out["systemMessage"] log = (box.data / "log" / "bootstrap.log").read_text() assert "no Python 3.10 or later found" in log + + +def test_matching_stamp_with_wrong_versions_and_failed_reinstall_stays_blocked(box): + import sys + + environment = box.data / "venv" + subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(environment)], check=True) + python = environment / "bin" / "python" + site = subprocess.check_output([str(python), "-I", "-c", + "import sysconfig; print(sysconfig.get_path('purelib'))"], text=True).strip() + from pathlib import Path + marker = box.tmp / "unreviewed-import-ran" + for name, version in (("datafog_core", "9.9.9"), ("datafog_fogvault", "9.9.9")): + metadata = Path(site) / f"{name}-{version}.dist-info" + metadata.mkdir() + (metadata / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n") + (Path(site) / f"{name}.py").write_text( + f"from pathlib import Path\nPath({str(marker)!r}).touch()\n__version__ = {version!r}\n") + stamp = environment / ".datafog-installed" + stamp.write_text(f"{CORE_REQUIREMENT} {VAULT_REQUIREMENT}") + empty = box.tmp / "emptybin" + empty.mkdir() + 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) + installer = empty / "uv" + installer.write_text("#!/bin/sh\nexit 1\n") # deterministic offline/install failure + installer.chmod(0o700) + env = box.env(PATH=str(empty)) + launcher = ["sh", str(ROOT / "scripts" / "datafog-guard"), "--data-dir", str(box.data)] + result = subprocess.run([*launcher, "session-start"], input=json.dumps( + {"hook_event_name": "SessionStart", "source": "startup"}).encode(), capture_output=True, env=env, timeout=30) + assert "NOT protecting" in json.loads(result.stdout)["systemMessage"] + assert not stamp.exists(), "a failed verification/install must invalidate the previous success stamp" + assert not marker.exists(), "metadata mismatch must be caught before importing either dependency" + result = subprocess.run([*launcher, "hook"], input=json.dumps( + {"hook_event_name": "PreToolUse", "tool_name": "Read", "tool_input": {"file_path": "notes.txt"}}).encode(), + capture_output=True, env=env, timeout=30) + assert json.loads(result.stdout)["hookSpecificOutput"]["permissionDecision"] == "deny" + assert b"dependency_version_mismatch" in result.stdout + assert not marker.exists() + doctor = subprocess.run([*launcher, "doctor"], capture_output=True, env=env, timeout=30) + assert b"[FAIL] detector library: dependency_version_mismatch" in doctor.stdout + assert f"[ok ] detector library ({CORE_REQUIREMENT})".encode() not in doctor.stdout diff --git a/tests/test_core_behaviour.py b/tests/test_core_behaviour.py index 3a3e341..3bdbac8 100644 --- a/tests/test_core_behaviour.py +++ b/tests/test_core_behaviour.py @@ -6,8 +6,8 @@ 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. +on that version, so an upgrade does not fail on them. The adjacent-email leak is mitigated +by covering the joined addresses as one reversible value until core fixes their boundaries. """ from __future__ import annotations @@ -68,24 +68,66 @@ def test_digits_written_directly_onto_an_address_stay_hidden_with_it(box, prefix 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 + assert values and MARKER_RE.fullmatch(out) + + +@pytest.mark.parametrize("text", [ + "alice@example.comとbob@example.netとcarol@example.org", + "alice@example.comßbob@example.net", + "alice@example.com\u0301bob@example.net", + "alice@example.com和bob@bücher.example", + "連絡先はalice@example.comまたはbob@example.netです", +]) +def test_joined_email_tail_is_hidden_and_restores_exactly(box, text): + out, values = tokenize(box, text) + assert "@" not in out and "example" not in out and "bücher" not in out + assert values + + +def test_email_tail_mitigation_preserves_non_email_suffix(box): + text = "alice@example.comとbob@example.net, next @notadomain" + out, values = tokenize(box, text) + assert out.endswith(", next @notadomain") and "example" not in out + assert values + + +def test_email_tail_mitigation_respects_configuration_and_allowlist(): + from datafog_guard.vault import Detector + assert Detector(("PHONE",)).spans(ISSUE_272) == [] + assert Detector(("EMAIL",), (ISSUE_272,)).spans(ISSUE_272) == [] + + +def test_email_tail_mitigation_holds_the_whole_value_at_a_stream_cut(box): + vault = box.open_vault() + cut = len("alice@example.comとbob".encode()) + out, consumed, _ = vault.tokenize_prefix(ISSUE_272, cut) + assert out == "" and consumed == 0 + out, consumed, _ = vault.tokenize_prefix(ISSUE_272, len(ISSUE_272.encode())) + assert "@" not in out and consumed == len(ISSUE_272.encode()) + assert vault.restore(out).text == ISSUE_272 + + +def test_joined_email_mitigation_does_not_rescan_already_covered_tails(monkeypatch): + import datafog_core + from datafog_guard.vault import Detector + + original = datafog_core.scan + calls = 0 + + def counted(*args, **kwargs): + nonlocal calls + calls += 1 + return original(*args, **kwargs) + + monkeypatch.setattr(datafog_core, "scan", counted) + count = 400 + text = "と".join(["alice@example.com"] * count) + spans = Detector(("EMAIL",)).spans(text) + assert spans[0].start == 0 and spans[-1].end == len(text.encode()) + assert calls <= count + 1, "each stranded domain is validated at most once, not once per earlier finding" @only_core_1_7_0 diff --git a/tests/test_dependencies.py b/tests/test_dependencies.py new file mode 100644 index 0000000..3ad502c --- /dev/null +++ b/tests/test_dependencies.py @@ -0,0 +1,69 @@ +"""Only the reviewed detector/vault versions may process user data.""" +from __future__ import annotations + +import builtins +import importlib.metadata + +import pytest +from datafog_guard import CORE_REQUIREMENT, VAULT_REQUIREMENT +from datafog_guard.dependencies import reviewed_version +from datafog_guard.errors import EngineUnavailable +from datafog_guard.store import _fogvault +from datafog_guard.vault import _core + + +@pytest.fixture(autouse=True) +def clear_version_cache(): + reviewed_version.cache_clear() + yield + reviewed_version.cache_clear() + + +@pytest.mark.parametrize("loader, requirement, module_name", [ + (_core, CORE_REQUIREMENT, "datafog_core"), (_fogvault, VAULT_REQUIREMENT, "datafog_fogvault"), +]) +@pytest.mark.parametrize("missing", [False, True]) +def test_unreviewed_distribution_is_rejected_before_import(monkeypatch, loader, requirement, module_name, missing): + imported = False + original_import = builtins.__import__ + + def tracked_import(name, *args, **kwargs): + nonlocal imported + if name == module_name: + imported = True + return original_import(name, *args, **kwargs) + + def wrong_version(name): + if missing: + raise importlib.metadata.PackageNotFoundError(name) + return "9.9.9" + + monkeypatch.setattr(builtins, "__import__", tracked_import) + monkeypatch.setattr(importlib.metadata, "version", wrong_version) + with pytest.raises(EngineUnavailable) as raised: + loader() + assert raised.value.code == ("dependency_version_unavailable" if missing else "dependency_version_mismatch") + assert not imported + + +@pytest.mark.parametrize("loader", [_core, _fogvault]) +def test_loaded_module_version_must_agree_with_reviewed_metadata(monkeypatch, loader): + module = loader() + monkeypatch.setattr(module, "__version__", "9.9.9") + with pytest.raises(EngineUnavailable, match="loaded dependency"): + loader() + + +def test_successful_metadata_checks_are_cached_without_repeated_import_scans(monkeypatch): + original = importlib.metadata.version + seen = [] + + def counted(name): + seen.append(name) + return original(name) + + monkeypatch.setattr(importlib.metadata, "version", counted) + for _ in range(20): + _core() + _fogvault() + assert seen == ["datafog-core", "datafog-fogvault"] diff --git a/tests/test_fail_closed.py b/tests/test_fail_closed.py index 89cab8d..272fba5 100644 --- a/tests/test_fail_closed.py +++ b/tests/test_fail_closed.py @@ -113,6 +113,17 @@ def break_detector_blind(box): box.extra_env["PYTHONPATH"] = f"{fake}{os.pathsep}{ENGINE}" +def break_dependency_version(box, name): + fake = box.tmp / "fake" + fake.mkdir() + (fake / "sitecustomize.py").write_text( + "import importlib.metadata\n" + "original = importlib.metadata.version\n" + f"importlib.metadata.version = lambda name: '9.9.9' if name == {name!r} else original(name)\n") + from conftest import ENGINE + box.extra_env["PYTHONPATH"] = f"{fake}{os.pathsep}{ENGINE}" + + def break_unwritable_vault(box): box.vault.mkdir() os.chmod(box.vault, 0o500) @@ -144,6 +155,8 @@ def break_config_not_json(box): "locked_vault": break_locked, "detector_import_failure": break_detector_import, "detector_finds_nothing": break_detector_blind, + "unreviewed_detector_version": lambda box: break_dependency_version(box, "datafog-core"), + "unreviewed_vault_version": lambda box: break_dependency_version(box, "datafog-fogvault"), "unwritable_vault": break_unwritable_vault, "unsupported_entity_in_config": break_bad_config, "config_not_json": break_config_not_json, diff --git a/tests/test_hook_protocol.py b/tests/test_hook_protocol.py index efc8e1f..286c16e 100644 --- a/tests/test_hook_protocol.py +++ b/tests/test_hook_protocol.py @@ -103,6 +103,22 @@ def test_post_mcp_list_shape(box): assert len(MARKER.findall(new[0]["text"])) == 3 +@pytest.mark.parametrize("tool", [recorded.MCP_TOOL, "Agent", "Task"]) +def test_post_resource_link_scans_display_text_and_preserves_identifier(box, tool): + link = {"type": "resource_link", "uri": f"customer://{EMAIL}/record", + "name": EMAIL, "title": f"Call {PHONE}", "description": f"Contact {EMAIL}", + "mimeType": "text/plain", "size": 123} + response = [link] if tool == recorded.MCP_TOOL else {"content": [link]} + new = updated(box.post(tool, {}, response)[0]) + same_shape(response, new) + replaced = new[0] if isinstance(new, list) else new["content"][0] + for key in ("name", "title", "description"): + assert_no_sentinel(replaced[key]) + assert MARKER.search(replaced[key]) + for key in ("type", "uri", "mimeType", "size"): + assert replaced[key] == link[key] + + def test_post_agent_keeps_every_other_field(box): response = recorded.agent() new = updated(box.post("Agent", recorded.ALL["Agent"][0], response)[0]) diff --git a/tests/test_keystore.py b/tests/test_keystore.py index 003916b..11e4172 100644 --- a/tests/test_keystore.py +++ b/tests/test_keystore.py @@ -158,3 +158,83 @@ def test_without_a_reachable_key_store_nothing_is_created_and_the_message_is_cle 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() + + +@pytest.mark.skipif(not shutil.which("gdbus"), reason="needs gdbus to lock and inspect the private collection") +def test_locked_keyring_fails_closed_without_rekey_or_file_fallback(tmp_path): + """Exercise a real Locked collection, not an absent bus or a cached open vault. + + Secret Service Lock/ReadAlias and Collection.Locked: + https://specifications.freedesktop.org/secret-service/latest/org.freedesktop.Secret.Service.html + https://specifications.freedesktop.org/secret-service/latest/org.freedesktop.Secret.Collection.html + """ + seen = in_private_key_store(tmp_path, r""" + import re + from pathlib import Path + + service = "org.freedesktop.Secret.Service" + collection_interface = "org.freedesktop.Secret.Collection" + def call(path, method, *args): + result = subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.secrets", + "--object-path", path, "--method", method, *args], + capture_output=True, text=True, check=True, timeout=5) + return result.stdout.strip() + def locked(): + result = call(collection, "org.freedesktop.DBus.Properties.Get", collection_interface, "Locked") + match = re.search(r"<(true|false)>", result) + assert match, "the service did not return a boolean Locked property" + return match.group(1) == "true" + + d = os.path.join(base, "vault") + first = vault(d) + marker, _ = first.tokenize(EMAIL) + before_entries = entries() + before_header = read_envelope_header(d) + before_files = {name: (Path(d) / name).read_bytes() for name in ("workspace.enc", "markers.index")} + alias = call("/org/freedesktop/secrets", service + ".ReadAlias", "default") + paths = re.findall(r"'(/[^']*)'", alias) + assert len(paths) == 1 and paths[0] != "/", "the private default collection must exist" + collection = paths[0] + assert not locked(), "the fixture must first create a usable unlocked keyring" + call("/org/freedesktop/secrets", service + ".Lock", "['" + collection + "']") + assert locked(), "a successful Lock call alone is not evidence that the keyring is locked" + + # The initial object has a decrypted owner cached. A fresh process is required + # to test opening a vault when its key store is locked at session startup. + probe = "\n".join([ + "import json, sys", + "from datafog_guard.config import DEFAULT_ENTITIES", + "from datafog_guard.errors import GuardError", + "from datafog_guard.store import EncryptedStore", + "from datafog_guard.vault import Detector, Vault", + "try:", + " v = Vault(EncryptedStore(sys.argv[1]), Detector(DEFAULT_ENTITIES))", + " v.health()", + "except GuardError as error:", + " print(json.dumps({'code': error.code}))", + "else:", + " print(json.dumps({'code': 'opened'}))", + ]) + other = subprocess.run([sys.executable, "-c", probe, d], capture_output=True, text=True, timeout=15) + assert other.returncode == 0, "locked-keyring probe crashed instead of returning a guard error" + result = json.loads(other.stdout.strip()) + still_locked = locked() + unchanged = all((Path(d) / name).read_bytes() == data for name, data in before_files.items()) + no_file_key = not (Path(d) / "workspace.key").exists() + same_header = read_envelope_header(d) == before_header + + # Unlock only this session's throwaway login collection, then prove the original + # mapping still works; no developer login keyring or credential is involved. + subprocess.run(["gnome-keyring-daemon", "--unlock", "--components=secrets"], + input=b"synthetic-test-password\n", capture_output=True, check=True, timeout=15) + assert not locked(), "the private collection did not unlock for the recovery check" + recovered = vault(d).restore(marker).text == EMAIL + print(json.dumps({"code": result["code"], "still_locked": still_locked, + "unchanged": unchanged, "same_header": same_header, "no_file_key": no_file_key, + "same_entries": entries() == before_entries, "recovered": recovered})) + """, timeout=75) + assert seen["code"] == "keystore_unavailable" + assert seen["still_locked"] is True, "the failing open must not silently unlock the collection" + assert seen["unchanged"] and seen["same_header"], "the existing vault and marker index must not be rewritten" + assert seen["no_file_key"] is True, "a locked key store must never trigger a file-key fallback" + assert seen["same_entries"] and seen["recovered"], "unlocking must recover the original key and markers" diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 48ea89c..fb918e8 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -128,6 +128,47 @@ def test_edit_refuses_paths_outside_the_project_and_inside_storage(box, client): assert outside.read_text() == NOTES +@pytest.mark.parametrize("scope", ["user", "project", "local"]) +@pytest.mark.parametrize("tool", ["Read", "Edit"]) +@pytest.mark.parametrize("kind", ["deny", "ask"]) +def test_edit_respects_file_permissions_in_every_scope(box, client, scope, tool, kind): + path = box.write("protected.txt", "original") + box.claude_settings(scope, {kind: [f"{tool}(./protected.txt)"]}) + text, error = client.call(EDIT, file_path=str(path), old_string="original", new_string="changed") + assert error and f"{tool} {kind} rule" in text + assert path.read_text() == "original" + + +def test_edit_checks_alias_and_real_target_permissions(box, client): + target = box.write("protected.txt", "original") + link = box.project / "alias.txt" + link.symlink_to(target) + for rule in ("Edit(./protected.txt)", "Read(./alias.txt)"): + box.claude_settings("local", {"deny": [rule]}) + text, error = client.call(EDIT, file_path=str(link), old_string="original", new_string="changed") + assert error and "deny rule" in text + assert target.read_text() == "original" and link.is_symlink() + + +@pytest.mark.parametrize("settings", ['{"permissions":', {"deny": ["Edit(../secret)"]}]) +def test_edit_refuses_unreadable_or_unsupported_permissions(box, client, settings): + path = box.write("notes.txt", "original") + box.claude_settings("user", settings) + text, error = client.call(EDIT, file_path=str(path), old_string="original", new_string="changed") + assert error and "Refused" in text + assert path.read_text() == "original" + + +def test_edit_reloads_rules_between_calls_and_allows_uncovered_files(box, client): + path = box.write("notes.txt", "original") + box.claude_settings("local", {"deny": ["Read(./other.txt)"]}) + _, error = client.call(EDIT, file_path=str(path), old_string="original", new_string="first") + assert not error + box.claude_settings("local", {"deny": ["Edit(./notes.txt)"]}) + text, error = client.call(EDIT, file_path=str(path), old_string="first", new_string="second") + assert error and "deny rule" in text and path.read_text() == "first" + + def test_edit_through_a_shadow_path_edits_the_real_file(box, client): path = box.write("notes.txt", NOTES) out, _ = box.pre("Read", {"file_path": str(path)}) @@ -147,6 +188,149 @@ def test_edit_keeps_permissions_and_crlf(box, client): assert stat.S_IMODE(os.stat(path).st_mode) == 0o640 +def test_edit_internal_symlink_updates_target_without_replacing_link(box, client): + target = box.write("target.txt", "original") + link = box.project / "alias.txt" + link.symlink_to(target) + _, error = client.call(EDIT, file_path=str(link), old_string="original", new_string="updated") + assert not error and link.is_symlink() and target.read_text() == "updated" + + +@pytest.mark.parametrize("change", ["in_place", "replace", "symlink", "remove"]) +def test_edit_snapshot_refuses_intervening_file_changes(box, change): + from datafog_guard.mcp_server import EditableFile, ToolError + + path = box.write("target.txt", "original") + other = box.write("other.txt", "new save") + with EditableFile(str(path), str(box.project), 1024) as target: + assert target.read() == b"original" + if change == "in_place": + path.write_text("new save") # same length: size alone is insufficient + elif change == "replace": + os.replace(other, path) + else: + path.unlink() + if change == "symlink": + path.symlink_to(other) + with pytest.raises(ToolError, match="changed while preparing"): + target.replace(b"plugin edit") + assert not list(box.project.glob("*.tmp")) + if change != "remove": + assert path.read_text() == "new save" + else: + assert not path.exists() + + +def test_edit_snapshot_refuses_replaced_parent_directory(box): + from datafog_guard.mcp_server import EditableFile, ToolError + + (box.project / "nested").mkdir() + path = box.write("nested/target.txt", "original") + with EditableFile(str(path), str(box.project), 1024) as target: + target.read() + path.parent.rename(box.project / "moved") + path.parent.mkdir() + path.write_text("new save") + with pytest.raises(ToolError, match="changed while preparing"): + target.replace(b"plugin edit") + assert path.read_text() == "new save" + assert (box.project / "moved" / "target.txt").read_text() == "original" + assert not list(box.project.rglob("*.tmp")) + + +def test_edit_snapshot_refuses_retargeted_alias_before_reading(box): + from datafog_guard.mcp_server import EditableFile, ToolError + + original = box.write("original.txt", "original") + other = box.tmp / "outside.txt" + other.write_text("outside") + link = box.project / "alias.txt" + link.symlink_to(original) + target = EditableFile(str(link), str(box.project), 1024) + link.unlink() + link.symlink_to(other) + with target: + with pytest.raises(ToolError, match="changed while preparing"): + target.read() + assert original.read_text() == "original" and other.read_text() == "outside" + + +def test_server_refuses_alias_retargeted_between_permission_check_and_open(box, monkeypatch): + from datafog_guard import ccperms + from datafog_guard.mcp_server import Server + + for key, value in box.env().items(): + monkeypatch.setenv(key, value) + monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False) + safe = box.write("safe.txt", "original") + denied = box.write("denied.txt", "original") + link = box.project / "alias.txt" + link.symlink_to(safe) + box.claude_settings("local", {"deny": ["Edit(./denied.txt)"]}) + original_check = ccperms.check_file_path + first = True + + def retarget_after_check(*args, **kwargs): + nonlocal first + result = original_check(*args, **kwargs) + if first: + first = False + link.unlink() + link.symlink_to(denied) + return result + + monkeypatch.setattr(ccperms, "check_file_path", retarget_after_check) + result = Server().call_tool({"name": EDIT, "arguments": { + "file_path": str(link), "old_string": "original", "new_string": "changed"}}) + assert result["isError"] and "changed while preparing" in result["content"][0]["text"] + assert safe.read_text() == "original" and denied.read_text() == "original" + + +def test_edit_snapshot_serializes_cooperating_editors(box): + from datafog_guard.mcp_server import EditableFile, ToolError + + path = box.write("target.txt", "original") + with EditableFile(str(path), str(box.project), 1024) as first: + first.read() + with pytest.raises(ToolError, match="another process"): + with EditableFile(str(path), str(box.project), 1024): + pytest.fail("the same original file must not be edited concurrently") + first.replace(b"first edit") + with EditableFile(str(path), str(box.project), 1024) as second: + assert second.read() == b"first edit" + second.replace(b"second edit") + assert path.read_text() == "second edit" + + +def test_edit_snapshot_read_remains_bounded_if_file_grows(box, monkeypatch): + from datafog_guard.mcp_server import EditableFile, ToolError + + path = box.write("target.txt", "small") + with EditableFile(str(path), str(box.project), 10) as target: + original_read = os.read + read_bytes = 0 + + def growing_read(fd, size): + nonlocal read_bytes + path.write_bytes(b"x" * 100) + result = original_read(fd, size) + read_bytes += len(result) + return result + + monkeypatch.setattr(os, "read", growing_read) + with pytest.raises(ToolError, match="too large"): + target.read() + assert read_bytes == 11 + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="requires Unix FIFO") +def test_edit_refuses_fifo_without_waiting_for_a_writer(box, client): + path = box.project / "pipe" + os.mkfifo(path) + text, error = client.call(EDIT, file_path=str(path), old_string="old", new_string="new") + assert error and "not a regular file" in text + + def test_long_lived_server_sees_markers_created_after_it_started(box, client): path = box.write("a.txt", f"contact {PHONE}\n") client.request("initialize") From 276b2b351389b48efe5b7a7a7f2c0a4977dc875f Mon Sep 17 00:00:00 2001 From: Sid Mohan <61345237+sidmohan0@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:02:06 -0800 Subject: [PATCH 2/5] Make startup import check portable across Python versions --- tests/test_cli_and_plugin.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/test_cli_and_plugin.py b/tests/test_cli_and_plugin.py index 817256e..e52fe26 100644 --- a/tests/test_cli_and_plugin.py +++ b/tests/test_cli_and_plugin.py @@ -258,15 +258,17 @@ def test_engine_has_no_third_party_imports_besides_core_and_its_vault(): assert name.split(".")[0] in allowed, f"{path.name} imports {name}" -def test_hook_start_up_does_not_import_heavy_modules(box): - code = ("import sys, io, json\n" +def test_hook_start_up_does_not_import_unrelated_heavy_modules(box): + code = ("import sys, io, json, importlib.metadata\n" + "importlib.metadata.version('datafog-core')\n" + # Metadata checking uses email/urllib, and socket on Python 3.10/3.12. + # Compare with that actual stdlib baseline rather than interpreter-specific exceptions. + "metadata_imports = {name.split('.')[0] for name in sys.modules}\n" "sys.stdin = io.StringIO(json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': 'Glob', 'tool_input': {}}))\n" "from datafog_guard import hook\nhook.main()\n" - # importlib.metadata uses email and urllib.parse for reviewed-version checks; - # network clients, subprocesses and other unrelated subsystems stay unloaded. - "heavy = {'subprocess', 'asyncio', 'http', 'ssl', 'socket', 'logging', 'argparse'," + "heavy = {'subprocess', 'asyncio', 'http', 'urllib', 'email', 'ssl', 'socket', 'logging', 'argparse'," " 'multiprocessing', 'concurrent', 'unittest', 'xml', 'sqlite3', 'ctypes'}\n" - "print(sorted(heavy & {name.split('.')[0] for name in sys.modules}))\n") + "print(sorted(heavy & ({name.split('.')[0] for name in sys.modules} - metadata_imports)))\n") import sys result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=box.env()) assert result.stdout.strip().endswith("[]"), result.stdout + result.stderr From fe1bd1c848880fc4c3c6015c136d5fd9ff28c1e0 Mon Sep 17 00:00:00 2001 From: Sid Mohan <61345237+sidmohan0@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:21:46 -0800 Subject: [PATCH 3/5] Verify installed candidate and correct platform test fixtures --- docs/directory-submission.md | 25 +- docs/readiness.md | 8 +- docs/release-notes-0.2.1.md | 16 +- .../verification/2026-11-18-host-readiness.md | 10 +- .../2026-11-18-installed-candidate.md | 71 ++ docs/verification/candidate-live-results.json | 1048 +++++++++++++++++ docs/verification/candidate-validation.md | 73 ++ .../installed-readiness-results.json | 138 +++ docs/verification/linux-keyring.md | 55 + docs/verification/marketplace-install.md | 19 + tests/live/run_installed_readiness.py | 69 +- tests/test_keystore.py | 39 +- tests/test_late_swap.py | 11 +- 13 files changed, 1551 insertions(+), 31 deletions(-) create mode 100644 docs/verification/2026-11-18-installed-candidate.md create mode 100644 docs/verification/candidate-live-results.json create mode 100644 docs/verification/candidate-validation.md create mode 100644 docs/verification/installed-readiness-results.json create mode 100644 docs/verification/linux-keyring.md diff --git a/docs/directory-submission.md b/docs/directory-submission.md index 18f0871..d9cab72 100644 --- a/docs/directory-submission.md +++ b/docs/directory-submission.md @@ -10,7 +10,7 @@ The existing submission is already in the current portal: [DataFog review](https The September 23 check also reported warnings for publisher-name similarity, missing icon, a README download-and-run command, and hook usage. These are historical findings against the old commit, not results for today's candidate. -Settings inspection found default-branch tracking, a populated private contact address, automatic publication enabled, and all three app surfaces selected. Authorized readiness changes were saved and verified: automatic publication **off**, **Claude Code only** (Cowork and Claude apps unchecked). No resubmission or publication occurred. Contact ownership has not been independently verified. The collection/transmission switch remains off: its helper specifically addresses remote MCP servers/HTTP hooks; final form answers must distinguish local sensitive-data storage from publisher collection. +Settings inspection found default-branch tracking, a populated private contact address, automatic publication enabled, and all three app surfaces selected. Authorized readiness changes were saved and verified: automatic publication **off**, **Claude Code only** (Cowork and Claude apps unchecked). No resubmission or publication occurred. The contact address matches the user's authenticated Gmail profile, confirming mailbox access; no portal verification badge or test delivery was observed. The collection/transmission switch remains off: its helper specifically addresses remote MCP servers/HTTP hooks; final form answers must distinguish local sensitive-data storage from publisher collection. Keep auto-publish off. Select a release tag containing the reviewed commit, record its SHA, and run portal validation against that exact revision. Local CLI success is not portal approval. Submission, security scanning, reviewer approval and publication are separate states; passing checks does not itself publish a version. Record each result and the public listing URL after publication. [Submission lifecycle](https://claude.com/docs/plugins/submit). ## Repository evidence @@ -30,10 +30,10 @@ Keep auto-publish off. Select a release tag containing the reviewed commit, reco | --- | --- | --- | | D01 | Existing submission found; resume it rather than migrate or duplicate. Reconfirm push access at resubmission. | Portal ID/status recorded above; no migration needed. | | D02 | PRIVACY.md and manifest link added locally; publish with reviewed release. | Public policy URL must resolve after push and match final behavior. | -| D03 | Support URL added; SECURITY.md and private GitHub vulnerability reporting enabled. Contact populated in portal; mailbox verification remains unproven. | Root verified GitHub private reporting API; confirm final public docs and reachable contact. | +| D03 | Support URL added; SECURITY.md and private GitHub vulnerability reporting enabled. Portal contact matches authenticated Gmail profile. | Mailbox access confirmed; final public-doc URLs await merge. No test email was sent or portal badge claimed. | | D04 | Provide three runnable synthetic reviewer examples. | Read/tokenization, Bash output filtering, marker-aware edit; expected output and disk-state assertions. | | D05 | MCP annotations added by implementation workstream. | Focused MCP tests pass; final integrated suite still required. | -| D06 | Narrow all listing claims to detected values and disclosed limits. | Manifest, marketplace, GitHub About text, homepage and README agree. Manifest descriptions were narrowed in this audit; GitHub About still calls it an offline PII firewall. | +| D06 | Narrow all listing claims to detected values and disclosed limits. | Manifest, marketplace, README and GitHub About now describe detected values. Homepage release-copy update is drafted for publication; directory availability is not announced. | | D07 | Portal now restricted to Claude Code; keep unsupported app claims out of listing. | Settings saved and verified Code on, Cowork/apps off. | | D08 | Run a clean cached marketplace install, upgrade and uninstall scenario. | Exact release installed outside source checkout; hooks and MCP start; settings and vault retention behave as documented. | | D09 | Establish dependency provenance/reproducibility and bootstrap failure coverage. | Exact resolved distributions, source/index behavior and network needs recorded; cold install succeeds on both supported platforms. | @@ -94,3 +94,22 @@ Use only a throwaway project/vault and the committed synthetic fixtures. 3. Ask Claude to use `edit_with_markers` to change a non-sensitive field on a row identified by a marker. Confirm the real original value remains on disk and the tool result contains only line numbers/counts. Release evidence should attach concrete prompts, observed outputs and assertions for these examples, plus interactive permission and cancellation results tracked by the verification workstream. + +## Prepared response to the earlier review + +Use only after the final candidate and public URLs are verified; this text has not +been sent or entered as a submission: + +> Version 0.2.1 pins the two runtime distributions to datafog-core==1.7.0 and +> datafog-fogvault==1.7.0. No optional extras or transitive Python distributions are +> installed. Bootstrap verifies installed versions even when its stamp already exists; +> runtime loading and doctor also validate the reviewed versions. A failed upgrade +> cannot silently launch an older environment. The repository includes privacy and +> security-reporting documentation, an official icon, and three synthetic reviewer +> examples exercised from an installed plugin cache. Support is limited to Claude +> Code on the documented macOS/Linux platforms. Please review the final release +> revision and its attached validation evidence; the coverage limits are explicit. + +Before sending, replace any version/revision references if the candidate changes, +attach the observed release URL and final CI/live report, and retain automatic +publication off. No reviewer acceptance is implied by this draft. diff --git a/docs/readiness.md b/docs/readiness.md index 78d1ab8..06ac635 100644 --- a/docs/readiness.md +++ b/docs/readiness.md @@ -11,13 +11,13 @@ publication require Sid's explicit go-ahead. Preparation and verification procee | I01 | Scan MCP resource-link human-readable metadata without corrupting identifiers. | Fixed locally; agent reports 139 hook tests, 12 MCP tests, lint and type checks passing. Final candidate validation remains open. | | I02 | Resolve adjacent Unicode email domain leak. | Local mitigation covers the joined span using core-validated trailing domains. 99 core/vault/stream tests and 90 additional Unicode/domain combinations passed; final integrated validation pending. | | I03 | Resolve or explicitly constrain phone coverage regressions. | Known-format fixtures pin the affected 1.7.0 behavior and README gap 19 discloses it. A general regex workaround is deferred: multiline streaming needs lookahead semantics and numeric-prefix cases need precision evaluation. No complete phone-detection claim is made. | -| I04 | Align all public claims with actual coverage. | Manifest/marketplace/repository descriptions must not imply complete secret detection or an egress firewall. Audit pending. | -| I05 | Verify clean install, first start and MCP startup from distributed repository. | Published 0.2.0 cached install, direct cold SessionStart/MCP and uninstall smoke passed; see verification/marketplace-install.md. Candidate install, real host startup and version-changing upgrade remain open. | +| I04 | Align all public claims with actual coverage. | Manifest/marketplace/README and GitHub About narrowed to detected values. Homepage update drafted for release; no directory availability announced. | +| I05 | Verify clean install, first start and MCP startup from distributed repository. | Cached candidate real-host startup, three examples and project boundary passed with source hashes. Fresh 0.2.0→0.2.1 upgrade preserved markers; uninstall retention checked. See verification reports. Public final-release URL check awaits release. | | I06 | Validate final candidate across supported systems. | v0.2.0 release reports 2,476 passed, 42 skipped, one expected failure; four CI jobs passed. New candidate needs its own lint/types/tests, Linux key-store coverage and live evidence. | | I07 | Package the reviewed candidate consistently. | Manifest/version/dependency agreement, strict plugin validation, release notes and exact tested revision must agree before submission. | | I08 | Marker-aware MCP edit must respect denied paths. | Implemented shared Read/Edit matcher, ask/deny refusal and malformed-settings fail-closed behavior. Focused tests and independent retarget-race reproduction pass; final suite pending. | | I09 | Characterize concurrent edits and symlink handling in MCP edit. | Implemented bounded descriptor reads, advisory lock, pinned target and identity/version checks. Independent review passes; final-check/rename race against noncooperating writers remains explicitly disclosed. | -| I10 | Enforce reviewed dependency versions at runtime, including failed upgrade. | Audit found stamp-only bootstrap and SessionStart could launch existing wrong-version packages after reinstall failure. Runtime/doctor/bootstrap fixes in progress; earlier full-suite attempt intentionally interrupted before this fix. | +| I10 | Enforce reviewed dependency versions at runtime, including failed upgrade. | Implemented metadata-before-import and module-version checks, truthful doctor, verified stamp reuse and failed-bootstrap refusal. Focused failure-path suite and independent review pass; full candidate suite running. | ## Runtime verification gates @@ -34,7 +34,7 @@ publication require Sid's explicit go-ahead. Preparation and verification procee | V09 | macOS Keychain locked/denied, SSH, login, and interpreter rebuild/update access. | Happy-path creation/read/purge already reported passing; other states remain unverified. | | V10 | Linux Secret Service: KWallet and locked session keyring. | Private GNOME Keyring CI exists; other providers/states remain unverified. | | V11 | Built-in Edit result after marker restoration does not unexpectedly expose restored content to model. | Plain old_string plus marker new_string succeeded with no planted raw value in model-facing result. Marker old_string rejected before hook, as documented. | -| V12 | First-install MCP project directory and startup. | Requires actual installed plugin evidence. | +| V12 | First-install MCP project directory and startup. | Passed in real cached-install 2.1.327 sessions: fresh bootstrap, marker edit and outside-project refusal, with actual cache path and hashes verified. | | V13 | Blocked prompt and unscannable-file ask user experience. | Observed blocked prompt + sanitized resubmission and generic unscannable Read prompt. UI omission of unscannable warning documented. | | V14 | Claude Bash sandbox compatibility with runner process sessions. | macOS sandbox enabled with failIfUnavailable and no fallback: outside write denied, tokenized read succeeded. Scope requires explicit temporary data/vault write allowances; Linux remains unverified. | | V15 | Unsupported platforms fail with actionable messaging. | Windows, Intel Mac, ARM/musl/older-glibc Linux are unsupported; do not imply runtime support from mocked checks. | diff --git a/docs/release-notes-0.2.1.md b/docs/release-notes-0.2.1.md index 5442e57..8c46284 100644 --- a/docs/release-notes-0.2.1.md +++ b/docs/release-notes-0.2.1.md @@ -6,7 +6,9 @@ using these notes for a release or directory review. This candidate addresses the directory reviewer's exact-version requirement and fixes two cases where readable tool content could escape tokenization. It pins the detector and encrypted vault to version 1.7.0, scans MCP resource-link names/titles/descriptions, -and hides stranded email-domain tails in joined Unicode text. Joined addresses may +and hides stranded email-domain tails in joined Unicode text. Startup and runtime +checks reject other installed versions, including after a failed upgrade; doctor +reports version failures accurately. Joined addresses may become one marker; restoration remains byte-exact. The manifest now provides privacy, documentation and support links, accurate coverage @@ -14,8 +16,16 @@ language and the official DataFog icon. MCP tools declare their effects. A separ CI job validates both plugin and marketplace manifests with an exact Claude Code version. Privacy and security reporting documentation explain local storage and remaining limits. -MCP edit permission and concurrent-file safety changes are under final verification; -their behavior and results must be included here after review. +Marker-aware MCP edits now enforce Read/Edit deny and ask rules, refuse uncheckable +settings, preserve internal symlink targets and reject intervening file/path changes. +Bounded reads, pinned directories and advisory locks protect the normal edit flow; +an unrelated writer can still race the final identity-check/rename boundary. + +Independent review reproduced and verified fixes for an alias-retarget permission +race and repeated email-tail scanning. Cached 0.2.1 model sessions passed Read, +Bash, marker-aware edit and outside-project refusal, with installed production-file +hashes matching the candidate. The 0.2.0 → 0.2.1 upgrade retained marker identity. +Full-suite and CI results remain to be attached below. ## Validation to attach diff --git a/docs/verification/2026-11-18-host-readiness.md b/docs/verification/2026-11-18-host-readiness.md index 8769efe..d97f299 100644 --- a/docs/verification/2026-11-18-host-readiness.md +++ b/docs/verification/2026-11-18-host-readiness.md @@ -82,8 +82,9 @@ observations but do not certify the final source revision. - Alternate configuration-root trust handling, server-managed policy and MDM. - Locked/denied macOS Keychain, SSH/login/rebuilt-interpreter access; KWallet and locked Linux keyrings. Happy-path vault tests do not prove these states. -- Actual installed marketplace startup, upgrade and MCP project-directory behavior - (the above loads the plugin by local directory). +- Network-hosted marketplace startup and upgrade paths. A later + [cached installed candidate run](2026-11-18-installed-candidate.md) separately + verifies installed first start, all three examples and MCP project boundaries. - Other sandbox configurations/providers, including a vault outside the sandbox's allowed write paths. The macOS probe explicitly allowed its temporary data/vault. - Unsupported hardware/OS runtime behavior beyond mocked platform checks. @@ -112,8 +113,9 @@ never hard-code them in a reviewer instruction. left on disk. Tool results contain no planted raw value. Automated assertion: `reviewer-mcp-edit`. -These three examples passed on 2.1.327. Repeat them after the final marketplace -install to close the distribution path separately from the local plugin path. +These three examples passed on 2.1.327 and were subsequently repeated against the +[installed cached candidate](2026-11-18-installed-candidate.md), closing that +distribution-path check separately from the local plugin path. ## Harness validation diff --git a/docs/verification/2026-11-18-installed-candidate.md b/docs/verification/2026-11-18-installed-candidate.md new file mode 100644 index 0000000..e7e2291 --- /dev/null +++ b/docs/verification/2026-11-18-installed-candidate.md @@ -0,0 +1,71 @@ +# Installed candidate verification + +**Passed on macOS Apple Silicon, Claude Code 2.1.327, 18 November 2026.** +The production files tested match commit +`276b2b351389b48efe5b7a7a7f2c0a4977dc875f` byte for byte. See +[installed-readiness-results.json](installed-readiness-results.json) for production +file hashes, installation identity, exact case results and cleanup status. + +The test used a unique temporary local-scope marketplace whose plugin source was +a Git URL pinned to a generated fixture commit. That Git repository contained an +unchanged snapshot of the candidate. The separate test catalog changed only the +marketplace name and source location. This exercises Claude's real clone/install +cache without publishing the candidate or modifying its public marketplace. + +`python3 tests/live/run_installed_readiness.py` reproduces the workflow. It uses +the existing Claude login, loads only fixture project/local settings, and never +passes `--plugin-dir` or copies credentials. The file-key vault and plugin data +directory are temporary. A bounded PTY accepts only the generated workspace's +trust prompt, waits for DataFog's protected startup, then exits. No model request +is submitted in that PTY. The four model probes run afterwards. + +## Observed results + +- Installed version **0.2.1** into the real Claude plugin cache. Production engine, + launcher, hook and MCP files in that cache matched the snapshot hashes. +- The plugin's private environment did not exist before first start. The actual + installed SessionStart path bootstrapped it and reported `DataFog guard: on.` +- The host recorded trust for the exact generated canonical project path. +- Each model run's initialization record named the installed cache path; none + loaded the source checkout or used the local-directory shortcut. +- **Read example:** returned markers for the synthetic fixture and no planted raw + value in model-facing tool results. +- **Bash example:** allowed `cat notes.txt` ran through the cached runner and + returned markers without planted raw values. +- **MCP edit example:** the installed MCP tool restored the exact synthetic email + plus the requested suffix on disk, left no markers in the file, and returned no + planted raw values to the model. +- **MCP project scope:** the actual installed tool was called on a synthetic + sibling file outside the fixture project. It returned “Refused: the path is + outside the project directory.” The sibling file stayed byte-for-byte unchanged. +- The unique local-scope install and marketplace were removed. A subsequent + plugin inventory verified the test plugin ID was absent. Only the generated + fixture's host transcript/trust record was purged; raw test logs remain in its + temporary evidence directory. + +## Why the source form matters + +The initial local-folder installation passed the functional examples but did +**not** prove cached execution: Claude's installed metadata included +`readFromFolder`, and the MCP process loaded that folder. The harness caught this +by comparing the runtime initialization path with the installation cache path. +The final pinned Git URL run has no such override and passes that assertion. +This distinction is documented in the official +[marketplace guide](https://code.claude.com/docs/en/plugin-marketplaces#test-an-edit-to-a-plugin). + +An intermediate test catalog used the unsupported source type `git` and was +rejected before plugin execution. The corrected documented source type is `url`. +That unique test catalog was also removed; this was a harness setup error, not a +candidate plugin failure. + +## Boundaries + +This closes cached installed startup, three runnable reviewer examples, and the +installed MCP project-boundary behavior for this host/platform. It does not prove +public directory acceptance, a network GitHub install from an unpublished +revision, Linux installed-host behavior, or first-start operating-system keychain +prompts. Those gates have separate evidence or remain explicit limitations. + +The separate relocated-config probe observed that `CLAUDE_CONFIG_DIR` creates +`/.claude.json`, but reached login before workspace trust. No +credentials were copied; relocated trust-field behavior remains unverified. diff --git a/docs/verification/candidate-live-results.json b/docs/verification/candidate-live-results.json new file mode 100644 index 0000000..65c083d --- /dev/null +++ b/docs/verification/candidate-live-results.json @@ -0,0 +1,1048 @@ +{ + "date": "2026-11-18", + "production_commit": "aa99659a0f3218c443a6fcbc17dbeb9e43537574", + "status": "DONE", + "claude_code": "2.1.327 (Claude Code)", + "runs": 29, + "skipped": 0, + "totals": { + "PASS": 187, + "INFO": 24 + }, + "full_local_results_sha256": "6726e98645168269f7cd10434798ed1d89b9e4146560e99e78d59bfcec497535", + "cases": [ + { + "case": "L00-probe", + "title": "The plugin loads and its hooks run", + "checks": [ + { + "name": "the plugin loaded in the headless session", + "status": "PASS" + }, + { + "name": "the plugin's MCP tools are present", + "status": "PASS" + }, + { + "name": "SessionStart ran and reported healthy", + "status": "PASS" + }, + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + } + ] + }, + { + "case": "L01-read", + "title": "Read is redirected to a tokenized copy", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "Read returned content", + "status": "PASS" + }, + { + "name": "Read result holds markers for all 4 values", + "status": "PASS" + }, + { + "name": "PreToolUse redirected the Read to a shadow copy", + "status": "PASS" + }, + { + "name": "the model repeated a marker verbatim", + "status": "PASS" + }, + { + "name": "the tool result does not show the shadow path", + "status": "PASS" + } + ] + }, + { + "case": "L02-bash-ok", + "title": "An allowed simple Bash command runs, and its output is filtered", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "a simple command matched by an allow rule in settings.local.json ran without a prompt", + "status": "PASS" + }, + { + "name": "the hook's own decision was allow, by the user's rule (step 7)", + "status": "PASS" + }, + { + "name": "Bash output holds markers", + "status": "PASS" + }, + { + "name": "the output filter ran", + "status": "PASS" + }, + { + "name": "API key in the output was replaced", + "status": "PASS" + } + ] + }, + { + "case": "L03-bash-fail", + "title": "A failing Bash command is filtered too (PostToolUse cannot do this)", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the failing command's result reached the model as an error", + "status": "PASS" + }, + { + "name": "its output holds markers, not values", + "status": "PASS" + }, + { + "name": "the real error message is kept", + "status": "PASS" + }, + { + "name": "the exit code is the command's own", + "status": "PASS" + } + ] + }, + { + "case": "L04-bash-cd", + "title": "cd persists across separate Bash calls", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "three Bash calls ran", + "status": "PASS" + }, + { + "name": "`cd` in one call carried over to the next", + "status": "PASS" + }, + { + "name": "the file in the new directory was readable and filtered", + "status": "PASS" + } + ] + }, + { + "case": "L05-bash-exit-trap", + "title": "Output of an EXIT trap cannot bypass the filter", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the command ran", + "status": "PASS" + }, + { + "name": "output printed by an EXIT trap went through the filter", + "status": "PASS" + } + ] + }, + { + "case": "L06-bash-colour", + "title": "A value split by colour codes is still replaced", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the command ran and matched", + "status": "PASS" + }, + { + "name": "a value split by colour codes was replaced", + "status": "PASS" + }, + { + "name": "colour codes present in the raw result (were they suppressed by NO_COLOR?)", + "status": "INFO" + } + ] + }, + { + "case": "L18-bash-marker-ask", + "title": "A Bash command containing a marker asks first (restore_in_bash=ask)", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model put a marker into a Bash command", + "status": "PASS" + }, + { + "name": "the hook asked for permission instead of restoring silently", + "status": "PASS" + }, + { + "name": "headless: the command was not auto-approved", + "status": "PASS" + }, + { + "name": "no real value in the transcript, the result record, permission_denials, stderr, the debug log or the guard log", + "status": "PASS" + }, + { + "name": "the command Claude Code recorded holds the marker", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L19-bash-marker-allow", + "title": "With restore_in_bash=allow the runner restores the marker; records keep it", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the program received the real value (grep counted 1 line)", + "status": "PASS" + }, + { + "name": "the runner restored the marker, and the hook did not ask about it", + "status": "PASS" + }, + { + "name": "the hook allowed it by the user's rule (step 7)", + "status": "PASS" + }, + { + "name": "the transcript shows the command with the marker only", + "status": "PASS" + }, + { + "name": "no real value in the transcript, the result record, permission_denials, stderr, the debug log or the guard log", + "status": "PASS" + } + ] + }, + { + "case": "L25-bash-nasty-value", + "title": "A value full of shell syntax is restored as inert data", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the program received exactly the hostile value, as one argument (grep -cxF counted 1)", + "status": "PASS" + }, + { + "name": "nothing inside the value ran (no PWNED file)", + "status": "PASS" + }, + { + "name": "the runner restored it", + "status": "PASS" + }, + { + "name": "no real value in the transcript, the result record, permission_denials, stderr, the debug log or the guard log", + "status": "PASS" + } + ] + }, + { + "case": "L21-bash-complex", + "title": "A command that is not simple asks (headless: denied), whatever the allow rules", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call", + "status": "PASS" + }, + { + "name": "the hook asked because the command is not a single simple command (step 6)", + "status": "PASS" + }, + { + "name": "the command did not run", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L22-bash-denied", + "title": "A command matched by a deny rule is denied", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call", + "status": "PASS" + }, + { + "name": "the hook denied it by the project's deny rule (step 2)", + "status": "PASS" + }, + { + "name": "the command did not run", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + }, + { + "name": "the file is still there", + "status": "PASS" + } + ] + }, + { + "case": "L23-bash-ask-rule", + "title": "A command matched by an ask rule asks (headless: denied)", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call", + "status": "PASS" + }, + { + "name": "the hook asked by the project's ask rule (step 3)", + "status": "PASS" + }, + { + "name": "the command did not run", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L24-bash-untrusted-project-allow", + "title": "An allow rule in the shared project settings is not applied to an untrusted folder", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call", + "status": "PASS" + }, + { + "name": "the hook found no applicable allow rule (step 8): Bash(wc *) is only in .claude/settings.json, and this folder was never trusted", + "status": "PASS" + }, + { + "name": "the command did not run", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L26-bash-read-deny", + "title": "A Read deny rule stops an allowed Bash command that names the file", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call", + "status": "PASS" + }, + { + "name": "the hook denied it by the Read deny rule, although Bash(cat *) is allowed (step 2)", + "status": "PASS" + }, + { + "name": "the command did not run", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L27-bash-read-deny-directory", + "title": "An allowed Bash command over a directory that holds the denied file asks (headless: denied)", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call", + "status": "PASS" + }, + { + "name": "the hook asked because a Read rule covers something in that directory (step 8, firm)", + "status": "PASS" + }, + { + "name": "the command did not run", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L28-bash-read-deny-quoted-glob", + "title": "A partly quoted glob that would reach the denied file is not allowed (headless: denied)", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call", + "status": "PASS" + }, + { + "name": "the hook asked because the command is not plain (step 6); with a deny rule present that ask holds in every permission mode", + "status": "PASS" + }, + { + "name": "the command did not run", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L29-bash-marker-unlisted-program", + "title": "A marker for a program that is not on the restore list is refused, although a Bash allow rule matches", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the model made the Bash call with a marker", + "status": "PASS" + }, + { + "name": "the hook refused to restore a marker for a program that is not on the list", + "status": "PASS" + }, + { + "name": "the command did not run (argdump recorded nothing)", + "status": "PASS" + }, + { + "name": "no real value in the transcript, the result record, permission_denials, stderr, the debug log or the guard log", + "status": "PASS" + }, + { + "name": "what the model was told", + "status": "INFO" + } + ] + }, + { + "case": "L07-grep", + "title": "Grep output is replaced after the tool ran", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "Grep returned matches", + "status": "PASS" + }, + { + "name": "PostToolUse replaced the values in the Grep result", + "status": "PASS" + } + ] + }, + { + "case": "L08-write-restore", + "title": "Markers are restored when Claude writes a file", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "contact.txt was created", + "status": "PASS" + }, + { + "name": "the file on disk holds the real value, not a marker", + "status": "PASS" + } + ] + }, + { + "case": "L09-edit-tool", + "title": "edit_with_markers edits a line that holds a marker", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the plugin's edit tool was available and called", + "status": "PASS" + }, + { + "name": "the line holding a marker was edited on disk with the real value kept", + "status": "PASS" + }, + { + "name": "no marker was written to disk", + "status": "PASS" + } + ] + }, + { + "case": "L10-write-over-read", + "title": "Write over an existing file that was read through a shadow copy", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "Write over a file that was read through a shadow copy succeeded", + "status": "PASS" + }, + { + "name": "every real value is back on disk, no markers", + "status": "PASS" + } + ] + }, + { + "case": "L11-edit-plain-line", + "title": "Built-in Edit on a line without markers, after a redirected Read", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "built-in Edit on a marker-free line of a shadow-read file worked", + "status": "PASS" + }, + { + "name": "the Edit result shown to the model holds no real value", + "status": "PASS" + } + ] + }, + { + "case": "L12-plain-file", + "title": "Files without values are left alone", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "a file without personal data is read and edited as usual", + "status": "PASS" + }, + { + "name": "its Read was not redirected", + "status": "PASS" + } + ] + }, + { + "case": "L13-at-file", + "title": "@file mention of a file holding values is blocked", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the UserPromptSubmit hook ran and blocked", + "status": "PASS" + }, + { + "name": "the model produced no answer", + "status": "PASS" + }, + { + "name": "how the blocked run ended", + "status": "INFO" + } + ] + }, + { + "case": "L14-prompt-pii", + "title": "A prompt that contains a value is blocked", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the UserPromptSubmit hook ran and blocked", + "status": "PASS" + }, + { + "name": "the model produced no answer", + "status": "PASS" + }, + { + "name": "how the blocked run ended", + "status": "INFO" + } + ] + }, + { + "case": "L15-subagent", + "title": "A subagent's Read is protected as well", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the subagent result came back", + "status": "PASS" + }, + { + "name": "hooks fired for the subagent's own Read", + "status": "PASS" + }, + { + "name": "the subagent reported markers", + "status": "PASS" + } + ] + }, + { + "case": "L16-engine-broken", + "title": "With a corrupt vault at session start nothing is processed (fail closed)", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "the engine reported itself unhealthy", + "status": "PASS" + }, + { + "name": "the prompt was not processed (blocked before the model)", + "status": "PASS" + }, + { + "name": "no tool ran while the engine was broken", + "status": "PASS" + }, + { + "name": "prompt hook events", + "status": "INFO" + } + ] + }, + { + "case": "L17-engine-breaks-mid-session", + "title": "When the vault breaks mid-session, later tool calls are refused", + "checks": [ + { + "name": "no real value in any tool result sent to the model", + "status": "PASS" + }, + { + "name": "the model never wrote a real value", + "status": "PASS" + }, + { + "name": "no real value in the plugin's logs or shadow copies", + "status": "PASS" + }, + { + "name": "permission denials in this run", + "status": "INFO" + }, + { + "name": "the vault was corrupted during the session", + "status": "PASS" + }, + { + "name": "tool calls after the break were attempted", + "status": "PASS" + }, + { + "name": "every later tool call was refused", + "status": "PASS" + }, + { + "name": "PreToolUse denied them", + "status": "PASS" + }, + { + "name": "the model was told why", + "status": "PASS" + } + ] + }, + { + "case": "L28-keychain", + "title": "OPTIONAL: the vault key in the real OS key store (Keychain / Secret Service)", + "checks": [ + { + "name": "first start creates the vault and its key store entry without failing", + "status": "PASS", + "detail": "0.1 s (includes any Keychain prompt you had to answer); DataFog guard: on. Vault: DATAFOG_VAULT_DIR, encrypted, key in the system key store. Bash output: filtered. Markers in Bash commands: ask. Detecting: EMAIL, PHO" + }, + { + "name": "the new vault's key store entry exists", + "status": "PASS", + "detail": "" + }, + { + "name": "status reports the key store as the key's home", + "status": "PASS", + "detail": "" + }, + { + "name": "no key file lies beside the vault", + "status": "PASS", + "detail": "workspace.enc, workspace.lock" + }, + { + "name": "a second process opens the vault with the stored key and tokenizes", + "status": "PASS", + "detail": "" + }, + { + "name": "fifteen more hook processes get the same marker (no prompt each time?)", + "status": "PASS", + "detail": "" + }, + { + "name": "wall time of one PostToolUse hook process with the key from the key store", + "status": "INFO", + "detail": "p50 71 ms, max 79 ms over 15 runs" + }, + { + "name": "the address is not readable anywhere in the vault directory", + "status": "PASS", + "detail": "" + }, + { + "name": "purge removed the vault and its key store entry", + "status": "PASS", + "detail": "The vault was deleted. Its key was removed from the operating system's key store. Markers issued before now can no longer be restored. A new, empty vault is created on next use." + } + ] + } + ] +} diff --git a/docs/verification/candidate-validation.md b/docs/verification/candidate-validation.md new file mode 100644 index 0000000..218abd5 --- /dev/null +++ b/docs/verification/candidate-validation.md @@ -0,0 +1,73 @@ +# 0.2.1 candidate validation + +Production code baseline: `aa99659a0f3218c443a6fcbc17dbeb9e43537574`. +The subsequent `276b2b3` change makes a startup-import test portable across Python +versions; production files are identical. This report is preparation evidence, not +a directory approval or release announcement. + +## Main real-Claude suite + +On 2026-11-18, `LIVE_KEYCHAIN=1 DISABLE_AUTOUPDATER=1 bash tests/live/run-live.command` +completed on macOS Apple Silicon with Claude Code 2.1.327: + +- 29 headless runs, 30 cases, 394 seconds; no cases skipped by caps. +- **187 PASS, 24 INFO, zero FAIL/FINDING.** +- Coverage includes Read shadows, successful/failing Bash, cwd persistence, exit traps, + terminal control sequences, marker approval/late restoration, hostile synthetic value + handling, deny/ask rules, untrusted-project rules, file-path denials, Grep, writes, + marker-aware editing, prompts, file mentions, subagents and unavailable/corrupt engines. +- Optional Keychain case created one separate throwaway vault and key entry, restored + the same marker across processes, then verified purge removed both vault and key entry. + Fifteen full hook processes measured p50 71 ms and maximum 79 ms. Initial key creation + took 0.1 seconds. No real user vault was used. + +[Candidate live check results](candidate-live-results.json) preserves each check and +its status. Full synthetic logs remain locally at `.live/results/`; the source-result +hash is recorded in the JSON. Production files were confirmed unchanged since the +run began. The supplementary interactive, sandbox, lifecycle and installed-cache +reports cover paths outside this main headless suite. + +## Local and platform suites + +The initial network-enabled local pytest run finished with **2,568 passed, 43 skipped, +one failed** in 738.89 seconds. The failed optional standalone-dash fuzz case was +investigated rather than retried into a passing release claim: + +- The receiver got an empty value in one three-stage pipeline. The isolated full + case passed, but four repeated context batches reproduced an empty result with + `Segmentation fault: 11` on stderr. +- Two corresponding macOS crash reports identify Apple's `/bin/dash` (`dash-16`, + `com.apple.dash`, macOS 26.6.2) with EXC_BAD_ACCESS/SIGSEGV. This binary is not + selected by the plugin: it selects bash/zsh, then literal `/bin/sh` as fallback. +- Tests now exercise that actual `/bin/sh` fallback. On this Mac it is Apple bash + 3.2.57; on Linux CI it is dash. The full hostile randomized corpus passed with + identical exact-byte, no-side-effect and exit-status assertions. No retries, + expected failures or relaxed assertions were added. The complete fallback subset + then passed: **27 passed, 1,128 deselected in 80.68 seconds**. The initial failed + full run remains recorded as failed; this is scoped replacement evidence for the + incorrectly selected shell, not a claim that the original run passed. + +Linux 3.10 CI finished with **2,608 passed, 3 skipped, one failed**. Its only failure +was the new test's private keyring recovery: the unlock command returned without +unlocking the original private collection. The corrected fixture uses a private control socket and the GNOME existing-daemon +unlock protocol. All six private keyring tests passed in an isolated Ubuntu 24.04 +container, including locked-state refusal, no rekey or file-key fallback, and recovery +of the original marker. See [Linux keyring evidence](linux-keyring.md). + +The revised four-way platform matrix must pass before submission. CI for `276b2b3` is +[run 44365243455](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44365243455). +Strict manifest validation has passed. Local lint and mypy pass on 21 engine modules. + +An earlier local full-suite attempt was intentionally interrupted when the failed +dependency-upgrade gap was found. It is not release evidence. The earlier GitHub +run for `aa99659` was cancelled after the cross-Python test correction; the new run +must supply platform evidence, including the added private locked-keyring case. + +## Distribution and remaining scope + +[Installed candidate verification](2026-11-18-installed-candidate.md) confirms real +cached startup and reviewer examples. [Upgrade checks](marketplace-install.md) confirm +marker preservation and retention, with cache hashes checked against the candidate. +Public release URLs, the portal's final scan/review, and directory publication remain +gated on the owner's instruction. Environment-specific limitations are retained in +the [readiness inventory](../readiness.md); green tests do not erase those limits. diff --git a/docs/verification/installed-readiness-results.json b/docs/verification/installed-readiness-results.json new file mode 100644 index 0000000..ca94a56 --- /dev/null +++ b/docs/verification/installed-readiness-results.json @@ -0,0 +1,138 @@ +{ + "marketplace": "datafog-readiness-44c4f7f94893", + "work": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-installed.gqu_kqy3", + "cases": [ + { + "case": "installed-read", + "version": "2.1.327", + "checks": { + "Read returned markers": true, + "first startup bootstrapped engine": true, + "successful host process": true, + "no sentinel in model tool results": true, + "loaded installed cached plugin": true + }, + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-installed.gqu_kqy3/log/runs/01-installed-read.jsonl" + }, + { + "case": "installed-bash", + "version": "2.1.327", + "checks": { + "Bash returned markers": true, + "successful host process": true, + "no sentinel in model tool results": true, + "loaded installed cached plugin": true + }, + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-installed.gqu_kqy3/log/runs/02-installed-bash.jsonl" + }, + { + "case": "installed-mcp-edit", + "version": "2.1.327", + "checks": { + "MCP edit called": true, + "real value plus suffix on disk": true, + "no marker on disk": true, + "successful host process": true, + "no sentinel in model tool results": true, + "loaded installed cached plugin": true + }, + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-installed.gqu_kqy3/log/runs/03-installed-mcp-edit.jsonl" + }, + { + "case": "installed-mcp-project-boundary", + "version": "2.1.327", + "checks": { + "MCP edit called": true, + "server refused outside project": true, + "outside fixture unchanged": true, + "successful host process": true, + "no sentinel in model tool results": true, + "loaded installed cached plugin": true + }, + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-installed.gqu_kqy3/log/runs/04-installed-mcp-project-boundary.jsonl" + } + ], + "cleanup": [ + { + "step": "uninstall", + "success": true + }, + { + "step": "marketplace-remove", + "success": true + }, + { + "step": "purge-fixture-session", + "success": true, + "note": "Performed after run; removes only generated fixture host transcript/trust record. Raw evidence remains in temp log directory." + } + ], + "installed": { + "id": "datafog@datafog-readiness-44c4f7f94893", + "version": "0.2.1", + "scope": "local", + "enabled": true, + "installPath": "/Users/sid/.claude/plugins/cache/datafog-readiness-44c4f7f94893/datafog/0.2.1", + "installedAt": "2026-11-18T18:02:27.354Z", + "lastUpdated": "2026-11-18T18:02:27.354Z", + "projectPath": "/private/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-installed.gqu_kqy3/project", + "mcpServers": { + "guard": { + "command": "sh", + "args": [ + "${CLAUDE_PLUGIN_ROOT}/scripts/datafog-guard", + "mcp" + ], + "env": { + "CLAUDE_PROJECT_DIR": "${CLAUDE_PROJECT_DIR}", + "DATAFOG_DATA_DIR": "${DATAFOG_DATA_DIR:-}", + "DATAFOG_VAULT_DIR": "${DATAFOG_VAULT_DIR:-}", + "DATAFOG_VAULT_KEY": "${DATAFOG_VAULT_KEY:-}" + } + } + }, + "projectEnabled": false, + "hasUserConfig": true + }, + "cache_matches_source": true, + "fresh_bootstrap": true, + "interactive_first_start": true, + "fixture_trust_recorded": true, + "cleanup_verified": true, + "source_revision": "276b2b351389b48efe5b7a7a7f2c0a4977dc875f", + "fixture_git_sha": "1e3cafb608497a830b9fc7c0cabf9c40adf9e9ca", + "production_file_sha256": { + ".claude-plugin/marketplace.json": "0921542848f7f5d8aa96770a93c9021d20d8a31e674aae29c3780b7defde6151", + ".claude-plugin/plugin.json": "a804eaeab8e1b483079e8d7915401021b01875fe54ff3b8a79847b0359b57648", + ".mcp.json": "62186ffb8aa88ca6a08b5aeaa23a6e0c2b424eaa3e39d77760fa7e21e722f7bd", + "engine/datafog_guard/__init__.py": "e486296852d8dc74ba7086fef26537074ddd28cca1a96610e9adfdba2a95b4ea", + "engine/datafog_guard/__main__.py": "19a405af122b22e15bd4759ef48350c1b57d802c3ffb37ac9f5e6da7a608af9f", + "engine/datafog_guard/bashwrap.py": "7d711399b49f6a526200fef8ec4ca6f626588f98f84ce6083cea5c00947a8809", + "engine/datafog_guard/ccperms.py": "99a93d82a59f2eed8d9f549a463c62a2ee90b8504a28facf03247900a3aee185", + "engine/datafog_guard/cli.py": "45930b7f694e42e06fbf955ff74cb8927a0bd0f217fa18ea9dca0d1edb78e6f1", + "engine/datafog_guard/config.py": "98440b35d5e03558abdc5796920fc286f2da67d4f2c49dadb84a8c8fc5bddbe8", + "engine/datafog_guard/dependencies.py": "f3aee7c7d9a012922aedf8be72df110ebb922bc4203c8db5568fbdf5e38a4390", + "engine/datafog_guard/engine.py": "9b23f76cc1cdf47ca1d3943c87497f0c957b2bc01839ed736775bd04c7f9b640", + "engine/datafog_guard/errors.py": "d5e2adc7f4da6dec409697d1b35f86ed0e62d596d783eee21a98a5817c4faeda", + "engine/datafog_guard/files.py": "aa1583b1ca84c9f5aa555642f24a397367db6d281ead1cfa272274bad5534faf", + "engine/datafog_guard/filtercmd.py": "141196d30c6ec4523968b1fb02ad800945c96fca4789b0a70fd37620089aae43", + "engine/datafog_guard/hook.py": "cf8e205d96cd41bb8ce9d65db6ba598a6d6bcedc1f052707c308881fcc1eb0a4", + "engine/datafog_guard/log.py": "dc3913d9763c2db69d71f57bb7c6bf8e34dd9f76e8c5e0117c5eaf7eebd26f6f", + "engine/datafog_guard/mcp_server.py": "ac0fe6c88703f5e5c0f8cf2a32a75e918a7ce51f9c04a6a2bb9a4a9a7223a774", + "engine/datafog_guard/plain.py": "d48b94c0bb3b1ee7fd00e4f30f8829f958bbbe76417577af48912cc682db84bb", + "engine/datafog_guard/shapes.py": "6df11350a02391f43437af94593417a0f2405eefa9d05509a1e54b3ad6178635", + "engine/datafog_guard/shellsub.py": "2326384c88e1b601a7094172d997c38d57d6efebabc2853345917592f41df95d", + "engine/datafog_guard/store.py": "81d9bcfd5f354fb68853d84581b893d0fd0fe5680a959dd0614d4019769ae150", + "engine/datafog_guard/stream.py": "f2699c5c3d01b19525afea292c34759030f566356238b0bcb0af717f60022cb4", + "engine/datafog_guard/support.py": "33be91dd33bcce5b814c1ae9746cb71b5dc5786f2e671dd0c2d181e7eb7281ca", + "engine/datafog_guard/vault.py": "ff39ecb3dc287c6dff32ad72fe5825a15e35df6d141db65f18ccc0f0d052d1c5", + "engine/run.py": "c510ca7de991bcd0ad8b19412e4b517a73d60dd964b849a36fae242f44883c47", + "hooks/hooks.json": "a1a540ea107921d3a568e3363c015f8e5f0f7d1a1d1909cdc04d10348e64dc2d", + "pyproject.toml": "eb370c164bd912c4a92551029cfb2c3e0d821964b28d1ef7fbd42f1844b653b0", + "scripts/bootstrap.sh": "916c54191844e614334201084258fab02685aa2485583063ec2dc4caf80b3195", + "scripts/datafog-guard": "c4d5d471711b20429e1c7f252b274f62c1c3d10cde1676009de4a930491081f0", + "scripts/verify-manifests.sh": "6f03cbf9101da54a72f2ec2eed49c08ea26e97a40b946985285524018eeb97af", + "scripts/wrap.sh": "4549077dce3ce12225d65e5197104bb3db67deda0fc0e1125b8d3cf511b1a4e4" + }, + "production_matches_source_revision": true +} diff --git a/docs/verification/linux-keyring.md b/docs/verification/linux-keyring.md new file mode 100644 index 0000000..edfb38d --- /dev/null +++ b/docs/verification/linux-keyring.md @@ -0,0 +1,55 @@ +# Private Linux keyring regression verification + +On 2026-11-18, all six tests in `tests/test_keystore.py` passed inside an isolated +Ubuntu 24.04 `linux/amd64` Docker container, emulated on the development host. +Environment: Python 3.12.3, glibc 2.39 (Ubuntu 2.39-0ubuntu8.9), +gnome-keyring-daemon 46.1, `datafog-core==1.7.0`, and `datafog-fogvault==1.7.0`. +The repository was mounted read-only; the venv, test homes, D-Bus sessions, +keyrings, and vaults lived in the disposable container. No host credentials, +configuration directories, or keychains were mounted. This focused result does +not substitute for the final candidate's Linux CI matrix. + +Command (inside the container): + +```sh +/tmp/test-env/bin/python -m pytest tests/test_keystore.py -q \ + -p no:cacheprovider --basetemp=/tmp/datafog-keystore-tests-protocol2 +``` + +Result: six tests passed, none skipped. The host Ruff check for the changed test +also passed. + +## Fixture failure and correction + +The earlier Linux CI failure occurred during recovery after the locked-vault +probe. The fixture discarded the daemon's control location and used the invalid +`XDG_RUN_DIR` variable. It now sets `XDG_RUNTIME_DIR`, uses an explicit private +`GNOME_KEYRING_CONTROL` directory with mode 0700, and checks that the expected +control socket exists. During diagnosis, mode 0755 caused the daemon to silently +select a different directory, despite returning success. + +A second `gnome-keyring-daemon --unlock` invocation did not unlock the existing +private daemon. Its zero exit status and matching control-directory output were +insufficient evidence of recovery. The test now sends GNOME's existing-daemon +UNLOCK request directly to that fixture's Unix control socket, with a bounded +socket timeout and an asserted success response. The synthetic password includes +the same newline used at fixture startup. No developer password is involved. + +The test verifies the default collection actually contains the DataFog items, +checks the real `Locked` property before and after locking, and opens the vault +in a bounded fresh subprocess. Before attempting recovery, it asserts +`keystore_unavailable`, a still-locked collection, unchanged encrypted data and +header, and no file-key fallback. It then verifies actual unlock, restoration of +the original marker, and unchanged key-store entries. A timeout fails the test; +it is not treated as fail-closed evidence. + +Protocol and behavior references: + +- [GNOME control client](https://github.com/GNOME/gnome-keyring/blob/46.2/daemon/control/gkd-control-client.c) +- [GNOME control operation/result codes](https://github.com/GNOME/gnome-keyring/blob/46.2/daemon/control/gkd-control-codes.h) +- [GNOME daemon initialization](https://github.com/GNOME/gnome-keyring/blob/46.2/daemon/gkd-main.c) +- [Secret Service methods](https://specifications.freedesktop.org/secret-service/latest/org.freedesktop.Secret.Service.html) +- [Collection Locked property](https://specifications.freedesktop.org/secret-service/latest/org.freedesktop.Secret.Collection.html) + +The control protocol is GNOME-specific test infrastructure. This evidence does +not claim KWallet or other Secret Service implementations were exercised. diff --git a/docs/verification/marketplace-install.md b/docs/verification/marketplace-install.md index feb8f5b..e2f8950 100644 --- a/docs/verification/marketplace-install.md +++ b/docs/verification/marketplace-install.md @@ -44,3 +44,22 @@ Both checks passed. Local evidence directory: These remain direct cached-hook checks, not model sessions, and precede the later runtime version-enforcement fix. Final-release host startup and updated-candidate certification are still required. + +## Final production-file upgrade repeat + +After the dependency-enforcement fix, a fresh isolated configuration repeated the +0.2.0 → 0.2.1 local-Git-marketplace upgrade against production files from `276b2b3` +(runtime unchanged from `aa99659`). All engine, script, hook and MCP manifest hashes +in the installed cache matched the candidate. Both cached startups were healthy, +the synthetic marker remained identical, the exact-pin environment stamp matched, +and uninstall removed plugin data while retaining the external temporary vault. + +Evidence and reproduction script: +`/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-final-upgrade-6kn6fs2q`. +An earlier repeat reused a development cache with the same 0.2.1 version and was +rejected after hash comparison found stale files; it is not candidate evidence. +Always use a fresh configuration or verify installed hashes when testing unreleased +changes under one version number. + +Actual model sessions from the cached installation are separately documented in +[installed candidate verification](2026-11-18-installed-candidate.md). diff --git a/tests/live/run_installed_readiness.py b/tests/live/run_installed_readiness.py index e326e36..b85a63f 100644 --- a/tests/live/run_installed_readiness.py +++ b/tests/live/run_installed_readiness.py @@ -8,19 +8,61 @@ """ import hashlib import json +import os import pathlib +import pty +import select import shutil +import signal import subprocess import tempfile +import time import uuid import run_live as live +def trust_fixture(driver): + """Accept only this generated workspace's real host trust prompt; no model request.""" + master, slave = pty.openpty() + process = subprocess.Popen(["claude", "--setting-sources", "project,local", "--ax-screen-reader", "--tools", ""], + cwd=driver.project, env=driver.env(), stdin=slave, stdout=slave, stderr=slave, + start_new_session=True) + os.close(slave) + transcript = bytearray() + accepted = False + deadline = time.monotonic() + 90 + try: + while process.poll() is None and time.monotonic() < deadline: + ready, _, _ = select.select([master], [], [], 1) + if ready: + try: + transcript.extend(os.read(master, 65536)) + except OSError: + break + text = transcript.decode(errors="replace") + if not accepted and "Accessing workspace" in text and "Enter y/n:" in text: + os.write(master, b"y\r") + accepted = True + if accepted and "DataFog guard: on." in text: + return True + return False + finally: + pathlib.Path(driver.log, "fixture-trust-pty.txt").write_bytes(transcript) + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + os.close(master) + + def main(): source = pathlib.Path(live.REPO) work = pathlib.Path(tempfile.mkdtemp(prefix="datafog-installed.")) - snapshot = work / "marketplace" + snapshot = work / "plugin-source" snapshot.mkdir() marketplace = "datafog-readiness-" + uuid.uuid4().hex[:12] plugin_id = "datafog@" + marketplace @@ -36,13 +78,22 @@ def main(): destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, destination) hashes[name] = hashlib.sha256(path.read_bytes()).hexdigest() - catalog_path = snapshot / ".claude-plugin/marketplace.json" - catalog = json.loads(catalog_path.read_text()) + subprocess.run(["git", "init", "-b", "readiness-fixture", str(snapshot)], check=True, capture_output=True) + subprocess.run(["git", "add", "--all"], cwd=snapshot, check=True, capture_output=True) + subprocess.run(["git", "-c", "user.name=DataFog readiness fixture", "-c", "user.email=fixture@example.invalid", + "commit", "-m", "Snapshot candidate for cached install verification"], cwd=snapshot, check=True, capture_output=True) + fixture_sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=snapshot, text=True).strip() + catalog_root = work / "marketplace" + catalog_path = catalog_root / ".claude-plugin/marketplace.json" + catalog_path.parent.mkdir(parents=True) + catalog = json.loads((snapshot / ".claude-plugin/marketplace.json").read_text()) catalog["name"] = marketplace + catalog["plugins"][0]["source"] = {"source": "url", "url": snapshot.as_uri(), "sha": fixture_sha} catalog_path.write_text(json.dumps(catalog, indent=2)) provenance = {"revision": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=source, text=True).strip(), "source_sha256": hashes, "marketplace": marketplace, - "snapshot_change": "Only marketplace.name changed to avoid collisions with real installations."} + "fixture_git_sha": fixture_sha, + "snapshot_change": "Plugin files unchanged. Separate unique marketplace uses pinned local Git source to force cached execution."} (work / "provenance.json").write_text(json.dumps(provenance, indent=2)) driver = live.Driver(str(work), "claude") driver.plugin_dir = None @@ -63,7 +114,7 @@ def command(label, args): return result.stdout try: - command("marketplace-add", ["plugin", "marketplace", "add", str(snapshot), "--scope", "local", "--json"]) + command("marketplace-add", ["plugin", "marketplace", "add", str(catalog_root), "--scope", "local", "--json"]) command("install", ["plugin", "install", plugin_id, "--scope", "local", "--json"]) plugins = json.loads(command("installed-list", ["plugin", "list", "--json"])) installed = next(p for p in plugins if p["id"] == plugin_id and p["scope"] == "local") @@ -73,6 +124,9 @@ def command(label, args): for name, digest in hashes.items() if name.startswith(("engine/", "scripts/", "hooks/")) or name == ".mcp.json") report["fresh_bootstrap"] = not pathlib.Path(driver.data, "venv").exists() + report["interactive_first_start"] = trust_fixture(driver) + config = json.loads((pathlib.Path.home() / ".claude.json").read_text()) + report["fixture_trust_recorded"] = config.get("projects", {}).get(str(pathlib.Path(driver.project).resolve()), {}).get("hasTrustDialogAccepted") is True def run(name, prompt, check): result = driver.run(name, prompt + " Do not retry a refused call or use alternative tools.") @@ -107,7 +161,8 @@ def run(name, prompt, check): "outside fixture unchanged": outside.read_text() == "ORIGINAL SYNTHETIC FIXTURE\n"}) finally: for label, args in (("uninstall", ["plugin", "uninstall", plugin_id, "--scope", "local", "--json"]), - ("marketplace-remove", ["plugin", "marketplace", "remove", marketplace, "--scope", "local", "--json"])): + ("marketplace-remove", ["plugin", "marketplace", "remove", marketplace, "--scope", "local", "--json"]), + ("purge-fixture-session", ["purge", driver.project, "--yes"])): try: command(label, args) report["cleanup"].append({"step": label, "success": True}) @@ -116,7 +171,7 @@ def run(name, prompt, check): remaining = json.loads(command("post-cleanup-list", ["plugin", "list", "--json"])) report["cleanup_verified"] = not any(p["id"] == plugin_id for p in remaining) (work / "installed-results.json").write_text(json.dumps(report, indent=2)) - passed = report.get("cache_matches_source") and report.get("fresh_bootstrap") and len(report["cases"]) == 4 + passed = report.get("cache_matches_source") and report.get("fresh_bootstrap") and report.get("interactive_first_start") and report.get("fixture_trust_recorded") and len(report["cases"]) == 4 passed = passed and all(all(row["checks"].values()) for row in report["cases"]) and all(row["success"] for row in report["cleanup"]) and report["cleanup_verified"] raise SystemExit(0 if passed else 1) diff --git a/tests/test_keystore.py b/tests/test_keystore.py index 11e4172..160168b 100644 --- a/tests/test_keystore.py +++ b/tests/test_keystore.py @@ -24,9 +24,12 @@ 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 + set -e + printf 'synthetic-test-password\\n' | gnome-keyring-daemon --unlock --components=secrets \ + --control-directory="$GNOME_KEYRING_CONTROL" >/dev/null 2>&1 sleep 0.3 - "$@" + test -S "$GNOME_KEYRING_CONTROL/control" + exec "$@" """) PRELUDE = textwrap.dedent(""" import json, os, subprocess, sys @@ -58,9 +61,14 @@ def in_private_key_store(tmp_path, script: str, timeout: int = 120) -> dict: "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) + env["XDG_RUNTIME_DIR" if name == "run" else f"XDG_{name.upper()}_HOME"] = str(root / name) (root / "home").mkdir(exist_ok=True) os.chmod(root / "run", 0o700) + # gnome-keyring otherwise chooses a temporary control socket and prints its + # location. Pin it explicitly so the recovery request reaches this same private daemon. + control = root / "run" / "keyring" + control.mkdir(mode=0o700) + env["GNOME_KEYRING_CONTROL"] = str(control) 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) @@ -195,6 +203,10 @@ def locked(): paths = re.findall(r"'(/[^']*)'", alias) assert len(paths) == 1 and paths[0] != "/", "the private default collection must exist" collection = paths[0] + found = call("/org/freedesktop/secrets", service + ".SearchItems", + "{'service': '" + KEYSTORE_SERVICE + "'}") + item_paths = re.findall(r"'(/[^']*)'", found) + assert item_paths and all(path.startswith(collection + "/") for path in item_paths) assert not locked(), "the fixture must first create a usable unlocked keyring" call("/org/freedesktop/secrets", service + ".Lock", "['" + collection + "']") assert locked(), "a successful Lock call alone is not evidence that the keyring is locked" @@ -225,8 +237,25 @@ def locked(): # Unlock only this session's throwaway login collection, then prove the original # mapping still works; no developer login keyring or credential is involved. - subprocess.run(["gnome-keyring-daemon", "--unlock", "--components=secrets"], - input=b"synthetic-test-password\n", capture_output=True, check=True, timeout=15) + assert result["code"] == "keystore_unavailable" + assert still_locked and unchanged and same_header and no_file_key + + # --unlock starts a daemon; it does not unlock an already-running one. + # Use GNOME's control-client UNLOCK protocol against only the fixture socket: + # https://github.com/GNOME/gnome-keyring/blob/46.2/daemon/control/gkd-control-client.c + import socket, struct + password = b"synthetic-test-password\n" + packet = struct.pack(">III", 12 + len(password), 1, len(password)) + password + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as control: + control.settimeout(5) + control.connect(os.path.join(os.environ["GNOME_KEYRING_CONTROL"], "control")) + control.sendall(b"\0" + packet) # credentials byte, then framed UNLOCK request + response = b"" + while len(response) < 8: + chunk = control.recv(8 - len(response)) + assert chunk, "private daemon closed its unlock response" + response += chunk + assert struct.unpack(">II", response) == (8, 0), "private daemon rejected unlock" assert not locked(), "the private collection did not unlock for the recovery check" recovered = vault(d).restore(marker).text == EMAIL print(json.dumps({"code": result["code"], "still_locked": still_locked, diff --git a/tests/test_late_swap.py b/tests/test_late_swap.py index 2b64d6e..a17a1b4 100644 --- a/tests/test_late_swap.py +++ b/tests/test_late_swap.py @@ -5,7 +5,7 @@ A command with a marker is restored only if the WHOLE command fits a small positive grammar (plain.py, shellsub.py); everything else is refused. Three layers of proof, under real bash, -zsh and dash: +zsh and the actual /bin/sh fallback (dash on the Linux CI images): * every nasty value x every supported context, substituted and run by the shell directly; * random values over a hostile alphabet x every context; * the same contexts through the real runner (wrap.sh, launcher, filtercmd), which is what @@ -27,9 +27,9 @@ from datafog_guard.shellsub import Refused, Span, substitute SHELLS = [shell for shell in ("bash", "zsh") if shutil.which(shell)] -# The runner falls back to /bin/sh when neither bash nor zsh exists; the grammar is the same, and it is -# checked against dash where it is installed. -PLAIN_SH = [shell for shell in ("dash",) if shutil.which(shell)] +# Exercise the runner's actual fallback, not an unrelated standalone shell. In particular, +# macOS /bin/sh is bash, while Apple's standalone dash is not selected by pick_shell(). +PLAIN_SH = ["/bin/sh"] if os.access("/bin/sh", os.X_OK) else [] def kind_of(shell: str) -> str: @@ -569,7 +569,8 @@ def test_random_values_in_every_context(receivers, shell): result = run_shell(receivers, shell, "\n".join(lines) + "\nrc 37") assert result.returncode == 37, (name, result.stderr[-300:]) for number, want in wanted.items(): - assert receivers.got(number) == want, (name, repr(values[number])) + assert receivers.got(number) == want, (name, number, repr(values[number]), + result.returncode, result.stderr[-2000:]) assert receivers.side_effects() == [], name checked += len(wanted) assert checked > 280 * len(CONTEXTS) From 34972866ac011d3789aad5f0915a646bd188616c Mon Sep 17 00:00:00 2001 From: Sid Mohan <61345237+sidmohan0@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:27:27 -0800 Subject: [PATCH 4/5] Record final host mode checks and reconcile readiness evidence --- docs/directory-submission.md | 13 +- docs/readiness.md | 36 +- docs/release-notes-0.2.1.md | 33 +- .../verification/2026-11-18-host-readiness.md | 34 +- docs/verification/candidate-validation.md | 9 +- .../mode-supplement-interactive.txt | 43 +++ .../verification/mode-supplement-results.json | 352 ++++++++++++++++++ 7 files changed, 482 insertions(+), 38 deletions(-) create mode 100644 docs/verification/mode-supplement-interactive.txt create mode 100644 docs/verification/mode-supplement-results.json diff --git a/docs/directory-submission.md b/docs/directory-submission.md index d9cab72..cff2850 100644 --- a/docs/directory-submission.md +++ b/docs/directory-submission.md @@ -22,7 +22,7 @@ Keep auto-publish off. Select a release tag containing the reviewed commit, reco - Three slash commands, four hook events, two local MCP tools, Python engine, shell launcher and bootstrap are bundled. - Exact-pin validation: 24 CLI/plugin tests passed with one network test skipped; that network bootstrap case then passed separately with `DATAFOG_TEST_NETWORK=1`. Ruff and `git diff --check` passed. - Bootstrap now pins `datafog-core==1.7.0` and `datafog-fogvault==1.7.0`, matching engine constants, pyproject, CI and documented install commands. This directly addresses the prior reviewer request; final portal confirmation remains necessary. -- CI parses JSON and runs shell parsing, Ruff, mypy and pytest on macOS/Linux with Python 3.10/3.12. A new isolated strict-manifest job uses Claude Code 2.1.327; local execution passed, but the changed CI workflow still needs a candidate run. See [verification and homepage plan](release-verification-plan.md). +- CI parses JSON and runs shell parsing, Ruff, mypy and pytest on macOS/Linux with Python 3.10/3.12. A new isolated strict-manifest job uses Claude Code 2.1.327; local execution and the final candidate CI manifest job passed; the four platform test jobs remain pending. See [verification and homepage plan](release-verification-plan.md). ## Directory-specific remaining gates @@ -31,11 +31,11 @@ Keep auto-publish off. Select a release tag containing the reviewed commit, reco | D01 | Existing submission found; resume it rather than migrate or duplicate. Reconfirm push access at resubmission. | Portal ID/status recorded above; no migration needed. | | D02 | PRIVACY.md and manifest link added locally; publish with reviewed release. | Public policy URL must resolve after push and match final behavior. | | D03 | Support URL added; SECURITY.md and private GitHub vulnerability reporting enabled. Portal contact matches authenticated Gmail profile. | Mailbox access confirmed; final public-doc URLs await merge. No test email was sent or portal badge claimed. | -| D04 | Provide three runnable synthetic reviewer examples. | Read/tokenization, Bash output filtering, marker-aware edit; expected output and disk-state assertions. | +| D04 | Provide three runnable synthetic reviewer examples. | All three passed in real cached candidate sessions with source hashes and disk-state assertions; see verification/2026-11-18-installed-candidate.md. | | D05 | MCP annotations added by implementation workstream. | Focused MCP tests pass; final integrated suite still required. | | D06 | Narrow all listing claims to detected values and disclosed limits. | Manifest, marketplace, README and GitHub About now describe detected values. Homepage release-copy update is drafted for publication; directory availability is not announced. | | D07 | Portal now restricted to Claude Code; keep unsupported app claims out of listing. | Settings saved and verified Code on, Cowork/apps off. | -| D08 | Run a clean cached marketplace install, upgrade and uninstall scenario. | Exact release installed outside source checkout; hooks and MCP start; settings and vault retention behave as documented. | +| D08 | Run a clean cached marketplace install, upgrade and uninstall scenario. | Cached candidate startup passed; fresh 0.2.0→0.2.1 upgrade preserved markers and uninstall retention passed. Final public release URL verification remains open; see verification/marketplace-install.md. | | D09 | Establish dependency provenance/reproducibility and bootstrap failure coverage. | Exact resolved distributions, source/index behavior and network needs recorded; cold install succeeds on both supported platforms. | | D10 | Assess permission/sandbox integration against directory policy. | Interactive verification report and reviewer explanation for wrapper behavior; no claim of sandbox compatibility without testing. | | D11 | Portal validation of final pushed release; address every blocking result. | Saved finding report tied to SHA, including any reviewer holds and responses. | @@ -48,6 +48,13 @@ D02–D05 reflect policy requirements for privacy, contact/support, sample use c Check the final archive for valid portable names, ordinary files, contained paths, supported readable file types, no OS junk or rewriting Git attributes, and size/count limits (50 MiB archive, 256 MiB unpacked, fewer than 10,000 entries; individual files under 5 MiB). Reviewer thresholds include 512 files and 256 KiB non-image/font files. Verify unique name, manifest, README, license, component schemas, front matter and absence of real credentials. Launchers require exact package pins; registry overrides and opaque execution can block or hold review. [Official checklist](https://claude.com/docs/plugins/pre-submission-checklist). +Local archive preflight for `fe1bd1c848880fc4c3c6015c136d5fd9ff28c1e0` used +`git archive --format=tar HEAD`: 1,075,200 archive bytes, 98 entries (84 files), +996,706 unpacked file bytes; largest file 77,973 bytes. No absolute/parent-traversal +or backslash paths, special entries, OS junk, or files at least 5 MiB were found. +This checks those packaging limits only; it does not certify credential absence, +policy compliance or the portal's scan. Repeat against the final release revision. + **Expected holds, not confirmed portal findings:** the MCP command uses `sh`; its launcher invokes another shell file and Python; bootstrap installs registry packages. The launcher derives its root using `dirname/..`, which could trigger a containment finding even though the computed root is inside the plugin. Do not redesign working bootstrapping merely to suppress an inferred hold: run the portal validator and resolve its actual result. Prepare a readable entry-point/dependency explanation for reviewers. Hooks are ignored in chat; local MCP servers also do not run there. Cowork supports hooks/local servers in supported sessions, but DataFog's OS assumptions, environment variables and permission semantics have only been targeted at Claude Code. The portal derives supported surfaces from components. This creates a concrete listing/compatibility risk to resolve, not evidence that Cowork works. [App support matrix](https://claude.com/docs/plugins/platform-support). diff --git a/docs/readiness.md b/docs/readiness.md index 06ac635..a624965 100644 --- a/docs/readiness.md +++ b/docs/readiness.md @@ -8,13 +8,13 @@ publication require Sid's explicit go-ahead. Preparation and verification procee | ID | Gap / required outcome | Status and evidence | | --- | --- | --- | -| I01 | Scan MCP resource-link human-readable metadata without corrupting identifiers. | Fixed locally; agent reports 139 hook tests, 12 MCP tests, lint and type checks passing. Final candidate validation remains open. | +| I01 | Scan MCP resource-link human-readable metadata without corrupting identifiers. | Implemented and committed; focused hook/MCP tests passed. Final candidate CI remains open; see verification/candidate-validation.md. | | I02 | Resolve adjacent Unicode email domain leak. | Local mitigation covers the joined span using core-validated trailing domains. 99 core/vault/stream tests and 90 additional Unicode/domain combinations passed; final integrated validation pending. | | I03 | Resolve or explicitly constrain phone coverage regressions. | Known-format fixtures pin the affected 1.7.0 behavior and README gap 19 discloses it. A general regex workaround is deferred: multiline streaming needs lookahead semantics and numeric-prefix cases need precision evaluation. No complete phone-detection claim is made. | | I04 | Align all public claims with actual coverage. | Manifest/marketplace/README and GitHub About narrowed to detected values. Homepage update drafted for release; no directory availability announced. | | I05 | Verify clean install, first start and MCP startup from distributed repository. | Cached candidate real-host startup, three examples and project boundary passed with source hashes. Fresh 0.2.0→0.2.1 upgrade preserved markers; uninstall retention checked. See verification reports. Public final-release URL check awaits release. | -| I06 | Validate final candidate across supported systems. | v0.2.0 release reports 2,476 passed, 42 skipped, one expected failure; four CI jobs passed. New candidate needs its own lint/types/tests, Linux key-store coverage and live evidence. | -| I07 | Package the reviewed candidate consistently. | Manifest/version/dependency agreement, strict plugin validation, release notes and exact tested revision must agree before submission. | +| I06 | Validate final candidate across supported systems. | Candidate lint/types/strict manifests pass; 187 real-Claude checks and six isolated Linux key-store tests pass. Final four-way CI for fe1bd1c remains active; prior release results are not substituted. | +| I07 | Package the reviewed candidate consistently. | Candidate manifests and pyproject agree on 0.2.1, runtime pins are 1.7.0, and strict manifests pass. Release notes identify tested production baseline and candidate; final CI and release/tag verification remain open. | | I08 | Marker-aware MCP edit must respect denied paths. | Implemented shared Read/Edit matcher, ask/deny refusal and malformed-settings fail-closed behavior. Focused tests and independent retarget-race reproduction pass; final suite pending. | | I09 | Characterize concurrent edits and symlink handling in MCP edit. | Implemented bounded descriptor reads, advisory lock, pinned target and identity/version checks. Independent review passes; final-check/rename race against noncooperating writers remains explicitly disclosed. | | I10 | Enforce reviewed dependency versions at runtime, including failed upgrade. | Implemented metadata-before-import and module-version checks, truthful doctor, verified stamp reuse and failed-bootstrap refusal. Focused failure-path suite and independent review pass; full candidate suite running. | @@ -23,21 +23,21 @@ publication require Sid's explicit go-ahead. Preparation and verification procee | ID | Behavior requiring evidence | Status | | --- | --- | --- | -| V01 | Runner preserves cwd; collects complete stdout/stderr; cancellation and timeout stop descendants. | L04 covers cwd. Real 2.1.327 collected 100 lines per stream; TaskStop and timeout with host background disabled prevented delayed effects. Default timeout auto-backgrounds; docs corrected. Repeat candidate cases after freeze. | -| V02 | Hook allow executes rewritten command without extra prompt in interactive and headless sessions. | Observed default-mode interactive allow on 2.1.299; headless fixture allows pass. | -| V03 | Hook ask displays markers; approve/deny works; persistent approval saves a safe rule; denied-call records retain marker command. | Real UI approve/deny passed; marker remained inside visible wrapper. Tested hook prompt has Yes/No only, no persistent approval. Four headless denial modes preserve marker and no raw value. | -| V04 | Plan, auto, dontAsk and bypassPermissions modes obey documented decisions. | Verify each separately; especially hook ask under bypassPermissions and auto classifier behavior. | -| V05 | Actual permission_mode hook values, including subagents. | Observer captured dontAsk/plan/bypassPermissions/auto; parent and subagent acceptEdits with child agent_id. See host report. | -| V06 | Claude rule matching agrees with plugin for Bash and Read/Edit paths; unknown cases remain conservative. | Unit coverage exists; live parity beyond documented examples remains open. | -| V07 | Trust location and CLAUDE_CONFIG_DIR behavior. | Verify against isolated configuration; do not alter real user trust/settings. | -| V08 | Managed settings from file versus server/MDM. | Cannot infer effective server policy from a file; document supported boundary and verify available cases. | -| V09 | macOS Keychain locked/denied, SSH, login, and interpreter rebuild/update access. | Happy-path creation/read/purge already reported passing; other states remain unverified. | -| V10 | Linux Secret Service: KWallet and locked session keyring. | Private GNOME Keyring CI exists; other providers/states remain unverified. | -| V11 | Built-in Edit result after marker restoration does not unexpectedly expose restored content to model. | Plain old_string plus marker new_string succeeded with no planted raw value in model-facing result. Marker old_string rejected before hook, as documented. | -| V12 | First-install MCP project directory and startup. | Passed in real cached-install 2.1.327 sessions: fresh bootstrap, marker edit and outside-project refusal, with actual cache path and hashes verified. | -| V13 | Blocked prompt and unscannable-file ask user experience. | Observed blocked prompt + sanitized resubmission and generic unscannable Read prompt. UI omission of unscannable warning documented. | -| V14 | Claude Bash sandbox compatibility with runner process sessions. | macOS sandbox enabled with failIfUnavailable and no fallback: outside write denied, tokenized read succeeded. Scope requires explicit temporary data/vault write allowances; Linux remains unverified. | -| V15 | Unsupported platforms fail with actionable messaging. | Windows, Intel Mac, ARM/musl/older-glibc Linux are unsupported; do not imply runtime support from mocked checks. | +| V01 | Runner preserves cwd and output; explicit cancellation/hard timeout stop descendants; default timeout behavior is accurately described. | **Verified scope:** candidate L04 passed cwd persistence; supplementary 2.1.327 probes collected 100 lines per stream and prevented delayed effects after TaskStop or timeout with `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1`. Default timeout auto-backgrounds, as now documented. Runner/wrapper code is unchanged between those probes and this candidate; no redundant repeat is required. Evidence: [candidate live](verification/candidate-validation.md), [host lifecycle](verification/2026-11-18-host-readiness.md). This does not prove unlimited output or every OS/termination signal. | +| V02 | Hook allow executes rewritten command without extra prompt in interactive and headless sessions. | **Verified scope:** default-mode interactive allow on 2.1.299; candidate 2.1.327 L02 and L19 confirm headless rule allow and late restoration; the cached installed Bash example also passed. Other interactive host versions are not certified. Evidence: [host](verification/2026-11-18-host-readiness.md), [candidate cases](verification/candidate-live-results.json), [installed](verification/2026-11-18-installed-candidate.md). | +| V03 | Hook ask retains markers, offered approve/deny choices work, and denial records retain marker commands. | **Verified scope:** real UI Yes/No worked and displayed the marker inside the rewritten wrapper. That hook prompt offers no persistent approval option, so a saved-rule test is inapplicable to this UI. Four headless denial modes preserve markers without raw values; candidate L18 also checks transcript/debug/denial records. Evidence: [interactive excerpts](verification/interactive-2026-11-18.txt), [host report](verification/2026-11-18-host-readiness.md), [candidate cases](verification/candidate-live-results.json). | +| V04 | Plan, auto, dontAsk and bypassPermissions modes obey documented decisions. | **Finite representative checks verified on 2.1.327:** four headless marker-ask denials; interactive bypass marker prompt/No; dontAsk exact-rule allow; interactive plan exact-rule command prompts/No; interactive auto nonmarker ask-rule prompts/No. For a deferred auto command, the guard recorded no decision plus rewritten input, and host permission metadata explicitly attributed acceptance to the classifier; interactive UI also showed `Allowed by auto mode`. This does not certify arbitrary classifier judgments or all mode/command combinations. [Mode evidence](verification/2026-11-18-host-readiness.md#finite-permission-mode-follow-up). | +| V05 | Actual permission_mode hook values, including subagents. | **Representative parent/child values verified:** default, acceptEdits, dontAsk, plan, bypassPermissions and auto arrived literally across probes. General-purpose child Read inherited acceptEdits, plan and dontAsk, with child agent IDs distinguishing it from the parent. Other child types/mode combinations are outside this finite check, not silently counted as covered. [Initial observer evidence](verification/host-readiness-results.json), [mode follow-up](verification/mode-supplement-results.json). | +| V06 | Documented Bash and Read/Edit path-rule cases match host behavior; unsupported cases remain conservative. | **Verified documented fixtures, not full matcher equivalence:** candidate live cases cover allow/ask/deny, untrusted shared allow rules and file/directory/quoted-glob Read restrictions. Broader host rule parity remains unverified; unknown patterns and invisible rules retain the documented conservative/unsupported boundary. Do not claim complete parity from unit tests. [Candidate cases](verification/candidate-live-results.json). | +| V07 | Trust location and CLAUDE_CONFIG_DIR behavior. | **Partial with an authentication boundary:** actual fixture trust was recorded under `~/.claude.json` at the canonical project path, including the installed candidate. A fresh CLAUDE_CONFIG_DIR created `/.claude.json`, but required login before workspace trust; relocated trust-field behavior remains unverified. No credentials were copied, and generated fixture trust/session records were cleaned up. [Installed report](verification/2026-11-18-installed-candidate.md). | +| V08 | Managed settings from file versus server/MDM. | **Disclosed environment limit:** a managed file does not prove the effective server/MDM policy. No organization-managed host was exercised. The plugin cannot enforce policy it cannot read, and the README discloses that boundary; enterprise-policy equivalence remains unverified and must not be promised. | +| V09 | macOS Keychain locked/denied, SSH, login, and interpreter rebuild/update access. | **Happy path verified; environment-specific states remain open:** candidate optional L28 created/read/purged a separate real Keychain entry, preserved markers across processes and measured 15 hook processes. Locked/denied, SSH/login and interpreter-rebuild access were not exercised. These are disclosed state limitations, not covered by happy-path success. [Candidate Keychain evidence](verification/candidate-validation.md). | +| V10 | Linux Secret Service: locked collection, recovery and alternate providers. | **Focused GNOME state verification passed:** six isolated Ubuntu 24.04 tests proved a genuinely locked collection yields bounded refusal without rekey/file fallback, then restores the original marker after actual unlock. KWallet and other providers remain unverified. This focused result does not replace the final four-way platform matrix; fe1bd1c [CI run 44368890375](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44368890375) remains pending in this inventory. [Private keyring evidence](verification/linux-keyring.md). | +| V11 | Built-in Edit result after marker restoration does not unexpectedly expose restored content to model. | **Verified scope on 2.1.327:** plain old_string plus marker new_string changed the real file, with no planted raw value in the model-facing result. Marker old_string was rejected before the hook, confirming the documented host limitation. Local transcripts can still contain restored input; this check does not remove that disclosure. [Host report](verification/2026-11-18-host-readiness.md). | +| V12 | First-install MCP project directory and startup. | **Verified cached candidate on 2.1.327:** real first-start bootstrap, marker-aware edit and outside-project refusal passed; initialization used the installed cache, with source/cache hashes checked. Production files match 276b2b3 and are unchanged at fe1bd1c. This closes local cached-install behavior; public final-release URL verification remains a separate release gate. [Installed report](verification/2026-11-18-installed-candidate.md). | +| V13 | Blocked prompt and unscannable-file ask user experience. | **Verified tested UI:** blocked synthetic prompt offered sanitized resubmission; unscannable Read offered a generic file approval and honored No. The screen-reader UI omitted DataFog's unscannable explanation; that limitation is documented rather than treated as a successful warning. Other renderers remain unverified. [Interactive excerpts](verification/interactive-2026-11-18.txt). | +| V14 | Claude Bash sandbox compatibility with runner process sessions. | **Verified configured macOS boundary:** sandbox enabled with failIfUnavailable and no unsandboxed fallback; a protected write inside the fixture was denied while the same runner returned tokenized content. Temporary plugin data/vault writes were explicitly allowed. Linux sandbox behavior and other sandbox/path configurations remain unverified environment limits. [Host report](verification/2026-11-18-host-readiness.md). | +| V15 | Unsupported platforms are clearly excluded and preflight gives actionable failure messaging. | **Support boundary disclosed; actual unsupported-host runs unverified:** Windows, Intel Mac, ARM/musl/older-glibc Linux remain unsupported. Platform-selection tests do not certify runtime behavior on those machines. No unsupported platform must pass as a supported target; preserve the explicit disable/uninstall guidance and do not market broader support. | ## Product limits requiring accurate disclosure diff --git a/docs/release-notes-0.2.1.md b/docs/release-notes-0.2.1.md index 8c46284..7df1c8f 100644 --- a/docs/release-notes-0.2.1.md +++ b/docs/release-notes-0.2.1.md @@ -25,16 +25,29 @@ Independent review reproduced and verified fixes for an alias-retarget permissio race and repeated email-tail scanning. Cached 0.2.1 model sessions passed Read, Bash, marker-aware edit and outside-project refusal, with installed production-file hashes matching the candidate. The 0.2.0 → 0.2.1 upgrade retained marker identity. -Full-suite and CI results remain to be attached below. - -## Validation to attach - -- Exact candidate commit and version agreement. -- Full Python suite, lint, types, shell parsing and strict manifests. -- Linux/macOS CI matrix, including private Secret Service tests on Linux. -- Real Claude Code read, Bash and marker-aware edit examples. -- Interactive permission behavior, host modes and runner lifecycle evidence. -- Candidate cached install, version-changing upgrade and uninstall retention. +Candidate evidence is recorded below; the final CI matrix remains open. + +## Candidate validation + +Candidate `fe1bd1c848880fc4c3c6015c136d5fd9ff28c1e0` retains the production files +from live-tested `aa99659a0f3218c443a6fcbc17dbeb9e43537574` unchanged. + +- Main real-Claude suite: 187 PASS, 24 INFO, no failures or cap skips. +- Cached installed candidate: fresh startup, Read, Bash, marker-aware edit and + outside-project refusal passed with installed production hashes verified. +- Fresh 0.2.0→0.2.1 upgrade preserved markers; uninstall retention was checked. +- Interactive permission, cancellation and macOS sandbox results are recorded in + the host report, including host limitations and unverified environments. +- Six isolated Linux keyring tests passed, including locked-keyring refusal and + recovery without rekeying or file-key fallback. +- Local lint, types and strict manifests passed. The actual `/bin/sh` fallback's + 27 cases passed after diagnosing an unrelated standalone Apple dash crash. +- The [final CI matrix](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44368890375) + is still running; this candidate is not yet declared ready to release. + +See [candidate validation](verification/candidate-validation.md) for original +failed runs, corrections, evidence links and scope. These results do not imply +portal acceptance or publication. ## Remaining product boundaries diff --git a/docs/verification/2026-11-18-host-readiness.md b/docs/verification/2026-11-18-host-readiness.md index d97f299..a43d789 100644 --- a/docs/verification/2026-11-18-host-readiness.md +++ b/docs/verification/2026-11-18-host-readiness.md @@ -74,10 +74,8 @@ observations but do not certify the final source revision. ## Still unverified -- Interactive plan and auto behavior beyond marker asks; auto classifier handling - of the rewritten command; dontAsk allow path. -- `default` hook input value and other permission modes inside subagents (the - observed child used `acceptEdits`). +- Arbitrary auto-classifier decisions and other command/permission combinations + beyond the finite mode checks below; all subagent types/mode combinations. - Additional Bash and Read/Edit rule parity beyond existing documented fixtures. - Alternate configuration-root trust handling, server-managed policy and MDM. - Locked/denied macOS Keychain, SSH/login/rebuilt-interpreter access; KWallet and @@ -125,3 +123,31 @@ rejection and fixture-settings isolation. The new supplementary probes use the real host directly; their successful observations are listed above rather than inferred from simulator behavior. Sandbox options follow the official [settings reference](https://code.claude.com/docs/en/settings-reference). + +## Finite permission-mode follow-up + +Five additional headless runs and two real PTY sessions on **2.1.327** closed the +remaining representative V04/V05 checks. They reused the existing live Driver +with synthetic fixtures and a file-key vault; no production code or tracked test +harness changed. Source revision was `fe1bd1c`. The observer saved only tool name, +tool-use ID, permission mode and agent metadata. See +[structured results](mode-supplement-results.json) and +[interactive excerpts](mode-supplement-interactive.txt). + +| Probe | Actual behavior and evidence | +| --- | --- | +| `default` exact-rule allow | `pwd` ran; guard recorded step 7 `allow`; actual hook input was the literal `default`. | +| `dontAsk` exact-rule allow | `pwd` ran without a denial; guard recorded step 7 `allow` and input `dontAsk`. This complements the earlier dontAsk marker denial. | +| `auto` deferred wrapper | No fixture rule allowed `date -u +%Y`. Guard recorded step 8 with a null decision and supplied the rewritten runner command. Host debug recorded that updated input; matching `tool_result_meta.permission_decision` reported `decision=accept`, `source=config`, `reason_type=classifier`. The command returned `2026`. This is actual classifier-attributed acceptance, not an inference from a successful command alone. | +| Interactive `auto` deferred wrapper | The same date command ran with no approval prompt; the UI showed `Allowed by auto mode`. Observer/guard records confirmed `auto`, step 8, null hook decision. | +| Interactive `plan` exact-rule allow | `pwd` matched a fixture allow rule, but the hook returned ask with its plan-mode explanation. The UI prompted; selecting No interrupted the call. The hook did not silently approve a read-only command in plan mode. | +| Interactive `auto` explicit ask rule | `git push --dry-run` matched the fixture ask rule and prompted with its rule explanation; selecting No interrupted it. The folder had no Git repository or remote, and the command was not executed. This verifies a nonmarker ask independently of marker restoration. | +| General-purpose child under `plan` | Parent Agent and child Read both received literal `plan`; the child was identified by its own agent ID and completed the allowed read. | +| General-purpose child under `dontAsk` | Parent Agent and child Read both received literal `dontAsk`; the child was identified by its own agent ID and completed the allowed read. Together with the earlier acceptEdits case, these are representative inherited modes, not every possible subagent configuration. | + +Both PTY sessions were exited. The host's own `claude purge +--yes` removed only these fixtures' local host records, trust and prompt history. +Synthetic raw evidence remains in their temporary log directories. No credentials +were copied, no real vault was opened, and no user-owned project was modified. +The classifier result characterizes this safe command on this host version; it +does not promise how the classifier will judge arbitrary commands or future hosts. diff --git a/docs/verification/candidate-validation.md b/docs/verification/candidate-validation.md index 218abd5..1c8bbe8 100644 --- a/docs/verification/candidate-validation.md +++ b/docs/verification/candidate-validation.md @@ -54,9 +54,12 @@ unlock protocol. All six private keyring tests passed in an isolated Ubuntu 24.0 container, including locked-state refusal, no rekey or file-key fallback, and recovery of the original marker. See [Linux keyring evidence](linux-keyring.md). -The revised four-way platform matrix must pass before submission. CI for `276b2b3` is -[run 44365243455](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44365243455). -Strict manifest validation has passed. Local lint and mypy pass on 21 engine modules. +The revised four-way platform matrix must pass before submission. Final fixture +and evidence commit `fe1bd1c` is being tested by +[run 44368890375](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44368890375). +Its strict manifest job passed; platform tests remain pending. Local lint and mypy +pass on 21 engine modules. The previous run for `276b2b3` was cancelled after its +Linux fixture failure once the corrected candidate run started; it is not green evidence. An earlier local full-suite attempt was intentionally interrupted when the failed dependency-upgrade gap was found. It is not release evidence. The earlier GitHub diff --git a/docs/verification/mode-supplement-interactive.txt b/docs/verification/mode-supplement-interactive.txt new file mode 100644 index 0000000..9bc66f5 --- /dev/null +++ b/docs/verification/mode-supplement-interactive.txt @@ -0,0 +1,43 @@ +Claude Code 2.1.327 real screen-reader PTY, synthetic fixture. Paths redacted. No selected for both prompts. + +plan mode: +Permission Required: Bash command +> Print current working directory +> . /scripts/wrap.sh && +> __datafog_run +> /scripts/datafog-guard +> /data +> /vault pwd +> Hook PreToolUse:Bash requires confirmation for this command: +> DataFog: plan mode. allowed by a Bash allow rule in your Claude Code local +> project settings. The plugin does not approve commands while planning. +> [plugin:datafog] +plugin hooks.json to update hooks +Do you want to proceed? +1. Yes +2. No +Select with numbers [1-2]. Then Enter to submit or Escape to cancel: + +--- +auto mode: +Permission Required: Bash command +> Dry-run a git push +> . /scripts/wrap.sh && +> __datafog_run +> /scripts/datafog-guard +> /data +> /vault 'git push --dry-run' +> Hook PreToolUse:Bash requires confirmation for this command: +> DataFog: a Bash ask rule in your Claude Code project settings matches this +> command (or a part of it). [plugin:datafog] +plugin hooks.json to update hooks +Do you want to proceed? +1. Yes +2. No +Select with numbers [1-2]. Then Enter to submit or Escape to cancel: + +--- +auto mode execution excerpt: +2026 +Allowed by auto mode +claude: The command printed 2026. diff --git a/docs/verification/mode-supplement-results.json b/docs/verification/mode-supplement-results.json new file mode 100644 index 0000000..556e3fb --- /dev/null +++ b/docs/verification/mode-supplement-results.json @@ -0,0 +1,352 @@ +{ + "provenance": { + "revision": "fe1bd1c848880fc4c3c6015c136d5fd9ff28c1e0", + "claude": "2.1.327", + "kind": "real host supplemental modes" + }, + "cases": [ + { + "case": "default-allow", + "version": "2.1.327", + "exit": 0, + "tool_names": [ + { + "name": "Bash", + "subagent": false + } + ], + "observed_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01Rb2x9ij1BiceeqD3Exwu5d", + "permission_mode": "default", + "agent_id": null, + "agent_type": null + } + ], + "guard_permissions": [ + { + "action": "bash_wrapped", + "decision": "allow", + "event": "PreToolUse", + "ms": 38.5, + "permission": { + "mode": "default", + "step": 7 + }, + "tool": "Bash", + "ts": "2026-11-18T18:24:07Z" + } + ], + "permission_metadata": [ + { + "id": "toolu_01Rb2x9ij1BiceeqD3Exwu5d", + "permission_decision": { + "decision": "accept", + "source": "hook", + "reason_type": "hook" + } + } + ], + "denial_count": 0, + "result_errors": [ + false + ], + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-mode-supplement.5aeyiyck/log/runs/01-default-allow.jsonl", + "requested_commands": [ + "pwd" + ] + }, + { + "case": "dontAsk-allow", + "version": "2.1.327", + "exit": 0, + "tool_names": [ + { + "name": "Bash", + "subagent": false + } + ], + "observed_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01S5D5u3uSdG52MghgU8Rhk7", + "permission_mode": "dontAsk", + "agent_id": null, + "agent_type": null + } + ], + "guard_permissions": [ + { + "action": "bash_wrapped", + "decision": "allow", + "event": "PreToolUse", + "ms": 37.7, + "permission": { + "mode": "dontAsk", + "step": 7 + }, + "tool": "Bash", + "ts": "2026-11-18T18:24:14Z" + } + ], + "permission_metadata": [ + { + "id": "toolu_01S5D5u3uSdG52MghgU8Rhk7", + "permission_decision": { + "decision": "accept", + "source": "hook", + "reason_type": "hook" + } + } + ], + "denial_count": 0, + "result_errors": [ + false + ], + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-mode-supplement.5aeyiyck/log/runs/02-dontAsk-allow.jsonl", + "requested_commands": [ + "pwd" + ] + }, + { + "case": "auto-defer", + "version": "2.1.327", + "exit": 0, + "tool_names": [ + { + "name": "Bash", + "subagent": false + } + ], + "observed_inputs": [ + { + "tool_name": "Bash", + "tool_use_id": "toolu_01YQUE5irLzfBdoso7nxWKfW", + "permission_mode": "auto", + "agent_id": null, + "agent_type": null + } + ], + "guard_permissions": [ + { + "action": "bash_wrapped", + "decision": null, + "event": "PreToolUse", + "ms": 67.4, + "permission": { + "mode": "auto", + "step": 8 + }, + "tool": "Bash", + "ts": "2026-11-18T18:24:25Z" + } + ], + "permission_metadata": [ + { + "id": "toolu_01YQUE5irLzfBdoso7nxWKfW", + "permission_decision": { + "decision": "accept", + "source": "config", + "reason_type": "classifier" + } + } + ], + "denial_count": 0, + "result_errors": [ + false + ], + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-mode-supplement.5aeyiyck/log/runs/03-auto-defer.jsonl", + "requested_commands": [ + "date -u +%Y" + ], + "host_recorded_updated_command": ". /scripts/wrap.sh && __datafog_run /scripts/datafog-guard /data /vault 'date -u +%Y'" + }, + { + "case": "plan-child", + "version": "2.1.327", + "exit": 0, + "tool_names": [ + { + "name": "Agent", + "subagent": false + }, + { + "name": "Read", + "subagent": true + } + ], + "observed_inputs": [ + { + "tool_name": "Agent", + "tool_use_id": "toolu_01LFVpjLEJTS2iNji6t12JYw", + "permission_mode": "plan", + "agent_id": null, + "agent_type": null + }, + { + "tool_name": "Read", + "tool_use_id": "toolu_01B7hfqRnUgo9tFsYfW9XLxF", + "permission_mode": "plan", + "agent_id": "a6670307e7f014c7d", + "agent_type": "general-purpose" + } + ], + "guard_permissions": [], + "permission_metadata": [ + { + "id": "toolu_01B7hfqRnUgo9tFsYfW9XLxF", + "permission_decision": { + "decision": "accept", + "source": "config", + "reason_type": "rule" + } + }, + { + "id": "toolu_01LFVpjLEJTS2iNji6t12JYw", + "permission_decision": { + "decision": "accept", + "source": "config", + "reason_type": "classifier" + } + } + ], + "denial_count": 0, + "result_errors": [ + false, + false + ], + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-mode-supplement.5aeyiyck/log/runs/04-plan-child.jsonl", + "requested_commands": [] + }, + { + "case": "dontAsk-child", + "version": "2.1.327", + "exit": 0, + "tool_names": [ + { + "name": "Agent", + "subagent": false + }, + { + "name": "Read", + "subagent": true + } + ], + "observed_inputs": [ + { + "tool_name": "Agent", + "tool_use_id": "toolu_01JBULGdT1ct8ZMHeCrUr63W", + "permission_mode": "dontAsk", + "agent_id": null, + "agent_type": null + }, + { + "tool_name": "Read", + "tool_use_id": "toolu_01EFJ9xmQXBjejdUnZEsfJ5L", + "permission_mode": "dontAsk", + "agent_id": "a3687a43a65005eca", + "agent_type": "general-purpose" + } + ], + "guard_permissions": [], + "permission_metadata": [ + { + "id": "toolu_01EFJ9xmQXBjejdUnZEsfJ5L", + "permission_decision": { + "decision": "accept", + "source": "config", + "reason_type": "rule" + } + }, + { + "id": "toolu_01JBULGdT1ct8ZMHeCrUr63W", + "permission_decision": { + "decision": "accept", + "source": "config", + "reason_type": "rule" + } + } + ], + "denial_count": 0, + "result_errors": [ + false, + false + ], + "transcript": "/var/folders/kt/xxfb4y954tbfw5mpmgm4ybq00000gn/T/datafog-mode-supplement.5aeyiyck/log/runs/05-dontAsk-child.jsonl", + "requested_commands": [] + } + ], + "interactive_observed_inputs": [ + { + "tool_name": "Bash", + "permission_mode": "plan", + "agent_id": null, + "agent_type": null + }, + { + "tool_name": "Bash", + "permission_mode": "auto", + "agent_id": null, + "agent_type": null + }, + { + "tool_name": "Bash", + "permission_mode": "auto", + "agent_id": null, + "agent_type": null + } + ], + "interactive_guard_permissions": [ + { + "action": "bash_wrapped", + "decision": "ask", + "event": "PreToolUse", + "ms": 66.5, + "permission": { + "mode": "plan", + "step": 7 + }, + "tool": "Bash", + "ts": "2026-11-18T18:24:38Z" + }, + { + "action": "bash_wrapped", + "decision": null, + "event": "PreToolUse", + "ms": 68.1, + "permission": { + "mode": "auto", + "step": 8 + }, + "tool": "Bash", + "ts": "2026-11-18T18:25:20Z" + }, + { + "action": "bash_wrapped", + "decision": "ask", + "event": "PreToolUse", + "ms": 40.6, + "permission": { + "mode": "auto", + "step": 3 + }, + "tool": "Bash", + "ts": "2026-11-18T18:25:50Z" + } + ], + "interactive_cases": [ + { + "case": "plan-exact-allow", + "result": "prompted; No interrupted" + }, + { + "case": "auto-deferred-date", + "result": "ran without prompt; UI Allowed by auto mode" + }, + { + "case": "auto-explicit-ask-rule", + "result": "prompted; No interrupted" + } + ] +} From 21207082bb24a2742aee7e5502601fcc6b572496 Mon Sep 17 00:00:00 2001 From: Sid Mohan <61345237+sidmohan0@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:52:40 -0800 Subject: [PATCH 5/5] Measure background drain from command start and record verification --- docs/directory-submission.md | 2 +- docs/readiness.md | 12 ++-- docs/release-notes-0.2.1.md | 11 +-- docs/verification/background-drain-timing.md | 73 ++++++++++++++++++++ docs/verification/candidate-validation.md | 26 +++++-- tests/test_bash_boundary.py | 59 ++++++++++++++-- 6 files changed, 164 insertions(+), 19 deletions(-) create mode 100644 docs/verification/background-drain-timing.md diff --git a/docs/directory-submission.md b/docs/directory-submission.md index cff2850..ecf3cff 100644 --- a/docs/directory-submission.md +++ b/docs/directory-submission.md @@ -73,7 +73,7 @@ Bundled `assets/datafog-icon-512.png` is the 512×512 PNG linked by the official **Documentation:** `https://github.com/DataFog/datafog-claude-plugin#readme`. -**Support:** `https://github.com/DataFog/datafog-claude-plugin/issues`; do not put personal data or credentials in public issues. Private security reports: `https://github.com/DataFog/datafog-claude-plugin/security/advisories/new` (enabled and verified by the root workstream). Portal contact is populated; mailbox ownership remains unverified. +**Support:** `https://github.com/DataFog/datafog-claude-plugin/issues`; do not put personal data or credentials in public issues. Private security reports: `https://github.com/DataFog/datafog-claude-plugin/security/advisories/new` (enabled and verified by the root workstream). Portal contact matches the authenticated Gmail profile, confirming mailbox access; no portal verification badge or test delivery is claimed. **Privacy policy:** `https://github.com/DataFog/datafog-claude-plugin/blob/main/PRIVACY.md` (authored locally; URL becomes live after push). **License:** Apache-2.0. diff --git a/docs/readiness.md b/docs/readiness.md index a624965..a87124c 100644 --- a/docs/readiness.md +++ b/docs/readiness.md @@ -8,16 +8,16 @@ publication require Sid's explicit go-ahead. Preparation and verification procee | ID | Gap / required outcome | Status and evidence | | --- | --- | --- | -| I01 | Scan MCP resource-link human-readable metadata without corrupting identifiers. | Implemented and committed; focused hook/MCP tests passed. Final candidate CI remains open; see verification/candidate-validation.md. | -| I02 | Resolve adjacent Unicode email domain leak. | Local mitigation covers the joined span using core-validated trailing domains. 99 core/vault/stream tests and 90 additional Unicode/domain combinations passed; final integrated validation pending. | +| I01 | Scan MCP resource-link human-readable metadata without corrupting identifiers. | Implemented and committed; focused hook/MCP tests passed. The corrected candidate four-way CI passed; see verification/candidate-validation.md. | +| I02 | Resolve adjacent Unicode email domain leak. | Local mitigation covers the joined span using core-validated trailing domains. 99 core/vault/stream tests and 90 additional Unicode/domain combinations passed; the corrected candidate four-way CI passed. | | I03 | Resolve or explicitly constrain phone coverage regressions. | Known-format fixtures pin the affected 1.7.0 behavior and README gap 19 discloses it. A general regex workaround is deferred: multiline streaming needs lookahead semantics and numeric-prefix cases need precision evaluation. No complete phone-detection claim is made. | | I04 | Align all public claims with actual coverage. | Manifest/marketplace/README and GitHub About narrowed to detected values. Homepage update drafted for release; no directory availability announced. | | I05 | Verify clean install, first start and MCP startup from distributed repository. | Cached candidate real-host startup, three examples and project boundary passed with source hashes. Fresh 0.2.0→0.2.1 upgrade preserved markers; uninstall retention checked. See verification reports. Public final-release URL check awaits release. | -| I06 | Validate final candidate across supported systems. | Candidate lint/types/strict manifests pass; 187 real-Claude checks and six isolated Linux key-store tests pass. Final four-way CI for fe1bd1c remains active; prior release results are not substituted. | +| I06 | Validate final candidate across supported systems. | Candidate lint/types/strict manifests pass; 187 real-Claude checks and six isolated Linux key-store tests pass. The corrected candidate four-way CI for fe1bd1c passed: Linux 2,609 passed/3 skipped and macOS 2,569 passed/43 skipped per Python version. Documentation follow-up CI is tracked separately. | | I07 | Package the reviewed candidate consistently. | Candidate manifests and pyproject agree on 0.2.1, runtime pins are 1.7.0, and strict manifests pass. Release notes identify tested production baseline and candidate; final CI and release/tag verification remain open. | -| I08 | Marker-aware MCP edit must respect denied paths. | Implemented shared Read/Edit matcher, ask/deny refusal and malformed-settings fail-closed behavior. Focused tests and independent retarget-race reproduction pass; final suite pending. | +| I08 | Marker-aware MCP edit must respect denied paths. | Implemented shared Read/Edit matcher, ask/deny refusal and malformed-settings fail-closed behavior. Focused tests and independent retarget-race reproduction pass; the corrected candidate four-way CI passed. | | I09 | Characterize concurrent edits and symlink handling in MCP edit. | Implemented bounded descriptor reads, advisory lock, pinned target and identity/version checks. Independent review passes; final-check/rename race against noncooperating writers remains explicitly disclosed. | -| I10 | Enforce reviewed dependency versions at runtime, including failed upgrade. | Implemented metadata-before-import and module-version checks, truthful doctor, verified stamp reuse and failed-bootstrap refusal. Focused failure-path suite and independent review pass; full candidate suite running. | +| I10 | Enforce reviewed dependency versions at runtime, including failed upgrade. | Implemented metadata-before-import and module-version checks, truthful doctor, verified stamp reuse and failed-bootstrap refusal. Focused failure-path suite and independent review pass; the corrected candidate four-way CI passed. | ## Runtime verification gates @@ -32,7 +32,7 @@ publication require Sid's explicit go-ahead. Preparation and verification procee | V07 | Trust location and CLAUDE_CONFIG_DIR behavior. | **Partial with an authentication boundary:** actual fixture trust was recorded under `~/.claude.json` at the canonical project path, including the installed candidate. A fresh CLAUDE_CONFIG_DIR created `/.claude.json`, but required login before workspace trust; relocated trust-field behavior remains unverified. No credentials were copied, and generated fixture trust/session records were cleaned up. [Installed report](verification/2026-11-18-installed-candidate.md). | | V08 | Managed settings from file versus server/MDM. | **Disclosed environment limit:** a managed file does not prove the effective server/MDM policy. No organization-managed host was exercised. The plugin cannot enforce policy it cannot read, and the README discloses that boundary; enterprise-policy equivalence remains unverified and must not be promised. | | V09 | macOS Keychain locked/denied, SSH, login, and interpreter rebuild/update access. | **Happy path verified; environment-specific states remain open:** candidate optional L28 created/read/purged a separate real Keychain entry, preserved markers across processes and measured 15 hook processes. Locked/denied, SSH/login and interpreter-rebuild access were not exercised. These are disclosed state limitations, not covered by happy-path success. [Candidate Keychain evidence](verification/candidate-validation.md). | -| V10 | Linux Secret Service: locked collection, recovery and alternate providers. | **Focused GNOME state verification passed:** six isolated Ubuntu 24.04 tests proved a genuinely locked collection yields bounded refusal without rekey/file fallback, then restores the original marker after actual unlock. KWallet and other providers remain unverified. This focused result does not replace the final four-way platform matrix; fe1bd1c [CI run 44368890375](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44368890375) remains pending in this inventory. [Private keyring evidence](verification/linux-keyring.md). | +| V10 | Linux Secret Service: locked collection, recovery and alternate providers. | **Focused GNOME state verification passed:** six isolated Ubuntu 24.04 tests proved a genuinely locked collection yields bounded refusal without rekey/file fallback, then restores the original marker after actual unlock. KWallet and other providers remain unverified. This focused result does not replace the final four-way platform matrix; 3497286 [CI run 44369937374](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44369937374) had one macOS background-output timing failure; its Linux jobs passed. Test-only measurement correction and negative controls pass; revised CI remains required (see verification/background-drain-timing.md). [Private keyring evidence](verification/linux-keyring.md). | | V11 | Built-in Edit result after marker restoration does not unexpectedly expose restored content to model. | **Verified scope on 2.1.327:** plain old_string plus marker new_string changed the real file, with no planted raw value in the model-facing result. Marker old_string was rejected before the hook, confirming the documented host limitation. Local transcripts can still contain restored input; this check does not remove that disclosure. [Host report](verification/2026-11-18-host-readiness.md). | | V12 | First-install MCP project directory and startup. | **Verified cached candidate on 2.1.327:** real first-start bootstrap, marker-aware edit and outside-project refusal passed; initialization used the installed cache, with source/cache hashes checked. Production files match 276b2b3 and are unchanged at fe1bd1c. This closes local cached-install behavior; public final-release URL verification remains a separate release gate. [Installed report](verification/2026-11-18-installed-candidate.md). | | V13 | Blocked prompt and unscannable-file ask user experience. | **Verified tested UI:** blocked synthetic prompt offered sanitized resubmission; unscannable Read offered a generic file approval and honored No. The screen-reader UI omitted DataFog's unscannable explanation; that limitation is documented rather than treated as a successful warning. Other renderers remain unverified. [Interactive excerpts](verification/interactive-2026-11-18.txt). | diff --git a/docs/release-notes-0.2.1.md b/docs/release-notes-0.2.1.md index 7df1c8f..bc0f550 100644 --- a/docs/release-notes-0.2.1.md +++ b/docs/release-notes-0.2.1.md @@ -25,11 +25,12 @@ Independent review reproduced and verified fixes for an alias-retarget permissio race and repeated email-tail scanning. Cached 0.2.1 model sessions passed Read, Bash, marker-aware edit and outside-project refusal, with installed production-file hashes matching the candidate. The 0.2.0 → 0.2.1 upgrade retained marker identity. -Candidate evidence is recorded below; the final CI matrix remains open. +Candidate evidence is recorded below. Current release-gate status and the exact +reviewed head are maintained in [PR #3](https://github.com/DataFog/datafog-claude-plugin/pull/3). ## Candidate validation -Candidate `fe1bd1c848880fc4c3c6015c136d5fd9ff28c1e0` retains the production files +Tested candidate `34972866ac011d3789aad5f0915a646bd188616c` retains the production files from live-tested `aa99659a0f3218c443a6fcbc17dbeb9e43537574` unchanged. - Main real-Claude suite: 187 PASS, 24 INFO, no failures or cap skips. @@ -42,8 +43,10 @@ from live-tested `aa99659a0f3218c443a6fcbc17dbeb9e43537574` unchanged. recovery without rekeying or file-key fallback. - Local lint, types and strict manifests passed. The actual `/bin/sh` fallback's 27 cases passed after diagnosing an unrelated standalone Apple dash crash. -- The [final CI matrix](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44368890375) - is still running; this candidate is not yet declared ready to release. +- The corrected-candidate four-way matrix passed at `fe1bd1c`. A subsequent + documentation-only run exposed a background-drain test timing failure; its + investigation and correction are retained in the validation report. Require all + checks on the current PR head to pass before release. See [candidate validation](verification/candidate-validation.md) for original failed runs, corrections, evidence links and scope. These results do not imply diff --git a/docs/verification/background-drain-timing.md b/docs/verification/background-drain-timing.md new file mode 100644 index 0000000..98306c4 --- /dev/null +++ b/docs/verification/background-drain-timing.md @@ -0,0 +1,73 @@ +# Background-output drain timing + +Investigated 2026-11-18 after the macOS/Python 3.10 job for candidate `3497286` +failed `test_background_job_writing_after_the_command_returned` with Bash and +`(sleep 6; cat s.txt) & echo started`. The measured 6.232 seconds exceeded the +test's 5.5-second bound; exit status, readiness output and no-raw-value assertions +passed. That run remains failed evidence, not a successful retry. + +## Measurement and controls + +The old timer started before `hooked.run()`, which first runs a separate +PreToolUse Python process and only then starts the rewritten command and its +runner. It therefore measured initialization as well as the background drain. +Production `GRACE_SECONDS` is 3.0 and starts after the command's status arrives. + +Four unchanged local runs, instrumented with command-start/end fixture files, +measured: + +| Stage | Observed duration | +| --- | --- | +| Separate PreToolUse call | 0.079–0.107 s | +| Runner launch to command start | 0.315–0.512 s | +| Foreground command body | 0.0005–0.0011 s | +| Command end to runner completion | 3.019–3.026 s | + +A controlled three-second delay in the temporary fixture launcher reproduced +the old assertion failure: 6.515 seconds total, despite a 3.021-second drain +after readiness. No production file was changed. Conversely, setting the grace +period to 30 seconds in a temporary runner shim caused the post-readiness +5.5-second bound to fail while the six-second background child remained active. +These controls distinguish initialization delay from loss of bounded draining. + +The CI failure log has no stage timestamps, so its precise cause—initialization, +scheduling or another delay—cannot be established retrospectively. Local results +do not prove which delay happened in that job or rule out every possible runtime +race. They do demonstrate a defect in the original test's timing boundary. + +## Corrected regression + +Only the test changes. A tiny fixture helper writes a shared monotonic timestamp +immediately before the original command starts. The observer waits for the real +runner's `started` line and then uses the remaining time until +**producer timestamp + 5.5 seconds**. It does not restart the timer when the line is read; a delayed +observer cannot shorten the measured drain or grant extra time. + +The original commands, six-second late writer, exit-status check and raw-value +assertions remain. A separate 40-second readiness bound covers initialization. +Failure cleanup terminates both the test's isolated wrapper group and the private +command group recorded by the fixture helper. Successful cases retain the original +wait for the late writer to finish. There are no retries, +expected failures or relaxed drain thresholds. Production runner code is unchanged. + +The actual revised test passed with a three-second launcher delay. A second control +disabled grace and delayed the observer's first read by two seconds; the test still +failed at its producer-based 5.5-second bound. The delayed read did not grant extra time. + +An initial cleanup control found that killing only the outer group could leave a +60-second background descendant alive: the command monitor had already reported +foreground exit. That private group was explicitly terminated during diagnosis. +After recording and terminating the fixture's private command group as well, the +same control found no live group members after 0.030 seconds. The recorded PGID +matched the background descendant's actual PGID; cleanup never targets an arbitrary +user process or the test runner's own group. + +Production normal grace closes the output pipes; it does not promise to terminate +every lingering background job. This test-cleanup change makes no new claim about +production cancellation after foreground completion or every termination signal. + +The focused background/liveness and within-grace output tests passed (10 cases). +Local raw measurements are in +`.live/readiness-validation/drain-stage-timings.json`, +`drain-negative-controls.json`, `drain-corrected-test-controls.json` and +`drain-cleanup-control.json`. diff --git a/docs/verification/candidate-validation.md b/docs/verification/candidate-validation.md index 1c8bbe8..7da912b 100644 --- a/docs/verification/candidate-validation.md +++ b/docs/verification/candidate-validation.md @@ -54,10 +54,23 @@ unlock protocol. All six private keyring tests passed in an isolated Ubuntu 24.0 container, including locked-state refusal, no rekey or file-key fallback, and recovery of the original marker. See [Linux keyring evidence](linux-keyring.md). -The revised four-way platform matrix must pass before submission. Final fixture -and evidence commit `fe1bd1c` is being tested by -[run 44368890375](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44368890375). -Its strict manifest job passed; platform tests remain pending. Local lint and mypy +The corrected candidate `fe1bd1c` passed its complete four-way matrix in +[run 44368890375](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44368890375): +Linux Python 3.10/3.12 each had **2,609 passed, 3 skipped**; macOS Python 3.10/3.12 +each had **2,569 passed, 43 skipped**. Strict manifests, shell parsing, lint and +types also passed. These results include the corrected keyring and actual `/bin/sh` +fixtures; no failed case was marked expected or skipped to obtain this result. + +The documentation follow-up `3497286` was tested by +[run 44369937374](https://github.com/DataFog/datafog-claude-plugin/actions/runs/44369937374). +Its manifests and both Linux jobs passed, as did macOS Python 3.12. macOS Python +3.10 had 2,568 passed, 43 skipped and one failure: the background-output test +measured 6.232 seconds against a 5.5-second bound. Its no-sentinel and successful +command assertions passed. The original aggregate timer included hook/runner startup. The corrected test uses +a producer-side monotonic timestamp and retains the 5.5-second bound; ten focused +cases pass, and disabling grace still fails that bound. Exact CI-stage attribution +remains unknown. See [diagnosis and controls](background-drain-timing.md); the earlier +green run does not override the failed run, and revised CI remains required. Local lint and mypy pass on 21 engine modules. The previous run for `276b2b3` was cancelled after its Linux fixture failure once the corrected candidate run started; it is not green evidence. @@ -74,3 +87,8 @@ marker preservation and retention, with cache hashes checked against the candida Public release URLs, the portal's final scan/review, and directory publication remain gated on the owner's instruction. Environment-specific limitations are retained in the [readiness inventory](../readiness.md); green tests do not erase those limits. + +Current release-gate status and exact head are maintained in [PR #3](https://github.com/DataFog/datafog-claude-plugin/pull/3). +Historical results above must not be substituted for successful checks on the current +head when test or runtime code changes. Documentation-only result recording does not +change the tested runtime; any such difference must remain explicit. diff --git a/tests/test_bash_boundary.py b/tests/test_bash_boundary.py index 00bf3b9..c184da9 100644 --- a/tests/test_bash_boundary.py +++ b/tests/test_bash_boundary.py @@ -10,7 +10,10 @@ from __future__ import annotations import os +import select +import shlex import shutil +import signal import subprocess import sys import time @@ -235,12 +238,60 @@ def test_known_residual_sweeping_proc_for_any_process_of_the_user(box): "nohup sh -c 'sleep 6; cat s.txt' >/dev/stdout 2>&1 & echo started", ]) def test_background_job_writing_after_the_command_returned(hooked, command): - started = time.time() - result = hooked.run(command, timeout=40) - took = time.time() - started + # Time the real command, not the separate PreToolUse/Python initialization. Record + # the producer's clock so a delayed parent read cannot restart or shorten the bound. + clock = hooked.box.write("drain-clock.py", "import os, time\nfrom pathlib import Path\n" + "Path('drain-start').write_text(f'{time.monotonic()} {os.getpgrp()}')\n") + script = hooked.command(f"{shlex.quote(sys.executable)} {shlex.quote(str(clock))}; {command}") + process = subprocess.Popen(["sh", "-c", '"$0" -c "$1"', hooked.shell, script], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, + cwd=hooked.box.project, start_new_session=True, + env={"PATH": os.environ["PATH"], "HOME": str(hooked.box.tmp), + "SHELL": shutil.which(hooked.shell)}) + finished = False + try: + startup_deadline = time.monotonic() + 40 + first = b"" + while not first.endswith(b"\n") and len(first) < 1024: + remaining = startup_deadline - time.monotonic() + assert remaining > 0 and select.select([process.stdout], [], [], remaining)[0], \ + "the command never reached its readiness marker" + byte = process.stdout.read(1) + if not byte: + break + first += byte + assert first == b"started\n", first + stamp, _ = (hooked.box.project / "drain-start").read_text().split() + started = float(stamp) + remaining = started + 5.5 - time.monotonic() + assert remaining > 0, "the command's 5.5s bound expired before readiness was observed" + try: + out, err = process.communicate(timeout=remaining) + except subprocess.TimeoutExpired: + pytest.fail("the background-output drain exceeded 5.5s from the producer's start timestamp") + took = time.monotonic() - started + result = subprocess.CompletedProcess(process.args, process.returncode, first + out, err) + finished = True + finally: + if not finished: + # The runner's command has its own session. Its monitor may have exited + # after the foreground command, so killing the outer group alone is insufficient. + groups = {process.pid} + try: + _, group = (hooked.box.project / "drain-start").read_text().split() + groups.add(int(group)) + except (OSError, ValueError): + pass + for group in groups: + assert group > 0 and group != os.getpgrp(), "cleanup must only target this fixture's private groups" + try: + os.killpg(group, signal.SIGKILL) + except ProcessLookupError: + pass + process.communicate(timeout=10) assert result.returncode == 0 and b"started" in result.stdout assert_no_sentinel(captured(result)) - assert took < 5.5, "the wait for background output is bounded" + assert took < 5.5, "the wait for background output is bounded from command start" time.sleep(max(0, 7 - took) if "sleep 6" in command else 0) # let the job finish: it must not find a way out