Skip to content

Commit 6088b4e

Browse files
authored
fix(verify): 0.4.6 security — withhold SAFE for untrusted diffs + forgery/leak hardening (#161)
Trust-mode gate (ADR-19), coverage-driver isolation (ADR-17), excluded-statement floor (ADR-18), value-aware credential redaction (ADR-20). Closes the in-process coverage forge and A1/A2/B advisories. Breaking default: untrusted coverage-SAFE now UNPROVEN (--trusted to restore).
1 parent 049b161 commit 6088b4e

39 files changed

Lines changed: 2016 additions & 194 deletions

‎CHANGELOG.md‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,51 @@ Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
---
99

10-
## [Unreleased]
10+
## [0.4.6] - 2026-09-07
11+
12+
### Security - a coverage-based `SAFE` on an untrusted diff was forgeable (BREAKING DEFAULT)
13+
14+
Refactron measured coverage and the pass/fail gates by running the diff's OWN
15+
test suite in the same process as the measurement, so a hostile diff controlled
16+
the evidence. A ~6-line `conftest.py` (public coverage API,
17+
`Coverage.current().get_data().add_arcs`) marked a never-executed changed line as
18+
covered and earned a false `SAFE` for an untested change. Reproduced end-to-end;
19+
present in 0.3.1-0.4.5. A false `SAFE` is the one defect this tool exists to
20+
prevent, so the fix changes a default.
21+
22+
**A would-be-`SAFE` is now WITHHELD to `UNPROVEN` for an UNTRUSTED diff, which is
23+
the default.** No launcher can stop in-process tampering (the attacker owns the
24+
process), so Refactron stops trusting the forgeable measurement rather than trying
25+
to detect the forgery. Trust is asserted by the operator, never inferred from the
26+
diff:
27+
28+
- CLI: pass `--trusted` for a diff whose author you trust (self/dev use).
29+
- MCP / library: `trusted: true` (default `false`).
30+
31+
`UNSAFE` is unchanged. Every report now carries `trustMode: 'trusted' |
32+
'untrusted'`, and a withheld verdict's `reason` begins "SAFE is withheld", so a
33+
consumer can tell a trust withhold from a real coverage gap. A trust-grade `SAFE`
34+
over an untrusted diff will require a hermetic (out-of-process) run. (ADR-19)
35+
36+
**Upgrade note.** If you rely on a coverage-based `SAFE` for diffs you author
37+
yourself, add `--trusted` (or `trusted: true`) to keep it. If you verify untrusted
38+
PRs in CI, the default is now the correct one: those verdicts degrade to
39+
`UNPROVEN` instead of a forgeable `SAFE`. Exit codes are unchanged (`UNPROVEN` and
40+
`SAFE` both exit 0).
41+
42+
Also hardened:
43+
44+
- Coverage-driver isolation — a repo-root `coverage.py` can no longer shadow the
45+
driver (ADR-17). Defense-in-depth for the trusted path.
46+
- Excluded-statement floor — a changed statement the diff excludes from coverage
47+
(`# pragma: no cover`, a coverage config) now floors the verdict instead of
48+
being subtracted (ADR-18). Trusted-path defense.
49+
- Credential redaction to the verified suite is strengthened from a name denylist
50+
to segment-name plus value-shape matching — token prefixes, `user:pass@`
51+
connection strings, PEM blocks, high-entropy blobs — closing
52+
GHSA-7gr9-rqqx-xg6m. `REFACTRON_FORWARD_ENV` re-admits a var an operator knows is
53+
a non-secret; redaction stays best-effort, not a sandbox (ADR-20).
54+
1155

1256
### Added — `--flaky-check`, an opt-in stability check
1357

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,14 @@ The CLI is then `node dist/cli/index.js <command>` and the MCP server is `node d
5959

6060
| Verdict | Meaning | Exit |
6161
| ---------- | ---------------------------------------------------------------------------------------------------- | ---- |
62-
| `SAFE` | Every gate passed **and** your tests exercised every coverable changed statement. | `0` |
62+
| `SAFE` | Every gate passed, your tests exercised every changed statement (none excluded), and the diff's author is trusted. | `0` |
6363
| `UNSAFE` | A gate failed: the change broke something. | `1` |
6464
| `UNPROVEN` | Tests pass, but the changed code isn't exercised (or coverage couldn't be assessed). | `0` |
6565

6666
`UNPROVEN` is the honest verdict. "Tests pass" is not "proven safe": if nothing runs the lines you changed, a green suite proves nothing about them. Refactron says so, and (for Python) names the line to add a test for.
6767

68+
By default the diff's author is **untrusted**, so a would-be-`SAFE` is withheld and returns `UNPROVEN`: coverage is measured by running the diff's own suite in-process, which an untrusted diff can forge. Pass `--trusted` (CLI) or `trusted: true` (MCP) only for a change whose author you already trust, never for an external or agent-authored diff.
69+
6870
Coverage is **Python-only** (via `coverage.py`), so a TypeScript or mixed-language diff can never earn `SAFE` today; it returns `UNPROVEN` ("coverage of the changed code could not be determined"). The gates still run; only the coverage half is Python-only.
6971

7072
---

‎SECURITY.md‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ belongs to the repository being verified. Both are treated as untrusted.
6161
- **Diff intake.** A path taken from a diff's `---`/`+++` headers is refused
6262
before it is read if it resolves outside the repository.
6363
- **Your credentials.** The test suite Refactron runs does not inherit them.
64-
`REFACTRON_TOKEN`, CI tokens, cloud keys, and any variable whose name ends in
65-
`_TOKEN`, `_SECRET`, `_API_KEY`, `_PASSWORD` or `_CREDENTIALS` are removed from
66-
the environment handed to every spawn that executes the suite.
64+
Every variable handed to a spawn that executes the suite is stripped if its name
65+
carries a credential word (`TOKEN`, `SECRET`, `KEY`, `PASSWORD`, `COOKIE`,
66+
`SESSION`, `AUTH`, `CERT`, …, matched per underscore-segment so `MY_TOKENIZER_PATH`
67+
survives) OR its value looks like a credential — a known token prefix (`sk_`,
68+
`ghp_`, `AKIA…`), a `user:pass@` connection string, a `-----BEGIN` block, or a
69+
high-entropy blob. Value shape is the axis an attacker cannot rename around
70+
(ADR-20). `REFACTRON_FORWARD_ENV` re-admits a var an operator knows is a non-secret.
6771
- **Verdict integrity.** A false `SAFE` is the only unforgivable defect in this
6872
product. Every degradation path — a missing sidecar, an unmeasurable coverage
6973
run, a test command we cannot parse, a flaky heal — resolves to `UNPROVEN`,
@@ -79,6 +83,13 @@ guarantee.
7983
`pytest` on the same repository yourself. A test that writes to an absolute
8084
path, opens a socket, or spawns a process will do so. Isolation means the
8185
shadow tree is a genuine copy, not that the suite is confined to it.
86+
87+
- **Credential redaction is best-effort, not a sandbox.** We strip variables whose
88+
name or value looks like a credential (above), which closes the common shapes and
89+
every vector in GHSA-7gr9-rqqx-xg6m — but a secret that is BOTH benignly named and
90+
benign-valued (say `DEPLOY_PIN=8675`) is undetectable. Do not run untrusted
91+
verification in an environment scoped to hold production secrets it does not need;
92+
the durable control is not putting them there, not the redaction.
8293
- **We do not sandbox the Python sidecars.** They parse source with the standard
8394
library and LibCST; they do not execute it.
8495
- **The MCP server applies no authentication.** For a stdio transport the trust

‎dev-docs/decisions/11-safe-coverage-rule.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
# ADR-11: SAFE requires every coverable changed statement to have executed
22

3-
> Status: **Accepted**
3+
> Status: **Accepted** (superseded in part by [ADR-18](18-excluded-changed-statement-floors.md))
44
> Date: 2026-08-17
55
> Deciders: @omsherikar
6+
>
7+
> **Superseded in part (2026-09-06, ADR-18, GHSA-9xch-4mch-222g):** the
8+
> "coverable = statements − excluded" subtraction below is attacker-controllable
9+
> (a diff can add `# pragma: no cover` / a coveragerc regex to a changed
10+
> statement). ADR-18 removes the subtraction: an excluded CHANGED statement now
11+
> floors to UNPROVEN. The per-statement, per-file rule this ADR established stands;
12+
> only the treatment of excluded changed statements changed.
613
714
## Context
815

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# ADR-17: Isolate the coverage driver from module shadowing
2+
3+
> Status: **Accepted**
4+
> Date: 2026-09-06
5+
> Deciders: @omsherikar
6+
> Closes: GHSA-739m-x9gc-9wjv (private advisory).
7+
8+
## Context
9+
10+
`reportCoverage` invoked the coverage driver as `python3 -m coverage run|json …`
11+
with `cwd = the shadow tree`. For `python -m`, CPython puts cwd first on
12+
`sys.path`, so a **`coverage.py` file committed at the repo root** shadows the
13+
real tool. A hostile PR ships one that fabricates `coverage.json` marking every
14+
changed line executed → the changed-line coverage rule (ADR-11) is satisfied on
15+
fabricated evidence and the verdict is a clean, undisclosed **false SAFE**,
16+
reachable by any PR with no machine access. Reproduced end-to-end through the real
17+
MCP server across 0.4.0–0.4.5.
18+
19+
The constraint that makes this non-trivial: the coverage run must stay
20+
**observationally equivalent** to the tests-gate suite run (the governing rule at
21+
the top of `python-line-coverage.ts` — two prior false SAFEs came from the two
22+
runs diverging). So the fix must isolate the **driver** (the `import coverage`)
23+
without changing what the **suite** sees on `sys.path`.
24+
25+
## The trap (why the obvious fix is wrong)
26+
27+
Launching the driver by absolute package path (`python <site-packages>/coverage
28+
run …`) sets `sys.path[0]` to the coverage dir and looked sufficient. It is **not**:
29+
measured empirically, it still forges under `PYTHONPATH=.` — the *documented*
30+
shadow-bypass remedy. `import coverage` from the package-dir launch does not
31+
resolve at `sys.path[0]` (the coverage package's own dir holds no top-level
32+
`coverage`), so it falls through to `PYTHONPATH` **before** site-packages, and a
33+
repo-local `coverage.py` on `PYTHONPATH=.` (= the shadow cwd) is imported. This is
34+
exactly the "the fix for one false SAFE introduces another" failure this module
35+
keeps relearning — caught here before shipping.
36+
37+
## Decision
38+
39+
**Launch the coverage CLI from a `-c` program that loads coverage from the real
40+
site-packages FIRST, then restores the suite's `sys.path`:**
41+
42+
```python
43+
import sys
44+
sys.path.insert(0, <resolved site-packages>) # ahead of cwd AND PYTHONPATH
45+
import coverage.cmdline as C
46+
del sys.path[0] # restore: the suite runs as the gate ran it
47+
sys.exit(C.main())
48+
```
49+
50+
- **Resolve** the site-packages dir with `<runner> -c "import coverage, os;
51+
print(os.path.dirname(os.path.dirname(coverage.__file__)))"` run from a
52+
**freshly-created empty temp dir** (neutral cwd) with the **base env only —
53+
never the testCmd's `PYTHONPATH`**. Both properties matter: a neutral cwd
54+
defeats cwd-shadowing; dropping the attacker-hoisted `PYTHONPATH` defeats
55+
path-shadowing of the resolve itself.
56+
- **Insert / import / delete.** Inserting site-packages at `sys.path[0]` makes the
57+
driver's `import coverage` resolve the real tool ahead of cwd and `PYTHONPATH`.
58+
Deleting the inserted entry before `C.main()` runs the suite means the suite
59+
sees the exact `sys.path` the gate gave it. Verified: the suite's `sys.path[0]`
60+
is byte-identical to the gate's under `PYTHONPATH=.`, so the package-under-test
61+
still imports from the shadow.
62+
- **Never fall back to `-m coverage`.** If resolution fails (coverage not
63+
importable for the interpreter, or a namespace `coverage/` dir with
64+
`__file__ = None`), the run the gate performed cannot be measured, so decline
65+
(`coverageToolFound: false` → UNPROVEN). This is the load-bearing invariant, the
66+
single line most likely to be "simplified" back into the hole.
67+
68+
`shadow-tree.ts` is untouched: the repo-local `coverage.py` stays in the shadow
69+
(the gate's suite legitimately sees it); it is only denied to the **driver**.
70+
71+
## Alternatives considered
72+
73+
- **Absolute-path package launch alone.** Rejected: forges under `PYTHONPATH=.`
74+
(above).
75+
- **`-P` / `PYTHONSAFEPATH=1`.** Rejected: Python 3.11+ only; the repo supports
76+
3.8+. The `-c` insert/import/delete is universal.
77+
- **Denylist a repo-local `coverage.py` / `sitecustomize.py` in the shadow.**
78+
Rejected: a denylist against a whitelist problem — `coverage.py` is not the only
79+
shadowing name, and it would diverge the suite from the gate. The launcher
80+
immunizes the driver's import against all cwd/`PYTHONPATH` shadowing at once.
81+
82+
## Consequences
83+
84+
- **Positive.** Closes GHSA-739m-x9gc-9wjv, including under `PYTHONPATH=.`.
85+
Fail-safe by construction: the only verdict move is toward UNPROVEN.
86+
87+
Correction (2026-09-07): an earlier version of this bullet claimed the fix also
88+
closed a repo-root `sitecustomize.py` driver-startup vector "because the driver's
89+
neutral cwd never imports it." That was WRONG — only the site-packages RESOLVE
90+
runs from a neutral cwd; the DRIVER runs from the shadow tree, so `site` imports
91+
a shadow `sitecustomize.py` at startup exactly as before. The launcher does NOT
92+
close the `sitecustomize` sys.modules substitution (F1), and no in-process
93+
launcher can (attempts with `-S` and with a `sys.modules` purge both failed;
94+
see ADR-19). That vector and the general in-process forgery family are mitigated
95+
by the trust-mode gate (ADR-19), which withholds SAFE for an untrusted diff.
96+
- **Negative, fail-safe.** A repo whose coverage is importable ONLY via the
97+
testCmd's `PYTHONPATH` (not installed in the interpreter) now declines to
98+
UNPROVEN. A repo that vendors a root `coverage.py` without pip-installing
99+
coverage declines (indistinguishable from the attack, correctly refused). Both
100+
are rare and move only toward UNPROVEN.
101+
- **Out of scope, filed separately.** The suite runs *in the same process* as
102+
coverage's collector, so a malicious test can still tamper with the data file /
103+
tracer in-process, and a `[tool.coverage] plugins = evil` entry makes the driver
104+
import an attacker plugin. A1's fix does not touch these; they are their own
105+
findings/advisories.
106+
107+
## Compliance
108+
109+
- Red-first: `tests/integration/coverage-driver-shadow.test.ts` — a repo-root
110+
`coverage.py` fabricating coverage returns SAFE on the pre-fix tree and UNPROVEN
111+
after, **and** a second case pins the `PYTHONPATH=.` regression so the abs-path
112+
form cannot be reintroduced.
113+
- Equivalence preserved: `tests/integration/coverage-reporter.test.ts` (30 cases,
114+
including the shebang-interpreter and json-failure paths) stays green.
115+
- Isolation at the redaction site: `tests/unit/verify/runner-env-redaction.test.ts`
116+
— a planted repo-root `coverage.py` is now never executed by any coverage spawn.
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# ADR-18: An excluded changed statement floors SAFE
2+
3+
> Status: **Accepted**
4+
> Date: 2026-09-06
5+
> Deciders: @omsherikar
6+
> Closes: GHSA-9xch-4mch-222g (private advisory). Supersedes in part [ADR-11](11-safe-coverage-rule.md).
7+
8+
## Context
9+
10+
ADR-11 defined the SAFE coverage rule in terms of **coverable** statements:
11+
`coverable = changedStatements − excludedStatements`, and required every coverable
12+
changed statement to have executed. Excluded statements (`# pragma: no cover`,
13+
`if TYPE_CHECKING:`, coverage config `exclude_lines`) were **subtracted** from the
14+
requirement, on the theory that no test can execute them, so counting them would
15+
make SAFE unreachable for a diff that merely adds a typing-only import block.
16+
17+
That theory assumes a good-faith author. The verify engine's inputs are hostile by
18+
design: the diff under verification is untrusted, and so is every file it carries,
19+
**including the coverage configuration and any pragma**. So the exclusion set is
20+
attacker-controlled.
21+
22+
**The hole, reproduced (GHSA-9xch-4mch-222g).** A diff adds a backdoor and marks
23+
it excluded:
24+
25+
```python
26+
result = amount + 1
27+
if amount == 1337: # pragma: no cover
28+
return -999999.0
29+
return result
30+
```
31+
32+
`fee(100)` is the only test; it exercises `result` and `return result` but never
33+
the pragma'd branch. The `# pragma: no cover` subtracts the two malicious
34+
statements from the requirement, so the file reads `covered === coverable` and the
35+
verdict is `SAFE` over a live `return -999999.0` — a false SAFE, the one
36+
unforgivable defect. The only disclosure is a `uncovered[].excluded: true` entry
37+
that reads as benign. Inline pragma, `.coveragerc`, and `pyproject
38+
[tool.coverage] exclude_lines` all reach it; all are attacker-authored.
39+
40+
## Decision
41+
42+
**Stop subtracting excluded statements. An excluded CHANGED statement floors the
43+
file to UNPROVEN.** A file is proven iff it has at least one changed statement and
44+
**every** changed statement executed:
45+
46+
```ts
47+
if (acc.statements === 0 || acc.covered < acc.statements) allFilesProven = false;
48+
```
49+
50+
coverage.py never lists an excluded line in `executed_lines`, so an excluded
51+
changed statement can never be counted covered, and `covered < statements` whenever
52+
one exists. The `statements === 0` arm preserves ADR-11's guard that keeps
53+
removal-only and inert-only files UNPROVEN.
54+
55+
An excluded changed statement is not evidence of anything — the author chose to
56+
exclude it. `UNPROVEN` ("we could not prove this changed statement is exercised")
57+
is the true verdict; `SAFE` would be the lie.
58+
59+
**Disclosure.** `CoverageAttribution`/`CoverageAssessment` gain an additive
60+
`excludedChangedStatements` count, and the UNPROVEN reason gains a distinct,
61+
stable substring for the exclusion-floor case whose remedy is **not** "add a test"
62+
(no test can execute an excluded line): it says the changed statement is excluded
63+
from coverage and, for an untrusted diff, cannot be proven — remove the exclusion
64+
or verify it another way.
65+
66+
## Alternatives considered
67+
68+
### F2 — floor only when the exclusion was introduced by the diff
69+
Rejected on **soundness**, not ergonomics. Two independent fatal flaws:
70+
- **It needs data coverage.py does not emit.** Coverage's JSON gives a flat
71+
`excluded_lines` list with no attribution to the marker/config that triggered
72+
each exclusion. You cannot tell a `# pragma` from a `.coveragerc` regex from
73+
`if TYPE_CHECKING:`. (Same lesson as ADR-17: do not build a rule on a
74+
distinction the measurement cannot make.)
75+
- **It has a known false-SAFE bypass.** Config-driven exclusion
76+
(`[tool.coverage] exclude_lines = .*# x`) puts **no marker on a changed line** —
77+
the attacker annotates the malicious statement with an innocuous comment and adds
78+
the regex in `pyproject`. F2's "only floor if the marker is on a changed line"
79+
waves it straight through to SAFE. A fix with a known false-SAFE bypass is not a
80+
fix.
81+
82+
### A "trust my own exclusions" mode
83+
Rejected. It is a feature flag for a hypothetical non-adversarial user, and it
84+
reopens the exact hole. Not added.
85+
86+
### A spoof-proof `if TYPE_CHECKING:` carve-out
87+
`TYPE_CHECKING` blocks are dead at runtime, so they cannot carry a behavioral
88+
backdoor — a tempting carve-out. Deferred: coverage's JSON can't distinguish
89+
`TYPE_CHECKING` from a pragma, and the name itself is spoofable (an attacker binds
90+
`TYPE_CHECKING` to a truthy value), so a sound carve-out needs new AST machinery
91+
with its own threat model — a separate signal, not a security patch. Left to a
92+
future ADR if DX data justifies it.
93+
94+
## Consequences
95+
96+
- **Positive.** Closes GHSA-9xch-4mch-222g. A diff-controlled exclusion can no
97+
longer clear a changed statement. Fail-safe by construction: the only verdict
98+
move is `SAFE` → `UNPROVEN`.
99+
- **Negative, and fail-safe.** These legit diffs move from `SAFE` to `UNPROVEN`
100+
(both exit 0 — not a CI failure):
101+
- a diff adding `# pragma: no cover` to a changed statement (a defensive
102+
unreachable branch, `if __name__ == "__main__":`);
103+
- a diff whose changes touch a file's `if TYPE_CHECKING:` block (typing-only
104+
imports) — note it drops the **whole file** to UNPROVEN;
105+
- a diff whose changed statement matches a project `.coveragerc` /
106+
`pyproject` `exclude_lines`/`exclude_also` regex (`def __repr__`, `@overload`).
107+
The advisory states this plainly: in the verify-untrusted-PR deployment,
108+
exclusions are not trusted; a diff relying on them earns UNPROVEN by design.
109+
- **Neutral.** `src/contracts.ts` untouched; `reportVersion` unchanged
110+
(`excludedChangedStatements` is additive).
111+
112+
## Compliance
113+
114+
- Red-first: `tests/integration/coverage-exclusion-forgery.test.ts` — the pragma'd
115+
backdoor returns `SAFE` on the pre-fix tree and `UNPROVEN` after, and an honest
116+
fully-covered change with no exclusions still reaches `SAFE`.
117+
- Unit: `tests/unit/verify/coverage-attribution.test.ts` — an excluded changed
118+
statement floors the file even when every other changed statement is covered.
119+
- Never strengthens: the rule only ever removes SAFE; it cannot create one.

0 commit comments

Comments
 (0)