Repository navigation
v0.9.3: reliability and security hardening - #39
Merged
Merged
Conversation
The bearer token was a SHA-256 of the pid, the clock, a stack address and $USER — all observable or guessable by another local user. It is now 256 bits from the OS CSPRNG (getrandom), with no fallback: the daemon refuses to start rather than run with a weak credential. A fresh token is minted per bind. daemon.json was written with the umask's permissions and chmod'ed afterwards, ignoring a chmod failure. It is now created 0600 with O_EXCL under a temporary name, fsynced and renamed into place (secure_fs::write_private_atomic). The sequential server read requests with BufRead::read_line: unbounded in size, and with a per-read timeout that a peer trickling bytes never tripped. Requests are now capped at 16 MiB and must arrive whole within 30 s, so an unauthenticated local process can cost the daemon at most that. Parse errors are no longer echoed to the unauthenticated peer, and the token is redacted from Debug output. Tests cover token entropy/uniqueness, loopback binding, malformed/truncated/ oversized requests, a stalled connection, concurrent clients, idle shutdown, token rotation across restarts and file permissions.
… credentials - Connect timeout (10 s) separate from the generation timeout, so a server that is not there is reported in seconds. - Response bodies capped at 8 MiB and read through Read::take; an unbounded `response.text()` was a memory DoS from a misbehaving server. - HTTP 429/500/502/503/504 and dropped connections are retried at most twice with exponential backoff, honouring Retry-After up to 30 s. Timeouts and other 4xx are not retried, so the worst case is a known small multiple of one request. - Redirects are not followed: one would re-send the code, and cross-origin possibly the key, somewhere the user did not configure. - The URL is validated up front (http/https with a host). `user:pass@` and the query string are removed from every label, error and identity; reqwest errors are stripped of their URL; an echoed API key is masked; server error text is stripped of control characters and truncated. - An API key is refused over plain HTTP to a non-loopback host unless DIFFMIND_ALLOW_INSECURE_API_KEY=1. Adds ReviewBackend::cache_identity (defaulting to describe()). The remote identity includes Ollama's model digest from /api/tags when available and says `unverified` otherwise, so a re-pulled tag cannot replay old cached findings. Tested against a scripted local HTTP server: 429 then success, bounded 5xx retries, no retry on 4xx, dropped connection, invalid JSON, missing fields, oversized and huge-error bodies, a stalled server, connection refused, redirects, credential redaction and digest tracking.
…er a per-user secret Key coverage. Keys were built from a hand-maintained list of prompt ingredients (chunk, unrendered context, rule-set digest, ...). The prompt that is actually sent depends on the backend's window and the split depth, which decide how much context and which rule sets are rendered; neither was in the key. Keys are now derived from the exact rendered prompt, every generation option (temperature, seed, max tokens, repeat penalty and window, JSON mode), the prompt version, and ReviewBackend::cache_identity. Fields are length-prefixed so adjacent fields cannot run together. Model identity. The local backend's identity now includes the pinned GGUF SHA-256 (verified at download, size re-checked at load), so a revision change behind the same file name and label cannot replay findings. Remote identities come from the backend (see the previous commit). Trust. The cache lives in the repository under review, and every input to a key was public, so a branch could commit `.diffmind/cache/<key>.json` saying "no findings" for its own change. Keys are now an HMAC-SHA256 under a 256-bit per-user secret in ~/.diffmind/cache-secret (0600, OS CSPRNG, outside the repository), and each entry stores the key it was written for, checked on read. No secret means no cache, never an unkeyed one. Robustness. Entries over 8 MiB, truncated, corrupt, from another format version or under the wrong key are misses, never errors. Temporary files are unique per process and call, so concurrent threads cannot interleave writes. The cache is pruned to 20,000 entries per run; prune() existed but was never called. ENTRY_VERSION 2 invalidates 0.9.2 entries once.
…uity Freshness. The graph skipped any file whose mtime matched, so an edit inside one timestamp tick, or one that restored an old mtime (cp -p, rsync -t, touch -r), left the previous version's symbols and line ranges in place, and context then quoted whatever now sits at those lines. Each file now records mtime, inode change time (Unix), size, content hash and when it was indexed. The metadata fast path is taken only when all match and the file is older than a 2 s racy window (git's racily-clean rule); otherwise the file is hashed, and reparsed only if the content changed. Old untouched files are not re-read (files_hashed is reported). A file that stops parsing or stops being UTF-8 drops its old rows. Files over 4 MiB are recorded without parsing. Context. rag.rs withholds all context when the working tree is not the diff's post-image (sampled added lines must match at their line numbers), as with `--range a..b` on another checkout or `--staged` under unstaged edits. Reads go through graph::read_repo_file, which refuses absolute paths and `..`, does not follow symlinks out of the repository and caps size; the conventional "test file" could previously be a committed symlink to any readable file. Ambiguity. A caller or referenced definition matched by a name that several definitions share is labelled "Possible caller/definition (matched by name; N definitions share it)" instead of being presented as a resolved dependency. Store. A corrupt or non-SQLite graph.db is deleted and rebuilt; before, every open failed and, because a failed open is not fatal, every later review ran silently without context. Index transactions are BEGIN IMMEDIATE (a deferred upgrade fails with SQLITE_BUSY_SNAPSHOT under WAL), connections wait up to 10 s for a lock, an up-to-date schema is opened without taking the write lock, and the schema migration re-checks the version under the lock so two first-time openers cannot drop each other's tables. SCHEMA_VERSION 2 rebuilds existing graphs once.
Repository content (diff, surrounding code, ticket text, triage previews) is untrusted input that can contain text written to be read as an instruction. - Each untrusted section is wrapped in <<<BEGIN X>>> / <<<END X>>> markers that grow until the content cannot contain them, so a diff cannot close its own fence and "speak" outside it. The choice is a pure function of the content, keeping prompts and cache keys reproducible. - The system half states that fenced text is never an instruction, that the model must not comply with requests to change the rules, the output format, what is reported, or to reveal other content, and that it reports only on files and lines in the diff. Triage is told that a preview claiming a file is trivial is not evidence that it is. PROMPT_VERSION 5. - A model finding must name a file in the unit that produced it; findings about other files (including ones only present as surrounding context) are dropped and counted as unanchorable. - rule_id and unit_id are cleared on model output: only the engine assigns them, so a model cannot claim a deterministic rule id (DM001) or another unit's provenance. - Model text is stripped of control characters and bidi overrides, capped in length, and capped at 50 findings and 10 notes per unit. This reduces prompt-injection risk; it does not eliminate it. A model can still be persuaded to omit a finding, which is why the deterministic tier is the one to gate on.
A unit whose model output could not be parsed, or that could not fit the
context window, was counted in stats and otherwise ignored: the run printed
"No issues found", exited 0 and wrote a clean report for code the model never
reviewed. Reproduced on v0.9.2 with a stub server answering one of two units in
prose — exit 0, zero findings, even with CI=true.
Engine
- AnalysisStats records each unreviewed unit (UnitSkip: unit id, files,
reason unparseable | too_large | backend_failed, detail) and exposes
units_skipped / units_reviewed / is_complete / completeness().
- A backend failure no longer discards everything gathered so far. The
remaining units are marked backend_failed without calling the backend
again, and the partial review (deterministic findings included) travels in
EngineError::Incomplete, so any caller using `?` still fails as before.
CLI
- Exit 2 when the backend failed — always, as before — and now also when any
unit went unreviewed and completeness is required. Completeness is required
by default when CI is set; `--require-complete` / `--allow-incomplete` and
`[review] require_complete` override, with flags beating the repository's
config so a pull request cannot relax a gate the workflow set.
- The report is written before exiting 2, in-process and via the daemon (whose
protocol now carries the skip record).
- JSON gains `completeness` {status complete|incomplete|failed, units planned/
reviewed/cached/skipped, per-reason counts, files skipped by triage,
deterministic_checks_completed, required, trustworthy, backend_error,
skipped[]}. SARIF sets invocations[0].executionSuccessful and lists skips as
toolExecutionNotifications. Markdown and text lead with a warning, and "No
issues found" is only said of a complete review. Existing fields unchanged.
- `baseline create` warns when built from an incomplete review.
Also in output.rs: model-written text in Markdown (PR comments, job
summaries) is escaped, so an image (fetched on render — an exfiltration
channel), HTML, links and @-mentions produced under planted instructions are
inert; locations use collision-proof code spans.
Tests: engine-level reliability tests with scripted backends (incomplete,
backend failure keeps partial results, fence forging, out-of-unit and
id-spoofing findings, control characters, finding floods, format hijack,
cache invalidation by model/rules/context, broken cache), CLI unit tests for
the exit-code contract, and end-to-end tests over the real binary.
- `--stdin` read the whole of standard input with no limit; it is now capped at the same 64 MB as a git-produced diff, read through take(). - A base branch can come from .diffmind/config.toml, which is part of the repository under review. One starting with `-` reached `git rev-parse` / `git diff` as an option (e.g. `--output=<file>`); it is now refused.
…on: none
Injection. Every `${{ inputs.* }}` inside a `run:` block (and the
github-script comment step) was pasted into the script source before bash or
node parsed it, so an input such as `$(...)` executed, and `args` was
word-split as shell code. Inputs now travel as environment variables, are
validated (model, severities, format, version tag, base ref via
`git check-ref-format --branch`, output path), and reach diffmind as argv
entries. `args` is split with Python's shlex — quotes honoured, nothing
evaluated. The review step moved to scripts/action/review.sh so it can be
tested.
Diff computation. The step ran `git fetch --depth=50 ... || true` then
`git diff origin/<base>...HEAD`. With actions/checkout's default depth 1 a PR
merge commit has no visible parents, so the diff failed ("no merge base"),
diffmind received an empty diff, wrote a clean SARIF report that was then
uploaded, and the job exited with an unexplained 128. The script now fetches
the base, deepens the shallow clone until the merge base is reachable
(50/200/1000, then --unshallow), diffs merge-base..HEAD into a file, and exits
2 with a clear error if any step fails. An empty diff from a successful git
diff is reported as a notice.
Gate. `fail-on: none` passed no --fail-on, so the CLI defaulted the gate to
--min-severity (low) and the job failed on the first finding. `none` now maps
"blocking findings" to a pass, never a failed or incomplete review. Abnormal
exits (134 from panic=abort, 137 OOM) become 2. A `status` output is added,
outputs are written even when the review fails, an unreadable report is
flagged rather than counted as zero findings, and SARIF upload is skipped when
no report exists. PR comments are truncated below GitHub's 65,536-char limit.
Trust. The PR's .diffmind/config.toml is part of the code under review and
could point [backend] at its own server and name any environment variable as
the API key. The action pins `--backend local` unless `args` chooses one, and
passes `--require-complete` (new `allow-incomplete` input to opt out) when the
installed binary supports it.
scripts/action/test-review.sh exercises all of this against real git
repositories (depth-1 PR merge checkout, missing base, unrelated history,
unicode branch, renames/deletions, empty diff, injection and validation
cases) with a stub binary; CI runs it on Linux and macOS. Workflow-level
permissions are now `contents: read`.
The shim's fail() exited 1 — the code the CLI reserves for "the review found blocking issues" — for an unsupported platform, musl, a missing platform package or a spawn failure, and `status === null` also mapped to 1. In CI a broken `npx diffmind` install therefore read as a review verdict. All of these now exit 2, diffmind's "could not run" code; a real exit status from the binary is still passed through unchanged.
Found in independent review of this branch: - fence() grew its tag one `~` at a time while the content still contained it — one full scan per step, so quadratic in content the PR author controls. A diff line of `DIFF` plus 40k tildes cost ~15 s per fence (measured); the 1.5 MB reviewable cap allowed hours, stalling CI and the sequential daemon. The tag is now the bare label when the content does not contain it, and otherwise the label plus a 64-bit content digest: one linear pass, a short tag, and unforgeable (content containing its own digest is a preimage problem). 1.4M tildes fence in well under 2 s. - The fences were text, but the tokenizer is not: Qwen's tokenizer (and most servers' chat templates) split added special tokens such as `<|im_end|>` out of raw text, so repository text could close the user turn and open a system turn of its own. `<|` in all fenced content and in rule-set bodies is rendered as `< |`, which matches no special token.
…diff The bearer token authenticated the client to the daemon, but nothing authenticated the daemon to the client. After a crash daemon.json survives, and another local user listening on that loopback port would receive the token, the full diff, the rule sets and the project path — and could answer "no findings" (found in independent review). Every connection now starts with a challenge the client checks before it sends anything secret: the client sends a 256-bit random nonce; the server answers HMAC-SHA256(token, domain || nonce); only if that verifies (constant time) does the client send the token and request. A failed proof is reported as "failed authentication", and connect() falls back to in-process inference. The hello is capped at 1 KiB inside the existing request deadline, so an unauthenticated peer is turned away earlier than before. Tests: an impostor on the daemon port never receives the token or the diff; proofs are bound to token and nonce; a hand-rolled client that skips the check and guesses a token is still refused by the server.
Pinning the backend was not enough. A pull request could still switch off the gate that reviews it: `[review] ignore = ["**"]` made every hunk "filtered" (exit 0, SARIF executionSuccessful: true, 0 units reviewed — reproduced in independent review), `min_confidence = 1.0` dropped every model finding, and a committed baseline.json suppressed the new ones. On pull requests the action now restores .diffmind/config.toml, rules.toml, rules/ and baseline.json from the merge base before running diffmind (or removes them if the base has none). The PR's edits to those files are still in the diff and still reviewed; they take effect once merged. New input `config-from: base | head` (default base) restores the old behaviour. Also: - `--backend local` is passed only if the installed binary supports it (added in v0.7.1), so pinned older versions do not fail with an unknown argument. - The diff is produced with core.quotepath=false, so non-ASCII paths arrive as UTF-8 rather than git's octal-escaped quoted form. The harness gains 4 cases (40 total): base config governs, head opt-in, invalid config-from rejected, --backend detection.
- analyzer: the "findings must be about the unit" filter used the diff-wide matcher, whose basename fallback let a finding about `src/b/mod.rs` pass for a unit covering `src/a/mod.rs` and then be anchored to b. The filter now requires an exact or path-component suffix match, and surviving findings are anchored against the unit's files only. - graph: a failed read (a Windows sharing violation, say) was hashed as an empty file and recorded with the current mtime and size; with no ctime on Windows the fast path then trusted that empty row until the file next changed. A read failure now leaves the row untouched so the next run retries. - remote: a timeout while reading the body (headers sent, then a stall) was classified as an interrupted connection and retried, costing up to three times --backend-timeout. It is now fatal, like a timeout before the headers. Server error text is redacted before it is truncated, so a key straddling the cut cannot leak as a prefix. - cache: temporaries orphaned by a crashed writer are removed by prune once an hour old. - context: when the working tree is not the reviewed revision's post-image, context is still withheld, but the run now says so once, naming a file — the common case is reviewing committed work with uncommitted edits on top, and a thinner review should not be unexplained. - git: diffs are produced with core.quotepath=false, so non-ASCII paths are UTF-8 rather than octal-escaped quoted strings the parser did not map back to files.
…nd limits CHANGELOG gains an Unreleased v0.9.3 section. README changes are limited to user-facing behaviour that changed: the exit-code table (incomplete reviews), `--require-complete` / `--allow-incomplete` and `require_complete`, the action's shallow-clone handling, base-branch config, backend pinning and permissions, remote backend key/retry/redirect behaviour and the cache's model-identity limits, daemon authentication, and the residual prompt-injection and config-trust limits.
…rdening v0.9.3: security, correctness and reliability hardening
…ut, not 5 s On Windows a connect to a closed loopback port is retried by the OS after the RST (~2 s each), so the three attempts take ~6 s and the 5 s bound failed on windows-latest (CI runs 44902147620, 44902203277). Because cargo stops at the first failing test binary, that also kept every CLI and integration test from running on Windows. The property under test is that a refused connection fails well before the request timeout rather than after MAX_ATTEMPTS x timeout, so the timeout is now 30 s and the bound 15 s: a hang still fails it, Windows' retry does not. Test-only; no behaviour change.
The comment inside the github-script step read "not `${{ }}`". GitHub
evaluates expression syntax anywhere in a `with:` value, comments in the
script included, and an empty expression is a template error, so every
workflow using the action failed before any step ran:
action.yml (Line: 173, Col: 17): An expression was expected
Failed to load .../action.yml
Found by the first real run of the action on GitHub (validation PR #34,
run 44904117395). The 40-case harness exercises review.sh only and never
loads action.yml, so it could not see this.
The comment no longer spells the syntax. The harness gains a check that
every expression in action.yml is a plain `key: value` mapping (YAML `#`
comments allowed), which fails on the previous file at line 175.
read_repo_file accepted any symlink whose target resolved inside the repository root, and .git/ is inside it. A pull request committing `src/app.test.js -> ../.git/config` had that file quoted as "the test file for src/app.js", and actions/checkout persists the job token in .git/config (http.extraheader). Planted text could then ask the model to repeat it into a SARIF annotation or PR comment. A PR-committed graph.db naming .git/config reached the same read through Def::source. Reproduced by the pre-release independent review (prompt captured from a CI-style checkout with the token present in SURROUNDING CODE). Refuse any path whose requested or resolved components include .git, case-insensitively. Tests cover a direct path, a case variant, and a symlink; with the check disabled both new tests fail.
…rdening v0.9.3: fixes from pre-release validation
supports_flag piped `diffmind --help` into `grep -q` under `set -o pipefail`. grep exits at its first match; if diffmind is still writing, its next write hits a closed pipe, it exits non-zero, and pipefail turns "supported" into "not supported". The action then silently dropped `--backend local` (the pin against repository-chosen backends) or `--require-complete`. The action harness reproduced it: 2 of 5 runs failed once the stub printed one more help line. Capture the help text once and search the string.
… review With the input set, review.sh only left out --require-complete. diffmind requires a complete review whenever CI is set, so on GitHub the input did nothing and an incomplete review still exited 2. Pass --allow-incomplete instead, only to a binary that supports it, and leave both flags alone when the workflow chose one in `args`. The harness case asserted only that --require-complete was absent, which passed while the input was a no-op. It now checks the flag that is passed, and adds cases for a flag chosen in args and for an older binary.
… cost "A PR cannot relax the gate that reviews it" holds only when the action knows the base branch, and only for the restored .diffmind/ files. Say so: merge_group and push events use the checkout's own config unless `base` is set, and a linguist-generated or @generated marker still drops a file from review. Add the release note on inference cost: the prompt-injection boundary makes local-model reviews about 10-15 % slower on CPU (232 s -> 259 s for the 1.5B model on a GitHub-hosted Linux runner).
v0.9.3: close the remaining release conditions (allow-incomplete, flag-detection race, docs)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
v0.9.3 is a stabilization release: security, correctness and reliability hardening, with no new review features. The headline is that a review that did not cover the whole diff can no longer pass as a clean one. The full user-facing notes are in
CHANGELOG.mdunder[Unreleased] — v0.9.3.Main changes:
.diffmind/config, and the local backend is pinned.allow-incompleteworks.pipefail..git.--stdindiffs are size-capped, and option-like base branches are refused.Behaviour changes users may notice:
argsare no longer shell-expanded.Versions are still
0.9.2; the version bump and tag are separate release steps.Type of change
Requirements addressed
dev)Testing
cargo test --workspacepasses. Ondev@76c1c32(run 44927800891), and on the PR v0.9.3: close the remaining release conditions (allow-incomplete, flag-detection race, docs) #38 head (run 44927669315): ubuntu 457/457, macOS ARM64 457/457, Windows 450/450. Linux ARM64 and macOS x86_64 passed 455/455 on native runners during pre-release validation.cargo clippy --all-targets -- -D warningspassescargo fmt --checkpassesscripts/action/test-review.sh: 43/43 on ubuntu and macOSdiffmind --branch mainruns without errordiffmind --stdin --format jsonproduces valid JSONChecklist
cargo build)Known limitations (documented)
merge_groupandpush, the checkout's own.diffmind/applies unless thebaseinput is set.linguist-generatedor@generatedmarker still drops a file from review, including its deterministic checks.After release: re-run the action once with
version: v0.9.3to confirm it installs the published binary.