diff --git a/changelog.d/845.md b/changelog.d/845.md new file mode 100644 index 0000000000..26b880e8ea --- /dev/null +++ b/changelog.d/845.md @@ -0,0 +1,21 @@ +### Changed +- **A Mitigated Finding Is Not a Verified One (`devops review path|branch|pr`, `devops review verify`, `devops_cli.ai.review.verdicts`)**: + - A MITIGATED verdict, a model's or a person's, sets `verified=False`, and so does the merge of two findings whose best verdict is MITIGATED. MITIGATED defaulted to verified, so 11 of the 28 mitigations in review session `20261001-224227` counted as verified defects (#845). +- **The Verifier Is Told What a Mitigation Needs (`devops review path|branch|pr`, `ai/tasks/verify_finding_system.md`)**: + - The verifier's instructions say a perimeter file is a repository-relative path to code or configuration in the reviewed tree, never documentation such as the project's conventions, that the mechanism names an identifier in backticks which a perimeter file or the finding's file holds, and that a mechanism describing the defect is no mitigation. The prompt digest changes, so cached verifier replies are not replayed (#845). + +### Fixed +- **A Mitigation Stands Only on Code the Reviewed Tree Holds (`devops review path|branch|pr`, `devops_cli.ai.review.verification`)**: + - A model's MITIGATED verdict stays MITIGATED only when every perimeter file resolves inside the reviewed tree through `safe_resolve_subpath`, and an identifier its mechanism names (`_extract_code_symbols`) appears in a perimeter file or in the finding's own file. An absolute path, even to a file in the tree, a `../` escape, a symlink, a directory and a missing file are unresolved, and a pull request review's tree holds only the pull request's files. Otherwise the finding is UNVERIFIED, stays reported, drops the line the verdict cited, and its `verification_note` names the check that failed. The finding's own file is read where its location points, absolute as a scanner writes it or relative, so a mechanism held only there still counts. A HIGH "Command injection via os.system" finding that the verifier called mitigated by a "shlex.quote wrapper in safe_exec" in `src/does/not/exist.py`, citing line 999 of a four-line file, was MITIGATED with no note and the review recommended APPROVE; it is now UNVERIFIED with a `mitigation-unproven` note saying that `src/does/not/exist.py` does not resolve inside the reviewed tree, and the review requests changes (#845). + - A documentation file, the conventions file `.devops/review.md` among them, is no perimeter, and a mechanism that negates itself ("caught but not logged", "does not fully sanitize", "is expected to handle", "intended to", "too permissive") describes the defect rather than what limits it. Replayed against session `20261001-224227`'s 28 MITIGATED verdicts, 26 become UNVERIFIED: 19 mechanisms name no code identifier, 5 describe the defect and 2 perimeters are `.devops/review.md`. The 2 naming `validate_service_url` and `is_relative_to()` in the files that hold them stay MITIGATED (#845). + - A verdict that names no reason, mechanism or perimeter files says which, under the same note kind (#845). +- **A Confirmation Cites a Line Its File Has (`devops review path|branch|pr`, `devops_cli.ai.review.verification`)**: + - A model's VERIFIED verdict whose `citation_line` is below 1 or past the end of the finding's file is UNVERIFIED, stays reported and drops the citation, with a `citation-out-of-range` note naming the line, the file and its length. A citation inside the file stays VERIFIED. A scanner's finding, located by an absolute path inside the reviewed tree, is checked the same way. Each verdict of a reply is checked on its own: a fabricated one leaves the others as they were (#845). +- **A Confirmation or Mitigation Its Own Reason Contradicts Is Not Applied (`devops review path|branch|pr`, `devops_cli.ai.review.verification`)**: + - A model's VERIFIED or MITIGATED verdict whose reason denies the finding's claim is UNVERIFIED, stays reported and drops its citation, with a `verifier-contradiction` note quoting the denial. In review session `20261003-012555` qwen3-coder confirmed two Semgrep findings, "Untrusted user input in `importlib.import_module()`", with reasons ending "No user input reaches this point" and "These are not derived from untrusted user input", and #948's ranking put both among the report's top 8 rows; in session `20261003-005122` it called two of the same findings mitigated on the same grounds. The guard mirrors the self-refutation guard on the same claim words and negations: a negation followed by at least two consecutive words of the claim that the claim does not negate itself (#845). + - A confirmation whose reason supports the claim is still applied, also when it negates a guard ("this does not prevent path traversal") or a word the claim negates too ("no input validation" against "Missing input validation"). Over 778 cached VERIFIED and MITIGATED verdicts, the plain mirror (any negation and 60% of the claim's words) would have set aside 318; this guard sets aside 13, 12 of which argue their finding away (#845). + - A verdict whose reason says a criterion passed ("verified by the test execution which passes") when every recorded run of a criterion failed gets the same note. Session `20261003-005122` confirmed a finding that way while its criterion had failed with `No module named 'pytest'` (#845). +- **The Profile Counts Mitigations That Proved Nothing (`devops review path|branch|pr`, `devops_cli.ai.review_schema`)**: + - `verdict_distributions.verification_note` in `profile.json` counts `mitigation-unproven`, `citation-out-of-range` and `verifier-contradiction` notes as their own kinds. A mitigation degraded for want of a mechanism or perimeter was noted in free text and counted as `other` (#845). +- **A Perimeter Path Matches Only Itself (`devops review branch|pr`, `devops pr check-readiness`, `devops_cli.ai.review.mitigations`)**: + - The perimeter-change warning stripped paths with `.lstrip("./")`, which cut the dot off `.github/...` and `.devops/...` and the root off an absolute path, so a change to `github/workflows/ci.yml` warned about a mitigation whose perimeter is `.github/workflows/ci.yml`, and `etc/hostname` matched `/etc/hostname`. It now strips a leading `./` only. An absolute path inside the repository is read relative to its root, so a person's mitigation of a scanner finding, whose perimeter is the finding's absolute path, still warns when that file changes; an absolute path outside the repository matches only itself (#845). diff --git a/docs/agent/tasks/task-845-mitigation-and-confirmation-verdicts-point-at-evidence.md b/docs/agent/tasks/task-845-mitigation-and-confirmation-verdicts-point-at-evidence.md new file mode 100644 index 0000000000..dd233628a9 --- /dev/null +++ b/docs/agent/tasks/task-845-mitigation-and-confirmation-verdicts-point-at-evidence.md @@ -0,0 +1,59 @@ +# Task: Mitigation and Confirmation Verdicts Must Point at Evidence That Exists (#845) + +**Issue**: [#845](https://github.com/dan-petty/devops-cli/issues/845) +**Status**: Done +**Milestone**: v0.2.25 +**Priority**: priority/p1-high +**Scope**: scope/review + +## Description +Only INVALIDATED verdicts were checked against evidence. A model's MITIGATED verdict needed a mechanism and a perimeter to be named, never to exist, and `derive_recommendation` leaves MITIGATED findings out. Through `_apply_single_finding_verification`, a HIGH "Command injection via os.system" finding with the mechanism "shlex.quote wrapper in safe_exec", the perimeter `src/does/not/exist.py` and line 999 of a four-line file cited came out MITIGATED with `verified_by=llm`, no note and APPROVE, and a model VERIFIED verdict citing line 999 also passed. In review session `20261001-224227` all 28 MITIGATED findings were reported and counted as defects: 18 mechanisms name no code identifier, 5 describe the defect itself, 2 perimeters are `.devops/review.md`, and 11 carry `verified=True` because `_build_verdict_updates` made MITIGATED verified. `mitigations._normalize_path` used `.lstrip("./")`, which cut the dot off `.github/...` and `.devops/...` and the root off an absolute path. + +The scope added on 2026-10-03 from review sessions `20261003-005122` (S7) and `20261003-012555` (S8) (`.data/review-evaluation-20261003-s7-s8.md`, D8): a confirmation or mitigation whose own reason refutes the claim was applied as given. In S8 qwen3-coder returned VERIFIED on `workspace.py:43` and `main.py:84` with reasons saying no untrusted input reaches the import (cache `llm_6818ef36`, `llm_f3d7fc26`), and #948's ranking put both among the report's top 8 rows. In S7 it returned 3 MITIGATED verdicts whose reasons argue the defect away (`llm_3ec3580c`, `llm_54a55488`, `llm_952922a2`) and a VERIFIED one (`llm_4617de34`) whose reason says "the test execution passes" while that criterion had failed with `No module named 'pytest'`. Replayed on this branch before the fix, `llm_6818ef36` gave `('VERIFIED', 'llm', None, True)`. + +What the merged v0.2.25 items left: #846 made `_extract_citation_line` read explicit citation keys only, added the note kinds `compute_verdict_distributions` counts (`CONST_VERIFICATION_NOTE_KINDS`) and the `VERDICT_FIELDS` copy-back, which carries `verified` back onto the saved finding. #948 lists MITIGATED findings apart in the summary. #949 and #950 record a person's MITIGATED verdict in the ledger. None of them checked a mitigation's perimeter or mechanism, a confirmation's citation, or a confirmation's or mitigation's reason against the claim; #846's self-refutation guard (`_without_self_refutation`) checks only the reverse, an invalidation whose reason confirms. #790's placeholder set has not landed, so the existing `_is_placeholder` and `_NO_VALUES` stay. #789 (multi-page recompose drops UNVERIFIED findings) is open and untouched. #1021 and #1018 (refutation guards, removed-symbol refutations) are not part of this change. + +## Key Changes +- **Mitigations** (`ai/review/verification.py`). `_unproven_mitigation_note` runs on every model MITIGATED verdict: `_mitigation_presence_gap` (reason, mechanism and perimeter named; it replaces `_determine_mitigated_degradation_note`), then `_mitigation_evidence_gap`. A mechanism matching `CONST_SELF_NEGATING_MECHANISM_PATTERN` (`but (does )?not|is expected to|intended to|too permissive`, `config/constants.py`) describes the defect. `_perimeter_gap` resolves each perimeter file with `_perimeter_file`: an absolute path is refused outright, and a relative one goes through `_file_in_reviewed_tree`, that is `safe_resolve_subpath(root, path, must_exist=True)` for the review's target and its repository (`_reviewed_tree_roots`; a pull request's head, written outside any repository, has only its own files), so a `../` escape, a symlink, a directory or a missing file is unresolved. A perimeter `classify_file_context` reads as documentation (`CONST_DOC_EXTENSIONS`, `CONST_DOC_FILENAMES`, documentation MIME types) is no perimeter. Then `_extract_code_symbols(mechanism)` must name an identifier that a perimeter file or the finding's own file holds as a whole word, read with the 50 MB cap (`DEFAULT_MAX_AST_FILE_SIZE_BYTES`). The finding's own file goes through `_file_in_reviewed_tree` directly, so a scanner's absolute location inside the tree is read (`safe_resolve_subpath` accepts an absolute path inside its base and refuses one outside). A failed check makes the verdict UNVERIFIED and reportable, without the line it cited, with the note `mitigation-unproven: ` (`CONST_MITIGATION_UNPROVEN`), which names the perimeter path or the identifiers. A verdict that claims a mitigation and is left UNVERIFIED for want of a part it never named gets the same kind. +- **Confirmations**. `_citation_outside_file` downgrades a model VERIFIED verdict whose `citation_line` is below 1, or past the end of the finding's file in the reviewed tree, to UNVERIFIED with `citation-out-of-range: line of ( lines)` (`CONST_CITATION_OUT_OF_RANGE`) and drops the citation. The finding's file is read where its location points, absolute or relative. A verdict without a citation, or whose file is not in the tree, is left as it was. +- **Contradictions** (`ai/review/verification.py`). `_contradiction_note` runs first on every model VERIFIED and MITIGATED verdict. `_denial_of_the_claim` mirrors `_reason_confirms` on the same claim words (`_claim_words` of the verification criteria and the title) and the same `_NEGATION`, but reads where the negation points: a negation (not "without", which names a missing guard as a confirmation does, nor "already") followed, past fillers ("the", "any", "actual") and bridges ("derived from", "controlled by"), by at least two consecutive claim words that the claim does not negate itself (`_negated_in_claim`: up to five words after "no", "not", "missing" or "lacks", three before "missing" or "disabled"). `_claims_a_failed_criterion_passed` matches `CONST_CRITERION_PASSED_CLAIM_PATTERN` (a test, command, criterion or check that "passes" or "succeeds" with nothing after it, or exit status 0) when the finding has executable criteria runs and none passed. Either makes the verdict UNVERIFIED and reportable, without its citation, with `verifier-contradiction: the verdict's reason denies the claim ('')` or `... says a criterion passed (''), but its recorded run failed` (`CONST_VERIFIER_CONTRADICTION`). The plain mirror (any negation and 60% of the claim's words) was measured first and rejected: over 778 VERIFIED and MITIGATED verdicts in 529 cached verifier replies (`.data/cache/llm`, the claim read from the title each reply repeats) it set aside 318, mostly confirmations that negate a guard ("does not prevent path traversal", "without a default value"). This guard sets aside 13 of the 778; 12 argue their finding away ("no user input", "not derived from untrusted user input", "no hardcoded secret", "no ambiguous command reference"), and the 13th quotes a convention ("not overly complex") in a reason that also says the finding "cannot be fully verified". +- **Structure**. `_resolve_status_and_verification_note` dispatches to `_resolve_refutation` (the unchanged INVALIDATED path), the contradiction check, the mitigation note and the citation check, and `_mitigation_fields` passes the mechanism, perimeter and regression test only for MITIGATED; `_build_finding_verdict_kwargs` is gone. Both functions are back under the complexity cap (12 each before, by `devops scan complexity`). Each verdict is still resolved on its own in `_apply_bound_verdicts_to_findings`. +- **The flag** (`ai/review/verdicts.py`, `ai/review_schema.py`). `_build_verdict_updates` writes MITIGATED with `verified=False`, for every adjudicator, and `_merge_two_findings` does the same when the best status is MITIGATED. +- **Distributions**. `mitigation-unproven`, `citation-out-of-range` and `verifier-contradiction` join `CONST_VERIFICATION_NOTE_KINDS`, so `compute_verdict_distributions` counts them in `profile.json`'s `verdict_distributions.verification_note`. +- **Perimeter matching** (`ai/review/mitigations.py`). `_normalize_path` strips a leading `./` only and reads an absolute path inside the repository relative to its root; `find_perimeter_changes` takes that root as `repo_root`, the current repository's (`find_repo_root()`) by default, as `devops pr check-readiness` and branch and pull request reviews call it. A person's MITIGATED verdict on a scanner finding records the finding's absolute location as its perimeter (`record_mitigated_finding`), so without this the warning never fired for it. `_is_path_matching` matches an absolute path, now one outside the repository, only to itself; two relative paths still match when one ends in the other. +- **Prompt and docs**. `ai/tasks/verify_finding_system.md` tells the verifier a perimeter is a repository-relative path to code or configuration, not documentation, that the mechanism names an identifier in backticks which a perimeter file or the finding's file holds, and that a mechanism describing the defect is no mitigation. The review knowledge base (`ai/knowledge_base/devops_cli/tasks/ai_code_review.md`) describes the rules, the contradiction check included. The verifier prompt does not mention the contradiction check. +- **Tests**. `tests/test_verdict_writers.py` holds the new tests. `tests/golden/review_findings.json` gains `app/shell.py`, the real defect `shell-injection`, four `fabricated_verdicts`, which `tests/test_review_regression_harness.py::test_a_verdict_pointing_at_no_evidence_leaves_the_defect_reported` drives with the golden files as the reviewed tree, and six `contradicting_verdicts`, the six cached replies trimmed to the finding (from the session's `candidates.json`) and the verdict's status fields, reason, citation, mechanism and perimeter, which `test_a_verdict_its_own_reason_contradicts_is_not_applied` drives the same way. Five existing tests encoded a MITIGATED verdict on a perimeter that does not exist, a mechanism naming no identifier, or MITIGATED meaning verified, and now give a reviewed tree that holds the mechanism or expect `verified=False`: `test_mitigating_mechanism_annotation` and `test_review_verify_cli_command` (`tests/test_verdict_writers.py`), `test_apply_single_finding_verification` and `test_verdicts_are_read_as_the_model_meant_them` (`tests/test_review_verification.py`), and `test_a_mitigated_finding_is_reported_with_its_mitigation` (`tests/test_review_project_conventions.py`). + +## Acceptance Criteria +- [x] The probe's fabricated mitigation gives `(status, reportable) == ('UNVERIFIED', True)`, its note names `src/does/not/exist.py`, and the recommendation is REQUEST CHANGES. `test_the_probe_fabricated_mitigation_stays_in_the_report` asserts `('UNVERIFIED', True, None, False, None, 'mitigation-unproven', True, 'REQUEST CHANGES')` for status, reportable, `verified_by`, `mitigated`, `citation_line`, note kind, the path in the note and `derive_recommendation` (red on da50329: MITIGATED with no note and APPROVE; red before the review fix: `citation_line` 999 of the four-line file). No merged item did this. +- Not checked when merged: the REQUEST CHANGES recommendation on a multi-page review. #789 is open; until it lands the recompose (`_reconcile_single_finding`) still makes every UNVERIFIED finding, these included, non-reportable. +- [x] A mitigation whose perimeter file exists and holds the named mechanism stays MITIGATED. `test_a_mitigation_whose_perimeter_exists_and_holds_the_mechanism_stays_mitigated[in-perimeter, in-finding-file, dot-github]`: `safe_exec` in `app/safe.py`, `cmd` only in the finding's file, and `contents: read` in `.github/workflows/ci.yml`, each MITIGATED, reported, not verified, by `llm`, with no note (red on da50329 only for `verified=True`). +- [x] An absolute or `../` perimeter path counts as unresolved. `test_a_perimeter_that_does_not_resolve_inside_the_reviewed_tree_is_unresolved[absolute-inside-tree, dot-dot-escape, absolute-outside, missing, directory]`; the `../` file and the absolute path inside the tree both exist and hold `safe_exec` (red on da50329: all five MITIGATED). +- [x] A VERIFIED verdict citing a line outside the file is downgraded, and an in-range citation stays VERIFIED. `test_a_confirmation_citing_a_line_outside_the_file_is_unverified[past-the-end, line-zero]` give UNVERIFIED with `citation-out-of-range` (red on da50329: VERIFIED by `llm`), and `[in-range, no-citation]` stay VERIFIED. No merged item checked a VERIFIED citation. +- [x] A finding located by an absolute path, as a scanner writes it (6 of 24 findings in session `20261003-012555`), is checked like a relative one. `test_a_finding_located_by_an_absolute_path_is_read_from_the_reviewed_tree[past-the-end]` gives UNVERIFIED with `citation-out-of-range: line 999 of `` (4 lines)` and `[identifier-in-finding-file]` stays MITIGATED with `cmd` held only in the finding's file (red before the review fix: VERIFIED with no note, and UNVERIFIED with `mitigation-unproven: none of its identifiers`); `[outside-the-tree]` leaves a confirmation on a file outside the tree VERIFIED. An absolute perimeter path is still refused. +- [x] In a reply with one fabricated verdict and valid ones, the valid ones are unchanged. `test_one_fabricated_verdict_leaves_the_rest_of_the_reply_as_it_was` runs `_validate_segment_findings` on a three-verdict reply: UNVERIFIED with `mitigation-unproven`, MITIGATED and VERIFIED, with one model call (red on da50329: the first was MITIGATED). The per-verdict structure predates this item; the test is new. +- [x] `assert_verdict_invariants` holds on every path. `apply_verdict` asserts it on each verdict written, and every new verification test asserts it again on its result (`_judged`, the reply test and the harness test). +- [x] Self-negating mechanisms become UNVERIFIED with a note. `test_a_mechanism_that_describes_the_defect_is_no_mitigation`, the session's five mechanisms with a perimeter that holds their identifiers (red on da50329: all MITIGATED). +- [x] A documentation or conventions file is not a perimeter, and a mechanism naming no identifier, or one no file holds, proves nothing. `test_a_mitigation_pointing_at_no_code_that_enforces_it_is_unproven[no-identifier, conventions-file, identifier-absent]`; the `.devops/review.md` in the tree holds `safe_exec` (red on da50329: all MITIGATED). +- [x] MITIGATED sets `verified=False`. `test_a_mitigated_finding_is_not_a_verified_one[llm, human, agent]` (red on da50329: `verified=True`), and `test_review_verify_cli_command` now expects it for `devops review verify --status MITIGATED`. +- [x] `compute_verdict_distributions` counts degraded mitigations. `test_the_verdict_distributions_count_degraded_mitigations`: a missing perimeter, a mechanism naming no identifier and a verdict naming no mechanism count as `{'mitigation-unproven': 3}`, and a confirmation denying its claim as `{'verifier-contradiction': 1}`, beside one MITIGATED (red on da50329: `{'other': 1}` and three MITIGATED). +- [x] Perimeter matching keeps a leading dot, and reads an absolute path inside the repository relative to its root. `test_a_perimeter_path_matches_itself_and_no_other_file` (11 cases): `.github/workflows/ci.yml` matches itself, also as `./.github/...`, `/etc/hostname` matches itself, and `/src/app.py` and `/.github/workflows/ci.yml` match `src/app.py` and `.github/workflows/ci.yml`; `github/...`, `devops/review.md`, `etc/hostname` and `/src/app.py` match no dotted perimeter or one outside the repository (red on da50329: all five negative cases matched; red before the review fix: the two `` cases did not). `test_a_person_mitigating_a_scanner_finding_is_warned_when_its_file_changes`: `record_mitigated_finding` on a finding at `/src/devops_cli/commands/workspace.py:43` records that absolute perimeter, and a change to `src/devops_cli/commands/workspace.py` warns about it (red before the review fix: no warning; on da50329 it warned, through the `.lstrip("./")` this item removes). +- [x] Golden cases. `tests/golden/review_findings.json` `fabricated_verdicts` (`perimeter-does-not-exist`, `mechanism-names-no-code`, `mechanism-describes-the-defect`, `confirmation-cites-past-the-end`) through `test_a_verdict_pointing_at_no_evidence_leaves_the_defect_reported` (red on da50329: three MITIGATED with APPROVE, one VERIFIED), and `test_a_real_defect_reaches_the_report[shell-injection]`. +- [x] A VERIFIED or MITIGATED verdict whose reason negates the finding's claim, or that says a criterion passed when its recorded result failed, is not applied: the finding stays UNVERIFIED, reported, with no citation and the note kind `verifier-contradiction`. Golden cases from the six cached replies: `test_a_verdict_its_own_reason_contradicts_is_not_applied[llm_6818ef36, llm_f3d7fc26, llm_3ec3580c, llm_54a55488, llm_4617de34]` give `verifier-contradiction` (denials 'no user input', 'not derived from untrusted user input' twice, 'not derived from untrusted input'; and 'test execution which passes' against a run that failed). `[llm_952922a2]` is not applied either, but under `mitigation-unproven`, because its perimeter is the conventions file `.devops/review.md`: its reason denies one word of the claim ('not the actual secret'), below the two a denial needs, and the S7/S8 evaluation itself calls this one a contradiction only in part. Red on da50329: all six applied (three VERIFIED, three MITIGATED). Red before the review fix: the three confirmations still VERIFIED by `llm`, and the three S7 mitigations UNVERIFIED under `mitigation-unproven` but keeping their citation (84, 60, 354). `test_a_verdict_whose_reason_denies_the_claim_is_not_applied[verified-no-user-input, verified-not-derived-from, mitigated-provable]` pins the rule, the last on a mitigation whose perimeter holds its mechanism, and `test_a_confirmation_saying_a_failed_criterion_passed_is_not_applied[failed]` the criterion case (each red before the fix: VERIFIED or MITIGATED). +- [x] A confirmation whose reason supports the claim is still applied. `test_a_confirmation_whose_reason_supports_the_claim_is_still_applied[no-negation, negated-verb, claim-says-missing, claim-says-disabled, passes-as-a-verb]` stay VERIFIED by `llm` with their citation and no note, a failed criterion run recorded on each: a reason without negation, one that negates a guard ("does not prevent path traversal", cache `llm_7b99d901`, which the plain mirror sets aside), two that negate words their claim negates ("no input validation" against "Missing input validation", "no TLS verification" against "TLS verification disabled"), and "the verification command passes the shell metacharacters through". `test_a_confirmation_saying_a_failed_criterion_passed_is_not_applied[passed, one-passed, none-run]` keep a confirmation saying "the test execution which passes" when a run passed or none ran. Over the 778 cached verdicts, 765 are applied as before (Contradictions above). +- [x] Replayed through `_unproven_mitigation_note` against this branch's files, session `20261001-224227`'s 28 MITIGATED verdicts give 26 `mitigation-unproven` (19 name no code identifier, 5 describe the defect, 2 perimeters are `.devops/review.md`) and keep 2 MITIGATED, whose mechanisms name `validate_service_url` and `is_relative_to()` in the files that hold them. The issue counted 18 without an identifier; "use of hasattr check" names `hasattr` without backticks or a call, which `_extract_code_symbols` does not read as one. +- [x] The new tests run offline: no network, model, scanner or Qdrant, and each takes at most 0.13 s (Measurements). The golden cases are trimmed copies; no test reads `.data`. +- [x] `changelog.d/845.md` records the change; `CHANGELOG.md` and `docs/ROADMAP.md` are not edited. +- [x] `ruff check`, `ruff format --check` and `mypy --strict` are clean on the touched modules, `uv run devops docs check` passes, the targeted files pass also with `CI=true GITHUB_ACTIONS=true` (319 passed), and the full suite passes (`uv run pytest -p no:cacheprovider -q -n 6 tests`: 7730 passed, 8 xfailed). The functions added or changed for the review fixes are under `devops scan complexity`'s cap of 10. +- Pending a person: `uv run devops ci` on this branch; it is this PR's own check, which readiness reads. +- Not checked when merged: a mechanism that names its code only in prose ("NetworkPolicy enforces ...", "use of hasattr check") is UNVERIFIED, since `_extract_code_symbols` reads backticked names, call forms and names with an underscore; the verifier prompt now asks for the identifier in backticks. + +## Measurements +The new tests, run with `uv run pytest -p no:cacheprovider -q -n 0 --durations=0` on this branch; every call not listed took under 0.01 s, the 35 cases added or changed for the review findings (contradictions, supporting confirmations, absolute locations, perimeter matching, the six golden replies) among them, whose setup takes at most 0.03 s. The first harness case of a process takes about 0.5 s of warm-up, whichever case it is (`missing-containment` in a full run); run alone after it, `shell-injection` takes 0.05 s. + +| Test | Call | +| :--- | ---: | +| `test_one_fabricated_verdict_leaves_the_rest_of_the_reply_as_it_was` | 0.13 s | +| `test_the_verdict_distributions_count_degraded_mitigations` | 0.01 s | +| `test_a_perimeter_path_matches_itself_and_no_other_file[/etc/hostname-/etc/hostname-True]` | 0.01 s | +| `test_a_confirmation_citing_a_line_outside_the_file_is_unverified[in-range]` | 0.01 s | diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ai_code_review.md b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ai_code_review.md index 509bc0ecf8..d2aa748e4f 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ai_code_review.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ai_code_review.md @@ -53,6 +53,7 @@ graph TD - **Path Routing**: Path, branch and pull request reviews keep lockfiles, planning documents (`docs/ROADMAP.md`, `CHANGELOG.md`, `changelog.d/`, `docs/agent/tasks/`, `docs/adr/`) and generated references (`docs/commands/*.md`, `docs/CLI_REFERENCE.md`) off persona pages, by one predicate (`skips_persona_review`). Gitleaks still reads them, the verifier of a finding in one is sent the lines it cites rather than the file, and a change made only of such files calls no model. - **One Taxonomy and Calibrated Severities**: A finding's category is the CWE it cites (`CWE-`) or a class of the closed `DefectClass` enum, the original kept as `category_raw`; the report and the category metrics group findings by that class. Once verdicts are final, CRITICAL requires VERIFIED, a hedged title ("Potential", "May", "Could") is MEDIUM at most unless executed criteria verified it, and a finding in a test or a document is LOW at most unless it concerns a verified secret, which a secret scanner's match counts as. A scanner's absolute path is read from the repository root. The verifier may only lower a severity; the value given first stays as `severity_raw`. Calibration runs when the report is written: a later verdict through `devops review verify` changes a finding's status, not its severity. - **Advisories Backed by the Scan**: A CVE or GHSA id stays in a finding's references only when a vulnerability record of this session's dependency scan, OSV's or Trivy's, carries it, by its id or by an alias the record holds (OSV's batch lookup returns ids only, so a review's records hold none); otherwise it is removed with a note, and a finding whose only evidence it was is INVALIDATED as `deterministic:unbacked_advisory`. An id written as a placeholder (`CVE-2023-xxxx`, or ascending digits such as `CVE-2023-1234`) invalidates its finding unless the scan carries it: sequential ids are also published ones, CVE-2016-1234 and CVE-2023-1234 among them. + - **Verdicts Point at Evidence the Tree Holds**: A model's MITIGATED verdict stands only when every perimeter file resolves inside the reviewed tree (`safe_resolve_subpath`: no absolute path, no `../` escape, and for a pull request only its own files) and is code or configuration rather than documentation such as the conventions file, and the mechanism names an identifier that a perimeter file or the finding's file holds. A mechanism that negates itself ("caught but not logged", "is expected to handle") describes the defect. A model's VERIFIED verdict citing a line its file does not have is not a confirmation. Nor is a VERIFIED or MITIGATED verdict whose own reason denies the claim ("No user input reaches this point" against "Untrusted user input in `importlib.import_module()`"), or says a criterion passed when every recorded run of one failed. Each becomes UNVERIFIED and stays reported, with a `mitigation-unproven`, `citation-out-of-range` or `verifier-contradiction` note that `profile.json` counts. Each verdict is checked on its own, and a MITIGATED finding is never a verified one (`verified=False`). A finding's own location, absolute as a scanner writes it, is read from the reviewed tree like a relative one; only a perimeter path must be repository-relative. - **Executive Summary & Pattern Synthesis (review.md)**: Every consolidated review report generates an Executive Summary statement at the top detailing: - The reported findings counted by status, each with its severities: verified and unverified, then, listed apart, those verification never reached and the mitigated ones. Findings rank verified first, then by severity, location and title, never by a model's confidence. - The defect classes that recur among verified findings, most severe first; a class seen once, a CVE or a finding title is never a theme. diff --git a/src/devops_cli/ai/review/mitigations.py b/src/devops_cli/ai/review/mitigations.py index 107ed9e7d8..b65d753ba3 100644 --- a/src/devops_cli/ai/review/mitigations.py +++ b/src/devops_cli/ai/review/mitigations.py @@ -11,13 +11,13 @@ import os from collections.abc import Iterable, Sequence from datetime import UTC, datetime -from pathlib import Path +from pathlib import Path, PurePosixPath from uuid import uuid4 from pydantic import BaseModel, ConfigDict, Field from devops_cli.ai.review_schema import Finding -from devops_cli.core.repo import resolve_data_path +from devops_cli.core.repo import find_repo_root, resolve_data_path logger = logging.getLogger(__name__) @@ -166,29 +166,50 @@ def record_mitigated_finding( return entry -def _normalize_path(path_str: str) -> str: - """Normalize file path for consistent prefix and separator matching.""" - return path_str.replace("\\", "/").strip().lstrip("./") +def _normalize_path(path_str: str, repo_root: PurePosixPath) -> str: + """A path with forward slashes and no leading `./`, relative to `repo_root` when it is an + absolute path inside it. + + `.lstrip("./")` also cut the dot off `.github/...` and `.devops/...`, and the root off an + absolute path (#845). A scanner's finding, and so a person's mitigation of it, names its file + absolute (#788), while changed files are repository-relative. + """ + normalized = path_str.replace("\\", "/").strip() + while normalized.startswith("./"): + normalized = normalized[2:] + path = PurePosixPath(normalized) + if path.is_absolute() and path.is_relative_to(repo_root): + return path.relative_to(repo_root).as_posix() + return normalized def _is_path_matching(changed: str, perimeter: str) -> bool: - """Check if changed file path matches a perimeter path exactly or as child.""" + """Whether a changed file is a perimeter file: the same path, or for two relative paths, one + ending in the other. An absolute path, which lies outside the repository, matches only + itself.""" if changed == perimeter: return True - if changed.endswith("/" + perimeter) or perimeter.endswith("/" + changed): - return True - return False + if changed.startswith("/") or perimeter.startswith("/"): + return False + return changed.endswith("/" + perimeter) or perimeter.endswith("/" + changed) def find_perimeter_changes( - changed_files: Iterable[str], ledger_path: Path | None = None + changed_files: Iterable[str], + ledger_path: Path | None = None, + repo_root: Path | None = None, ) -> list[tuple[MitigatedFindingEntry, list[str]]]: - """Find mitigated findings whose perimeter files intersect with changed files.""" + """Find mitigated findings whose perimeter files intersect with changed files. + + `repo_root`, the current repository's by default, is what an absolute path is read + against. + """ entries = load_mitigated_findings(ledger_path) if not entries: return [] - norm_changed = {_normalize_path(f) for f in changed_files if f.strip()} + root = PurePosixPath((repo_root or find_repo_root()).resolve().as_posix()) + norm_changed = {_normalize_path(f, root) for f in changed_files if f.strip()} if not norm_changed: return [] @@ -196,7 +217,7 @@ def find_perimeter_changes( for entry in entries: matched_perimeters: list[str] = [] for perim in entry.perimeter_files: - norm_perim = _normalize_path(perim) + norm_perim = _normalize_path(perim, root) if any(_is_path_matching(ch, norm_perim) for ch in norm_changed): matched_perimeters.append(perim) if matched_perimeters: diff --git a/src/devops_cli/ai/review/verdicts.py b/src/devops_cli/ai/review/verdicts.py index 2a4f8d348e..e48874814e 100644 --- a/src/devops_cli/ai/review/verdicts.py +++ b/src/devops_cli/ai/review/verdicts.py @@ -204,10 +204,10 @@ def _build_verdict_updates( "citation_line": citation_line, "verification_note": verification_note, } - # MITIGATED + # MITIGATED: reported beside the defect it limits, which is not a verified one (#845). return { "status": "MITIGATED", - "verified": True, + "verified": False, "reportable": True, "mitigated": True, "verified_by": by, diff --git a/src/devops_cli/ai/review/verification.py b/src/devops_cli/ai/review/verification.py index 313c51aef4..287705b188 100644 --- a/src/devops_cli/ai/review/verification.py +++ b/src/devops_cli/ai/review/verification.py @@ -19,6 +19,7 @@ from devops_cli.ai.client.network import limit_completion_tokens from devops_cli.ai.review.chunker import page_line_number +from devops_cli.ai.review.classification import FileContextType, classify_file_context from devops_cli.ai.review.construct_validator import validate_construct_location from devops_cli.ai.review.judged_claims import cited_code from devops_cli.ai.review.verdicts import apply_verdict @@ -26,6 +27,7 @@ Finding, ReviewResult, SavedFinding, + _extract_code_symbols, extract_json_block, less_severe, ) @@ -35,18 +37,23 @@ CONST_AUTH_HEADER_CLAIM_KEYWORDS, CONST_AUTH_HEADER_CODE_PATTERNS, CONST_CACHE_DIR_NAME, + CONST_CITATION_OUT_OF_RANGE, CONST_COMPLIMENT_NEGATIONS, CONST_COMPLIMENT_PHRASES, CONST_CRITERIA_NON_DISCRIMINATING, + CONST_CRITERION_PASSED_CLAIM_PATTERN, CONST_FINISH_REASON_LENGTH, CONST_FIXTURE_CREDENTIAL_KEYWORDS, CONST_MASKED_SYNTAX_ERROR_PHRASES, + CONST_MITIGATION_UNPROVEN, CONST_MONOLOGUE_PREFIXES, CONST_PLACEHOLDER_VALUES, + CONST_SELF_NEGATING_MECHANISM_PATTERN, CONST_TYPECHECK_PROBE_CACHE_DIR_NAME, CONST_TYPECHECK_PROBE_MYPY_CONFIG, CONST_UNINITIALIZED_CLAIM_KEYWORDS, CONST_VERIFICATION_UNAVAILABLE, + CONST_VERIFIER_CONTRADICTION, CONST_VERIFIER_FINDING_FIELDS, CONST_VERIFIER_INCONCLUSIVE, CONST_VERIFIER_NO_VERDICT, @@ -56,6 +63,7 @@ ) from devops_cli.config.defaults import ( DEFAULT_DIFF_CONTEXT_LINES, + DEFAULT_MAX_AST_FILE_SIZE_BYTES, DEFAULT_MAX_RELATED_FILES, DEFAULT_RELATED_FILE_MAX_CHARS, DEFAULT_REVIEW_VERIFICATION_REPLY_BASE_TOKENS, @@ -63,6 +71,8 @@ DEFAULT_REVIEW_VERIFICATION_REPLY_TOKENS_PER_FINDING, DEFAULT_TYPECHECK_PROBE_TIMEOUT_SECONDS, ) +from devops_cli.core.paths import safe_resolve_subpath +from devops_cli.exceptions.base import DevOpsCLIError from devops_cli.security.sanitizer import ( mask_secrets, sanitize_prompt_boundary_tags, @@ -209,8 +219,6 @@ def _read_and_mask_related_file( if _is_secret_path(rel_path): return None try: - from devops_cli.core.paths import safe_resolve_subpath - resolved = safe_resolve_subpath(repo_root, rel_path, must_exist=True) if not resolved.is_file(): return None @@ -1694,6 +1702,119 @@ def _without_self_refutation( return withdrawn, [], True +# A reason's words, an identifier (`validate_no_path_traversal`) kept whole. +_REASON_WORD = re.compile(r"[a-z0-9_]+(?:'[a-z]+)?") +# What a reason may put between a negation and the claim it denies: "no actual secret", "not +# derived from untrusted user input". +_DENIAL_FILLERS = frozenset( + {"a", "an", "the", "any", "actual", "such", "is", "are", "be", "being", "been", "was", "were"} +) +_DENIAL_BRIDGES = frozenset( + {("derived", "from"), ("coming", "from"), ("sourced", "from")} + | {("controlled", "by"), ("supplied", "by"), ("provided", "by")} +) +# "without" names a missing guard, as a confirmation does ("without a timeout"), and "already" a +# check a mitigation points at; neither denies the claim. +_NOT_A_DENIAL = frozenset({"without", "already"}) +# Words by which a claim negates what follows ("Missing timeout") or what precedes them ("TLS +# verification disabled"): a reason that negates the same words agrees with it. +_CLAIM_ABSENCE_BEFORE = frozenset( + {"no", "not", "never", "none", "without", "missing", "lack", "lacks", "lacking", "absent"} +) +_CLAIM_ABSENCE_AFTER = frozenset({"missing", "absent", "disabled"}) +# A denial names at least this many consecutive words of the claim: "no user input". One word +# ("not the actual secret") is as often a confirmation's aside. +_DENIAL_MIN_CLAIM_WORDS = 2 +_CLAIMS_A_CRITERION_PASSED = re.compile(CONST_CRITERION_PASSED_CLAIM_PATTERN, re.IGNORECASE) + + +def _reason_words(text: str) -> list[str]: + return _REASON_WORD.findall(text.lower().replace("’", "'")) + + +def _is_negation(word: str) -> bool: + return bool(_NEGATION.fullmatch(word)) or word.endswith("n't") + + +def _negated_in_claim(claims: Sequence[str]) -> set[str]: + """The words a claim itself negates: up to five after "no", "not" or "missing", and up to + three before "missing" or "disabled".""" + negated: set[str] = set() + for claim in claims: + words = _reason_words(claim) + for i, word in enumerate(words): + if word in _CLAIM_ABSENCE_BEFORE or _is_negation(word): + negated.update(words[i + 1 : i + 6]) + if word in _CLAIM_ABSENCE_AFTER: + negated.update(words[max(0, i - 3) : i]) + return negated + + +def _after_fillers(words: Sequence[str], start: int) -> int: + """The index of the first word from `start` that is neither a filler nor a bridge.""" + i = start + while i < len(words): + if words[i] in _DENIAL_FILLERS: + i += 1 + elif tuple(words[i : i + 2]) in _DENIAL_BRIDGES: + i += 2 + else: + break + return i + + +def _denial_of_the_claim(reason: str, f: Finding) -> str | None: + """The words in which a verdict's reason denies the finding's claim; None when it does not. + + The mirror of `_reason_confirms`, on the same claim words and negations: a negation followed, + past fillers such as "the" or "derived from", by at least two consecutive words of the + claim that the claim does not negate itself. "No user input reaches this point" denies + "Untrusted user input in `importlib.import_module()`". A negated verb ("does not quote user + input"), a missing guard ("without a timeout") or one the claim says is missing ("no + timeout" against "Missing timeout") confirms the claim. + """ + claims = [*(str(c) for c in f.verification_criteria), f.title] + claim_words = set().union(*(_claim_words(c) for c in claims)) - _negated_in_claim(claims) + words = _reason_words(reason) + for i, word in enumerate(words): + if not _is_negation(word) or word in _NOT_A_DENIAL: + continue + start = end = _after_fillers(words, i + 1) + while end < len(words) and words[end] in claim_words: + end += 1 + if len(set(words[start:end])) >= _DENIAL_MIN_CLAIM_WORDS: + return " ".join(words[i:end]) + return None + + +def _claims_a_failed_criterion_passed(reason: str, f: Finding) -> str | None: + """The words in which a reason says a criterion passed, when no recorded run of one did.""" + ran = [r for r in f.criteria_execution_results if r.executable] + if not ran or any(r.passed for r in ran): + return None + claim = _CLAIMS_A_CRITERION_PASSED.search(reason) + return " ".join(_reason_words(claim.group(0))) if claim else None + + +def _contradiction_note(f: Finding, status: str, reason: str) -> str | None: + """Why a confirmation or mitigation is not applied when its own reason contradicts it. + + A reason that denies the claim argues the finding away, and one that says a criterion + passed when its recorded run failed points at evidence that does not exist (#845). + """ + if denial := _denial_of_the_claim(reason, f): + return ( + f"{CONST_VERIFIER_CONTRADICTION}: the {status} verdict's reason denies the claim " + f"('{denial}')" + ) + if passed := _claims_a_failed_criterion_passed(reason, f): + return ( + f"{CONST_VERIFIER_CONTRADICTION}: the {status} verdict's reason says a criterion " + f"passed ('{passed}'), but its recorded run failed" + ) + return None + + def _extract_citation_line(item: dict[str, Any]) -> int | None: """The line a verdict cites under an explicit citation key. @@ -1762,7 +1883,6 @@ def _validate_citation_line( ) from devops_cli.ai.review.construct_validator import extract_finding_construct_candidates - from devops_cli.ai.review_schema import _extract_code_symbols candidates = extract_finding_construct_candidates(f) if not candidates: @@ -1808,17 +1928,166 @@ def _extract_finding_confidence(conf_val: Any, default: float | None) -> float | return default -def _determine_mitigated_degradation_note( - reason: str, mech: str | None, perimeter: list[str] -) -> str: - """Return specific reason why a claimed mitigation was degraded to UNVERIFIED.""" +def _mitigation_presence_gap(reason: str, mech: str | None, perimeter: list[str]) -> str | None: + """Which part of a mitigation the verdict leaves out; None when it names them all.""" if not reason: - return "Mitigated verdict without explanation; degraded to UNVERIFIED" + return "no reason given" if not mech or _is_placeholder(mech): - return "Mitigated verdict without specified mitigating mechanism; degraded to UNVERIFIED" + return "no mitigating mechanism named" if not perimeter or _is_placeholder(perimeter): - return "Mitigated verdict without specified perimeter files; degraded to UNVERIFIED" - return "" + return "no perimeter files named" + return None + + +_SELF_NEGATING_MECHANISM = re.compile(CONST_SELF_NEGATING_MECHANISM_PATTERN, re.IGNORECASE) + + +def _reviewed_tree_roots(repo_root: Path | None) -> tuple[Path, ...]: + """The directories a verdict's files must lie in: the review's target and its repository. + + A pull request's head is written outside any repository, so there only the pull request's + own files can be pointed at. + """ + if repo_root is None: + return () + from devops_cli.core.repo import find_repo_root + + return tuple(dict.fromkeys((repo_root.resolve(), find_repo_root(repo_root)))) + + +def _file_in_reviewed_tree(path: str, roots: Sequence[Path]) -> Path | None: + """The file `path` names inside the reviewed tree, through `safe_resolve_subpath`. + + None for a path that escapes the tree, absolute, through `..` or a symlink, and anything + but an existing file. A `:line` suffix is read as a location's. A finding's own location is + read with it: the pipeline writes that, and a scanner writes it absolute (#788). + """ + file_part = _parse_location(path)[0] + if not file_part: + return None + for root in roots: + try: + resolved = safe_resolve_subpath(root, file_part, must_exist=True) + except DevOpsCLIError, OSError: + continue + if resolved.is_file(): + return resolved + return None + + +def _perimeter_file(path: str, roots: Sequence[Path]) -> Path | None: + """The file a verdict's perimeter path names in the reviewed tree; None for any absolute path. + + The verifier is asked for repository-relative paths, so an absolute one, even to a file in + the tree, is refused before containment is checked. + """ + if Path(_parse_location(path)[0]).is_absolute(): + return None + return _file_in_reviewed_tree(path, roots) + + +def _reviewed_text(path: Path) -> str | None: + """A reviewed file's text; None when it is too large or cannot be read.""" + try: + if path.stat().st_size > DEFAULT_MAX_AST_FILE_SIZE_BYTES: + return None + return path.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + + +def _holds_any(path: Path, identifiers: Iterable[str]) -> bool: + """Whether the file names one of `identifiers` as a whole word, in any case.""" + text = _reviewed_text(path) or "" + return any(re.search(rf"\b{re.escape(name)}\b", text, re.IGNORECASE) for name in identifiers) + + +def _perimeter_gap( + perimeter: Sequence[str], roots: Sequence[Path] +) -> tuple[list[Path], str | None]: + """The perimeter's files, or why one of them is not code in the reviewed tree.""" + files: list[Path] = [] + for path in perimeter: + resolved = _perimeter_file(path, roots) + if resolved is None: + return files, f"perimeter file `{path}` does not resolve inside the reviewed tree" + if classify_file_context(resolved) is FileContextType.DOCUMENTATION: + return files, f"perimeter file `{path}` is documentation, not code that enforces it" + files.append(resolved) + return files, None + + +def _mitigation_evidence_gap( + f: Finding, mechanism: str, perimeter: Sequence[str], repo_root: Path | None +) -> str | None: + """Why a mitigation points at no code in the reviewed tree that enforces it; None when it does. + + Every perimeter file resolves inside the tree and is not documentation, such as a + conventions file, and the mechanism names an identifier (`_extract_code_symbols`) that a + perimeter file or the finding's own file holds. A mechanism that negates itself ("caught but + not logged") describes the defect. + """ + if negation := _SELF_NEGATING_MECHANISM.search(mechanism): + return f"the mechanism describes the defect ('{negation.group(0)}'), not what limits it" + roots = _reviewed_tree_roots(repo_root) + files, gap = _perimeter_gap(perimeter, roots) + if gap: + return gap + identifiers = _extract_code_symbols(mechanism) + if not identifiers: + return "the mechanism names no code identifier" + finding_file = _file_in_reviewed_tree(f.location, roots) + if any(_holds_any(p, identifiers) for p in [*files, *filter(None, [finding_file])]): + return None + names = ", ".join(f"`{name}`" for name in sorted(identifiers)[:5]) + return f"none of its identifiers ({names}) appears in a perimeter file or the finding's file" + + +def _citation_outside_file( + f: Finding, citation_line: int | None, repo_root: Path | None +) -> str | None: + """Why a confirmation's cited line is no line of the finding's file; None when it is one, + or when there is no citation, or no file in the reviewed tree to count lines in.""" + if citation_line is None: + return None + file_part = _parse_location(f.location)[0] + if citation_line < 1: + return f"{CONST_CITATION_OUT_OF_RANGE}: line {citation_line} of `{file_part}`" + path = _file_in_reviewed_tree(file_part, _reviewed_tree_roots(repo_root)) + text = _reviewed_text(path) if path else None + if text is None or citation_line <= len(lines := text.splitlines()): + return None + return ( + f"{CONST_CITATION_OUT_OF_RANGE}: line {citation_line} of `{file_part}` ({len(lines)} lines)" + ) + + +def _unproven_mitigation_note( + f: Finding, reason: str, mechanism: str | None, perimeter: list[str], repo_root: Path | None +) -> str | None: + """Why a MITIGATED verdict proves no mitigation; None when it points at one.""" + gap = _mitigation_presence_gap(reason, mechanism, perimeter) or _mitigation_evidence_gap( + f, mechanism or "", perimeter, repo_root + ) + return f"{CONST_MITIGATION_UNPROVEN}: {gap}" if gap else None + + +def _claims_mitigation(item: dict[str, Any]) -> bool: + """Whether a verdict calls its finding mitigated, by flag or by status.""" + status = str(item.get("status") or "").strip().upper() + return bool(_verdict_bool(item.get("mitigated"))) or status == "MITIGATED" + + +def _resolve_refutation( + f: Finding, reason: str, citation_line: int | None, repo_root: Path | None +) -> tuple[str, str, int | None, str | None, bool]: + """An INVALIDATED verdict, or UNVERIFIED with a note when its citation does not hold.""" + if citation_line is None and _REFUTES_THE_CRITERIA.search(reason): + return "UNVERIFIED", "", None, _CRITERIA_REFUTATION_NOTE, True + is_valid, cit_line, note = _validate_citation_line(f, citation_line, repo_root) + if not is_valid: + return "UNVERIFIED", "", None, note, True + return "INVALIDATED", reason, cit_line, None, False def _resolve_status_and_verification_note( @@ -1832,30 +2101,29 @@ def _resolve_status_and_verification_note( repo_root: Path | None, is_rep: bool, ) -> tuple[str, str, int | None, str | None, bool]: - """Resolve validated status, reason, citation line, verification note, and reportability.""" - if status_val == "INVALIDATED": - if citation_line is None and _REFUTES_THE_CRITERIA.search(reason): - return "UNVERIFIED", "", None, _CRITERIA_REFUTATION_NOTE, True - is_valid, cit_line, note = _validate_citation_line(f, citation_line, repo_root) - if not is_valid: - return "UNVERIFIED", "", None, note, True - return "INVALIDATED", reason, cit_line, None, False - - if status_val == "MITIGATED": - note = ( - "Mitigated verdict without specified mitigating mechanism" - if not mitigating_mechanism or _is_placeholder(mitigating_mechanism) - else None - ) - return "MITIGATED", reason, citation_line, note, True - - is_mitigated = ( - _verdict_bool(item.get("mitigated")) or str(item.get("status", "")).upper() == "MITIGATED" - ) - if is_mitigated and status_val == "UNVERIFIED": - note = _determine_mitigated_degradation_note(reason, mitigating_mechanism, perimeter_files) - return "UNVERIFIED", reason, citation_line, note or None, True + """Resolve validated status, reason, citation line, verification note, and reportability. + Each verdict is checked on its own (#845): a confirmation or mitigation whose reason + contradicts it is not applied, a mitigation stands only on code the reviewed tree holds, + and a confirmation only on a line its file has. One that fails is UNVERIFIED, reported, + with a note naming the check and no citation. + """ + if status_val == "INVALIDATED": + return _resolve_refutation(f, reason, citation_line, repo_root) + if status_val == "MITIGATED" and ( + note := _contradiction_note(f, status_val, reason) + or _unproven_mitigation_note(f, reason, mitigating_mechanism, perimeter_files, repo_root) + ): + return "UNVERIFIED", "", None, note, True + if status_val == "VERIFIED" and ( + note := _contradiction_note(f, status_val, reason) + or _citation_outside_file(f, citation_line, repo_root) + ): + return "UNVERIFIED", "", None, note, True + # A mitigation the verdict left unverified for want of a part it never named says which. + gap = _mitigation_presence_gap(reason, mitigating_mechanism, perimeter_files) + if gap and _claims_mitigation(item): + return status_val, reason, None, f"{CONST_MITIGATION_UNPROVEN}: {gap}", is_rep return status_val, reason, citation_line, None, is_rep @@ -1896,20 +2164,6 @@ def _resolve_finding_attributes( return sev, loc, final_obs, final_exp -def _build_finding_verdict_kwargs( - status_val: str, - item: dict[str, Any], - final_reportable: bool, -) -> dict[str, Any]: - """Build extra keyword arguments for apply_verdict.""" - extra_kw: dict[str, Any] = {} - if status_val == "MITIGATED" and _verdict_bool(item.get("verified")) is False: - extra_kw["verified"] = False - if final_reportable is False: - extra_kw["reportable"] = False - return extra_kw - - def _no_verdict_note(f: Finding, withdrawn: bool) -> str: """Why a finding the verifier judged has no verdict, when no check of the verdict said. @@ -1925,6 +2179,19 @@ def _no_verdict_note(f: Finding, withdrawn: bool) -> str: return CONST_VERIFIER_INCONCLUSIVE +def _mitigation_fields( + status_val: str, item: dict[str, Any], mechanism: str | None, perimeter: list[str] +) -> dict[str, Any]: + """The mitigation a MITIGATED verdict records; none for any other verdict.""" + if status_val != "MITIGATED": + return {} + return { + "mitigating_mechanism": mechanism, + "perimeter_files": perimeter, + "regression_test": _extract_regression_test(item), + } + + def _apply_single_finding_verification( f: Finding, item: dict[str, Any] | None, @@ -1947,7 +2214,6 @@ def _apply_single_finding_verification( raw_citation = _extract_citation_line(item) mitigating_mechanism = _extract_mitigating_mechanism(item, raw_reason) perimeter_files = _extract_perimeter_files(item, raw_reason) - regression_test = _extract_regression_test(item) status_val, reason, citation_line, verification_note, final_rep = ( _resolve_status_and_verification_note( @@ -1965,7 +2231,6 @@ def _apply_single_finding_verification( sev, loc, final_obs, final_exp = _resolve_finding_attributes(f, item) status_val, by, reason = _check_finding_polarity(final_obs, final_exp, status_val, reason) - extra_kw = _build_finding_verdict_kwargs(status_val, item, final_rep) if status_val == "UNVERIFIED" and verification_note is None: verification_note = _no_verdict_note(f, withdrawn) @@ -1975,9 +2240,6 @@ def _apply_single_finding_verification( by=by, reason=reason if status_val in {"INVALIDATED", "MITIGATED"} else None, citation_line=citation_line, - mitigating_mechanism=mitigating_mechanism if status_val == "MITIGATED" else None, - perimeter_files=perimeter_files if status_val == "MITIGATED" else None, - regression_test=regression_test if status_val == "MITIGATED" else None, verification_note=verification_note, confidence_score=conf, verified_at=now_iso if status_val != "UNVERIFIED" else None, @@ -1989,7 +2251,8 @@ def _apply_single_finding_verification( verified_criteria_matched=merged_ver_matched, invalidated_criteria_matched=merged_inv_matched, criteria_execution_results=f.criteria_execution_results, - **extra_kw, + reportable=None if final_rep else False, + **_mitigation_fields(status_val, item, mitigating_mechanism, perimeter_files), ) diff --git a/src/devops_cli/ai/review_schema.py b/src/devops_cli/ai/review_schema.py index 9ed0e9643c..29c5bb9085 100644 --- a/src/devops_cli/ai/review_schema.py +++ b/src/devops_cli/ai/review_schema.py @@ -1143,7 +1143,7 @@ def _merge_two_findings[F: Finding](base: F, other: F) -> F: reportable = False verified_by = base.verified_by or other.verified_by elif best_status == "MITIGATED": - verified = base.verified or other.verified + verified = False mitigated = True reportable = True verified_by = base.verified_by or other.verified_by diff --git a/src/devops_cli/ai/tasks/verify_finding_system.md b/src/devops_cli/ai/tasks/verify_finding_system.md index f1daca6edd..c8e27e4e50 100644 --- a/src/devops_cli/ai/tasks/verify_finding_system.md +++ b/src/devops_cli/ai/tasks/verify_finding_system.md @@ -7,7 +7,7 @@ These rules hold for any project. The reviewed project's own conventions, when g - **Verified** needs the defective line in front of you: quote it in `reason` and give its number in `citation_line`. A vulnerability also needs the untrusted source and the sink it reaches; a misconfiguration needs the quoted setting and what it exposes or permits beyond its job. A passing command counts, for either verdict, only when it runs the cited code and asserts the outcome; a command that finds, imports or prints code (`git grep`, `hasattr`, `co_varnames`, `inspect.getsource`, `print('ok')`) shows only that the code exists. - **Trusted input**: the operator's config files, environment variables and command-line arguments, and values the code builds itself, are trusted unless the project's conventions say otherwise. A claim that needs an attacker to control one is refuted, unless the conventions require the guard anyway; then verify it as LOW. - **Refuted** (`invalidated`, `invalidated_criteria_matched`): the shown code contradicts the claim. The check exists, the value cannot reach the sink, the name is defined. A check in the shown code that makes the claimed failure impossible (a format check that admits no `..`, an `except` that returns) refutes the finding. Cite that line in `citation_line`. -- **Mitigated** (`mitigated`): the defect the finding describes is present and the claimed failure can still happen, but something else limits it. Name the mechanism in `mitigating_mechanism`, cite the file(s) enforcing the boundary in `perimeter_files` (as a non-empty array of file paths), cite the line that provides it in `citation_line` and `reason`, and leave `invalidated_criteria_matched` empty. A mitigation without both a named `mitigating_mechanism` and at least one file in `perimeter_files` proves nothing and will be degraded to UNVERIFIED. A mechanism you cannot point to in the shown code is not a mitigation. +- **Mitigated** (`mitigated`): the defect the finding describes is present and the claimed failure can still happen, but something else limits it. Name the mechanism in `mitigating_mechanism`, cite the file(s) enforcing the boundary in `perimeter_files` (as a non-empty array of file paths), cite the line that provides it in `citation_line` and `reason`, and leave `invalidated_criteria_matched` empty. A mitigation without both a named `mitigating_mechanism` and at least one file in `perimeter_files` proves nothing and will be degraded to UNVERIFIED. So will one whose perimeter file is not a repository-relative path to code or configuration in the reviewed tree (documentation, the project's conventions included, enforces nothing), or whose mechanism names no identifier, in backticks, that a perimeter file or the finding's file holds. A mechanism that describes the defect ("caught but not logged", "is expected to handle") is not a mitigation, nor is one you cannot point to in the shown code. - **Unverified** is the answer when the code that would settle the claim is not shown. - **Severity** is the band the evidence supports, on the reviewer's scale: - **CRITICAL** — an untrusted input reaches code execution, credential disclosure, or a write outside its root, and you can quote every step. diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 5259531969..de19b0738b 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2914,6 +2914,17 @@ # Marks a finding whose verification and invalidation criteria both passed as evidence: the # pair cannot tell the defect from its absence, so the finding goes to the verifier. CONST_CRITERIA_NON_DISCRIMINATING: Final[str] = "criteria-non-discriminating" +# Marks a finding the verifier called mitigated without pointing at code that enforces the +# mitigation (#845): no mechanism, reason or perimeter named, a perimeter file that does not +# resolve inside the reviewed tree or is documentation, a mechanism that describes the defect, +# or one naming no identifier a perimeter file or the finding's file holds. +CONST_MITIGATION_UNPROVEN: Final[str] = "mitigation-unproven" +# Marks a finding the verifier confirmed by citing a line its file does not have (#845). +CONST_CITATION_OUT_OF_RANGE: Final[str] = "citation-out-of-range" +# Marks a finding whose confirmation or mitigation the verifier's own reason contradicts +# (#845): the reason denies the claim ("No user input reaches this point"), or says a criterion +# passed whose recorded run failed. The mirror of a self-refutation. +CONST_VERIFIER_CONTRADICTION: Final[str] = "verifier-contradiction" # The notes that say why a finding has no verdict, each counted in a review's profile.json. A # note names its kind before any `: ` detail. CONST_VERIFICATION_NOTE_KINDS: Final[tuple[str, ...]] = ( @@ -2924,6 +2935,25 @@ CONST_VERIFIER_SELF_REFUTATION, CONST_VERIFIER_INCONCLUSIVE, CONST_CRITERIA_NON_DISCRIMINATING, + CONST_MITIGATION_UNPROVEN, + CONST_CITATION_OUT_OF_RANGE, + CONST_VERIFIER_CONTRADICTION, +) +# A mitigating mechanism that negates itself describes the defect, not what limits it: "caught +# but not logged", "is expected to handle", "the mock is too permissive" (session +# 20261001-224227, #845). +CONST_SELF_NEGATING_MECHANISM_PATTERN: Final[str] = ( + r"\bbut (?:does )?not\b|\bis expected to\b|\bintended to\b|\btoo permissive\b" +) +# A verdict's reason saying a criterion passed: a test, command, criterion or check that passes +# or succeeds with nothing after it ("the test execution which passes, confirming"; not "passes +# the flag"), or an exit status of 0 (session 20261003-005122, #845). +CONST_CRITERION_PASSED_CLAIM_PATTERN: Final[str] = ( + r"\b(?:tests?|commands?|criteri(?:on|a)|checks?|executions?|assertions?)\b" + r"(?:\W+\w+){0,3}?\W+(?:pass(?:es|ed)?|succeed(?:s|ed)?)" + r"(?=\s*(?:[.,;:()]|$)|\s+(?:successfully|correctly|cleanly|and|but|so|which|while" + r"|confirming|showing|indicating|as)\b)" + r"|\bexit(?:s|ed)?(?:\s+with)?(?:\s+(?:code|status))?\s+0\b" ) # The fields of a finding the verifier is shown: its number in the call and the claim as the # reviewer wrote it, criteria included. Nothing the pipeline writes (status, confidence, diff --git a/tests/golden/review_findings.json b/tests/golden/review_findings.json index 370005fe78..c6cb1ecc4c 100644 --- a/tests/golden/review_findings.json +++ b/tests/golden/review_findings.json @@ -1,5 +1,5 @@ { - "about": "Golden findings for the review regression harness (#509). Real defects come from injected defects of the synthetic corpus (#415) and from reproductions written by hand for the #509 audit; none comes from the verifier under test. Each must survive every deterministic layer. Known false alarms must still be caught. Add human-verified records here as they accumulate.", + "about": "Golden findings for the review regression harness (#509). Real defects come from injected defects of the synthetic corpus (#415) and from reproductions written by hand for the #509 audit; none comes from the verifier under test. Each must survive every deterministic layer. Known false alarms must still be caught. A verdict pointing at evidence the reviewed files do not hold (`fabricated_verdicts`, #845) must leave its defect reported, and so must a confirmation or mitigation whose own reason contradicts it (`contradicting_verdicts`, six cached verifier replies of review sessions 20261003-005122 and 20261003-012555, #845). Add human-verified records here as they accumulate.", "files": { "core/paths.py": "from pathlib import Path\n\n\ndef safe_resolve_subpath(base_dir: Path, name: str) -> Path:\n candidate = base_dir / name\n if candidate.is_symlink():\n raise PermissionError(name)\n return candidate.resolve()\n", "security/suppression.py": "CONST_SUPPRESSION_MAX_INHERITANCE_DEPTH = 8\n\n\ndef load_policy(path, loaded=None, _depth=0):\n loaded = loaded or set()\n loaded.add(path)\n parent = read_parent(path)\n if parent and parent not in loaded:\n return load_policy(parent, loaded, _depth + 1)\n return path\n\n\ndef read_parent(path):\n return None\n", @@ -27,7 +27,8 @@ "app/helpers.py": "def helper() -> None:\n return None\n", "app/enum_use.py": "from enum import StrEnum\n", "tests/test_login.py": "TOKEN = \"test-token-123\"\n", - "app/paths_only.py": "from pathlib import Path\n\n\ndef where(p):\n return Path(p).resolve()\n" + "app/paths_only.py": "from pathlib import Path\n\n\ndef where(p):\n return Path(p).resolve()\n", + "app/shell.py": "import os\n\ndef run(cmd):\n os.system(cmd)\n" }, "real_defects": [ { @@ -195,6 +196,13 @@ "severity": "MEDIUM", "title": "Unvalidated module constant", "description": "The line number is past the end of the file, as a model's own count can be." + }, + { + "id": "shell-injection", + "location": "app/shell.py:4", + "severity": "HIGH", + "title": "Command injection via os.system", + "description": "`run` passes its `cmd` argument to `os.system` unquoted." } ], "distinct_groups": [ @@ -346,5 +354,265 @@ ] } } + ], + "fabricated_verdicts": [ + { + "id": "perimeter-does-not-exist", + "finding": { + "location": "app/shell.py:4", + "severity": "HIGH", + "title": "Command injection via os.system", + "description": "`run` passes its `cmd` argument to `os.system` unquoted.", + "fix": "Pass an argument list to subprocess.run without a shell." + }, + "verdict": { + "status": "MITIGATED", + "mitigated": true, + "reason": "Commands are quoted by a wrapper before they reach the shell.", + "mitigating_mechanism": "shlex.quote wrapper in safe_exec", + "perimeter_files": [ + "src/does/not/exist.py" + ], + "citation_line": 999 + }, + "status": "UNVERIFIED", + "note": "mitigation-unproven", + "recommendation": "REQUEST CHANGES" + }, + { + "id": "mechanism-names-no-code", + "finding": { + "location": "app/db.py:2-3", + "severity": "CRITICAL", + "title": "SQL injection via f-string", + "description": "`search` interpolates `term` into the query with an f-string.", + "fix": "Pass term as a bound parameter." + }, + "verdict": { + "status": "MITIGATED", + "mitigated": true, + "reason": "Input is validated before it reaches the query.", + "mitigating_mechanism": "Input validation and sanitization", + "perimeter_files": [ + "app/db.py" + ], + "citation_line": 2 + }, + "status": "UNVERIFIED", + "note": "mitigation-unproven", + "recommendation": "BLOCK" + }, + { + "id": "mechanism-describes-the-defect", + "finding": { + "location": "app/errors.py:4", + "severity": "MEDIUM", + "title": "Bare `except` clause swallows KeyboardInterrupt", + "description": "`run` catches every exception with a bare `except` and passes.", + "fix": "Catch Exception and log it." + }, + "verdict": { + "status": "MITIGATED", + "mitigated": true, + "reason": "The except clause in run handles the error.", + "mitigating_mechanism": "The error in `run` is caught but not logged or re-raised", + "perimeter_files": [ + "app/errors.py" + ], + "citation_line": 4 + }, + "status": "UNVERIFIED", + "note": "mitigation-unproven", + "recommendation": "REQUEST CHANGES" + }, + { + "id": "confirmation-cites-past-the-end", + "finding": { + "location": "app/shell.py:4", + "severity": "HIGH", + "title": "Command injection via os.system", + "description": "`run` passes its `cmd` argument to `os.system` unquoted.", + "fix": "Pass an argument list to subprocess.run without a shell." + }, + "verdict": { + "status": "VERIFIED", + "verified": true, + "reason": "os.system(cmd) runs the unquoted command.", + "citation_line": 999 + }, + "status": "UNVERIFIED", + "note": "citation-out-of-range", + "recommendation": "REQUEST CHANGES" + } + ], + "contradicting_verdicts": [ + { + "id": "llm_6818ef36", + "source": "Cached verifier reply llm_6818ef36 (S8, workspace.py:43, ledger row 10050)", + "finding": { + "location": "/workspaces/devops-cli/src/devops_cli/commands/workspace.py:43", + "severity": "MEDIUM", + "title": "[python.lang.security.audit.non-literal-import.non-literal-import] Untrusted user input in `importlib.import_module()` function allows an attacker", + "description": "Semgrep AST flaw (python.lang.security.audit.non-literal-import.non-literal-import) at /workspaces/devops-cli/src/devops_cli/commands/workspace.py:43: Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", + "fix": "Remediate python.lang.security.audit.non-literal-import.non-literal-import. OWASP: ['A01:2021 - Broken Access Control', 'A01:2025 - Broken Access Control']" + }, + "verdict": { + "status": "VERIFIED", + "verified": true, + "mitigated": false, + "invalidated": false, + "citation_line": 43, + "reason": "Line 43 in `__getattr__` function calls `importlib.import_module(mod_path)` where `mod_path` is retrieved from `_LAZY_OBJECT_MAPPING[name]`. The `_LAZY_OBJECT_MAPPING` dictionary (lines 24-37) contains only hardcoded module paths and object names. The `name` parameter comes from the function's argument, but since this is a special method (`__getattr__`) that gets called when an attribute is not found in the module, it's only invoked for valid internal references within the codebase. No user input reaches this point." + }, + "status": "UNVERIFIED", + "note": "verifier-contradiction", + "recommendation": "REQUEST CHANGES" + }, + { + "id": "llm_f3d7fc26", + "source": "Cached verifier reply llm_f3d7fc26 (S8, main.py:84, ledger row 10067)", + "finding": { + "location": "/workspaces/devops-cli/src/devops_cli/main.py:84", + "severity": "MEDIUM", + "title": "[python.lang.security.audit.non-literal-import.non-literal-import] Untrusted user input in `importlib.import_module()` function allows an attacker", + "description": "Semgrep AST flaw (python.lang.security.audit.non-literal-import.non-literal-import) at /workspaces/devops-cli/src/devops_cli/main.py:84: Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", + "fix": "Remediate python.lang.security.audit.non-literal-import.non-literal-import. OWASP: ['A01:2021 - Broken Access Control', 'A01:2025 - Broken Access Control']" + }, + "verdict": { + "status": "VERIFIED", + "verified": true, + "mitigated": false, + "invalidated": false, + "citation_line": 84, + "reason": "Line 84 in `devops_cli/main.py` calls `import_module(module_path)` where `module_path` comes from the `_COMMAND_SPECS` dictionary. The values in this dictionary are hardcoded strings like 'devops_cli.commands.repos', 'devops_cli.commands.ssh', etc., which are defined at lines 33-72. These are not derived from untrusted user input, so the import is not vulnerable to code injection through user-controlled module names." + }, + "status": "UNVERIFIED", + "note": "verifier-contradiction", + "recommendation": "REQUEST CHANGES" + }, + { + "id": "llm_3ec3580c", + "source": "Cached verifier reply llm_3ec3580c (S7, main.py:84)", + "finding": { + "location": "/workspaces/devops-cli/src/devops_cli/main.py:84", + "severity": "MEDIUM", + "title": "[python.lang.security.audit.non-literal-import.non-literal-import] Untrusted user input in `importlib.import_module()` function allows an attacker", + "description": "Semgrep AST flaw (python.lang.security.audit.non-literal-import.non-literal-import) at /workspaces/devops-cli/src/devops_cli/main.py:84: Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", + "fix": "Remediate python.lang.security.audit.non-literal-import.non-literal-import. OWASP: ['A01:2021 - Broken Access Control', 'A01:2025 - Broken Access Control']" + }, + "verdict": { + "status": "MITIGATED", + "verified": false, + "mitigated": true, + "invalidated": false, + "citation_line": 84, + "reason": "Line 84 in main.py calls `import_module(module_path)` where `module_path` is sourced from `_COMMAND_SPECS` dictionary which is defined at lines 33-72. These module paths are hardcoded strings that are part of the project's command structure and not derived from untrusted user input. The delegation mechanism uses a fixed mapping of command names to module paths, ensuring that only pre-defined, trusted modules can be imported. This prevents arbitrary code execution through dynamic imports.", + "mitigating_mechanism": "Command delegation via predefined command specs with trusted module paths", + "perimeter_files": [ + "/workspaces/devops-cli/src/devops_cli/main.py" + ] + }, + "status": "UNVERIFIED", + "note": "verifier-contradiction", + "recommendation": "REQUEST CHANGES" + }, + { + "id": "llm_54a55488", + "source": "Cached verifier reply llm_54a55488 (S7, release.py:60)", + "finding": { + "location": "/workspaces/devops-cli/src/devops_cli/commands/release.py:60", + "severity": "MEDIUM", + "title": "[python.lang.security.audit.non-literal-import.non-literal-import] Untrusted user input in `importlib.import_module()` function allows an attacker", + "description": "Semgrep AST flaw (python.lang.security.audit.non-literal-import.non-literal-import) at /workspaces/devops-cli/src/devops_cli/commands/release.py:60: Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", + "fix": "Remediate python.lang.security.audit.non-literal-import.non-literal-import. OWASP: ['A01:2021 - Broken Access Control', 'A01:2025 - Broken Access Control']" + }, + "verdict": { + "status": "MITIGATED", + "verified": false, + "mitigated": true, + "invalidated": false, + "citation_line": 60, + "reason": "Line 60 in `__getattr__` uses `importlib.import_module(mod_path)` where `mod_path` comes from `_LAZY_OBJECT_MAPPING`, a controlled dictionary defined within the same file. The keys are hardcoded strings and the values are tuples of module paths and object names that are also hardcoded. Since these mappings are not derived from untrusted input, this is not vulnerable to arbitrary code execution.", + "mitigating_mechanism": "Controlled import mapping", + "perimeter_files": [ + "/workspaces/devops-cli/src/devops_cli/commands/release.py" + ] + }, + "status": "UNVERIFIED", + "note": "verifier-contradiction", + "recommendation": "REQUEST CHANGES" + }, + { + "id": "llm_952922a2", + "source": "Cached verifier reply llm_952922a2 (S7, indexer.py:12); its reason denies one word of the claim ('not the actual secret'), below the two a denial needs, and its perimeter is the conventions file", + "finding": { + "location": "/workspaces/devops-cli/src/devops_cli/ai/rag/indexer.py:12", + "severity": "LOW", + "title": "[python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure] Detected a python logger call with a potential hardcoded secret \"Failed to resol", + "description": "Semgrep AST flaw (python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure) at /workspaces/devops-cli/src/devops_cli/ai/rag/indexer.py:353-355: Detected a python logger call with a potential hardcoded secret \"Failed to resolve Qdrant API key from keyring: %s\" being logged. This may lead to secret credentials being exposed. Make sure that the logger is not logging sensitive information.", + "fix": "Remediate python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure. OWASP: ['A09:2021 - Security Logging and Monitoring Failures', 'A09:2025 - Security Logging & Alerting Failures']" + }, + "verdict": { + "status": "MITIGATED", + "verified": false, + "mitigated": true, + "invalidated": false, + "citation_line": 354, + "reason": "Line 354 in the code shows `logger.debug(\"Failed to resolve Qdrant API key from keyring: %s\", type(err).__name__)`. This is a debug log message that only outputs the exception type name, not the actual secret. According to project convention (in .devops/review.md), debug logging of paths under inspection or progress indicators is not considered information exposure. The code does not log any actual secrets or credentials.", + "mitigating_mechanism": "Project convention states that information-exposure claims about terminal output, debug logging of paths under inspection, or progress indicators are not defects", + "perimeter_files": [ + ".devops/review.md" + ] + }, + "status": "UNVERIFIED", + "note": "mitigation-unproven", + "recommendation": "REQUEST CHANGES" + }, + { + "id": "llm_4617de34", + "source": "Cached verifier reply llm_4617de34 (S7, test_security_bandit.py:142-154, finding 2 of the reply)", + "finding": { + "location": "tests/test_security_bandit.py:142-154", + "severity": "MEDIUM", + "title": "Insecure Mocking of Bandit Process Output", + "description": "The test `test_bandit_asks_for_quiet_output_in_every_command_shape` relies on mocking `run_subprocess` with a fake implementation that does not fully simulate real-world behavior. Specifically, it assumes all commands will be passed the `-q` flag but doesn't validate that this is actually enforced in all command shapes, which could lead to incorrect assumptions about Bandit's behavior under different conditions.", + "fix": "Ensure that the mocking correctly simulates actual Bandit execution by verifying that each command shape includes `-q` and also checking that other flags are handled appropriately. Consider using a more robust approach such as running a real Bandit instance in a controlled environment with known inputs to validate behavior.", + "verification_criteria": [ + { + "command": null, + "description": "Each command shape must include the `-q` flag to suppress progress bar output.", + "executable": false + } + ], + "invalidation_criteria": [ + { + "command": "python -c \"from tests.test_security_bandit import test_bandit_asks_for_quiet_output_in_every_command_shape; import tempfile; from pathlib import Path; t = tempfile.TemporaryDirectory(); p = Path(t.name); (p / 'app.py').write_text('x = 1'); test_bandit_asks_for_quiet_output_in_every_command_shape(p); t.cleanup()\"", + "description": "python -c \"from tests.test_security_bandit import test_bandit_asks_for_quiet_output_in_every_command_shape; import tempfile; from pathlib import Path; t = tempfile.TemporaryDirectory(); p = Path(t.name); (p / 'app.py').write_text('x = 1'); test_bandit_asks_for_quiet_output_in_every_command_shape(p); t.cleanup()\"", + "executable": true + } + ], + "criteria_execution_results": [ + { + "command": "python -c \"from tests.test_security_bandit import test_bandit_asks_for_quiet_output_in_every_command_shape; import tempfile; from pathlib import Path; t = tempfile.TemporaryDirectory(); p = Path(t.name); (p / 'app.py').write_text('x = 1'); test_bandit_asks_for_quiet_output_in_every_command_shape(p); t.cleanup()\"", + "description": "python -c \"from tests.test_security_bandit import test_bandit_asks_for_quiet_output_in_every_command_shape; import tempfile; from pathlib import Path; t = tempfile.TemporaryDirectory(); p = Path(t.name); (p / 'app.py').write_text('x = 1'); test_bandit_asks_for_quiet_output_in_every_command_shape(p); t.cleanup()\"", + "executable": true, + "exit_code": 1, + "passed": false, + "stderr": "ModuleNotFoundError: No module named 'pytest'\n" + } + ] + }, + "verdict": { + "status": "VERIFIED", + "verified": true, + "mitigated": false, + "invalidated": false, + "citation_line": 142, + "reason": "The test `test_bandit_asks_for_quiet_output_in_every_command_shape` correctly verifies that each command shape passes the `-q` flag. Lines 148-153 in the code show the construction of commands using `scanner.build_command()` for different target types (file list, single file, directory), and line 154 asserts that all three commands contain `-q`. This is verified by the test execution which passes, confirming that the mocking correctly simulates Bandit's behavior with the `-q` flag." + }, + "status": "UNVERIFIED", + "note": "verifier-contradiction", + "recommendation": "REQUEST CHANGES" + } ] } diff --git a/tests/test_review_project_conventions.py b/tests/test_review_project_conventions.py index 04fb918844..5b436ed7a0 100644 --- a/tests/test_review_project_conventions.py +++ b/tests/test_review_project_conventions.py @@ -522,10 +522,15 @@ def test_the_verifier_prompt_shows_conventions_only_when_there_are_some() -> Non ) == (True, False) -def test_a_mitigated_finding_is_reported_with_its_mitigation() -> None: +def test_a_mitigated_finding_is_reported_with_its_mitigation(tmp_path: Path) -> None: """Verify a confirmed defect the verifier calls mitigated stays in the report, reason shown.""" from devops_cli.ai.review.verification import _apply_single_finding_verification + (tmp_path / "paths.py").write_text( + "def safe_resolve_subpath(base, name):\n if (base / name).is_symlink():\n" + " raise PermissionError(name)\n", + encoding="utf-8", + ) finding = Finding( severity="HIGH", location="paths.py:40", @@ -535,12 +540,12 @@ def test_a_mitigated_finding_is_reported_with_its_mitigation() -> None: verdict = { "title": finding.title, "mitigated": True, - "mitigating_mechanism": "SymlinkCheck", + "mitigating_mechanism": "The `is_symlink` check", "perimeter_files": ["paths.py"], "reason": "Symlinks are rejected at line 31, which limits but does not stop `../`.", } - result = _apply_single_finding_verification(finding, verdict, "t") + result = _apply_single_finding_verification(finding, verdict, "t", repo_root=tmp_path) saved = SavedFinding(**result.model_dump(), persona="devsecops") section = ReviewPipelineOrchestrator._build_detailed_findings_section([saved]) diff --git a/tests/test_review_regression_harness.py b/tests/test_review_regression_harness.py index 3d6d6dc93c..e25f39947f 100644 --- a/tests/test_review_regression_harness.py +++ b/tests/test_review_regression_harness.py @@ -13,7 +13,9 @@ 5. the report's own filter. It must come out reported. A change that makes any layer discard a real finding fails here. Each -known false alarm must still be invalidated by the deterministic layer. +known false alarm must still be invalidated by the deterministic layer, and a verifier verdict +that points at evidence the golden files do not hold, or that its own reason contradicts, must +leave its defect reported (#845). """ from __future__ import annotations @@ -25,6 +27,7 @@ import pytest from devops_cli.ai.review import ReviewPipelineOrchestrator +from devops_cli.ai.review.verdicts import assert_verdict_invariants from devops_cli.ai.review.verification import ( _apply_single_finding_verification, _deterministic_pre_verification, @@ -34,6 +37,7 @@ Finding, SavedFinding, consolidate_duplicate_findings, + derive_recommendation, parse_review_response, reset_verification_state, ) @@ -127,3 +131,46 @@ def test_a_verdict_restating_the_defect_does_not_remove_it(case: dict[str, Any]) result = _apply_single_finding_verification(finding, case["verdict"], "2026-09-25T00:00:00Z") assert (result.status in _DISMISSED, result.reportable) == (False, True) + + +@pytest.mark.parametrize("case", _GOLDEN["fabricated_verdicts"], ids=lambda c: c["id"]) +def test_a_verdict_pointing_at_no_evidence_leaves_the_defect_reported( + case: dict[str, Any], project: Path +) -> None: + """Verify a mitigation or confirmation the golden files do not back keeps the finding (#845).""" + finding = Finding(**case["finding"]) + + result = _apply_single_finding_verification( + finding, case["verdict"], "2026-10-03T00:00:00Z", repo_root=project + ) + assert_verdict_invariants([result]) + + assert ( + result.status, + result.reportable, + (result.verification_note or "").split(":", 1)[0], + derive_recommendation([result]), + ) == (case["status"], True, case["note"], case["recommendation"]) + + +@pytest.mark.parametrize("case", _GOLDEN["contradicting_verdicts"], ids=lambda c: c["id"]) +def test_a_verdict_its_own_reason_contradicts_is_not_applied( + case: dict[str, Any], project: Path +) -> None: + """Verify a cached confirmation or mitigation whose reason denies the claim, or says a failed + criterion passed, leaves its finding unverified and reported (#845).""" + finding = Finding(**case["finding"]) + + result = _apply_single_finding_verification( + finding, case["verdict"], "2026-10-03T00:00:00Z", repo_root=project + ) + assert_verdict_invariants([result]) + + assert ( + result.status, + result.reportable, + result.verified_by, + result.citation_line, + (result.verification_note or "").split(":", 1)[0], + derive_recommendation([result]), + ) == (case["status"], True, None, None, case["note"], case["recommendation"]) diff --git a/tests/test_review_verification.py b/tests/test_review_verification.py index b3aee313d0..b0461a7ebf 100644 --- a/tests/test_review_verification.py +++ b/tests/test_review_verification.py @@ -375,7 +375,7 @@ def test_format_related_file_block(tmp_path: Path) -> None: "mitigated": True, "verified": False, "reason": "Input is bounded at line 12.", - "mitigating_mechanism": "BoundedInputValidator", + "mitigating_mechanism": "`BoundedInputValidator`", "perimeter_files": ["src/validator.py"], }, "MITIGATED", @@ -418,9 +418,14 @@ def test_apply_single_finding_verification( expected_reportable: bool, expected_verified: bool, expected_conf: float | None, + tmp_path: Path, ) -> None: from devops_cli.ai.review.verification import _apply_single_finding_verification + # The perimeter a mitigation names must hold its mechanism in the reviewed tree (#845). + (tmp_path / "src").mkdir() + (tmp_path / "src/validator.py").write_text("class BoundedInputValidator: ...\n", "utf-8") + f = Finding( title="Test Finding", location="test.py:10", @@ -431,7 +436,7 @@ def test_apply_single_finding_verification( ) now_iso = "2026-08-26T00:00:00" - res = _apply_single_finding_verification(f, item, now_iso) + res = _apply_single_finding_verification(f, item, now_iso, repo_root=tmp_path) actual_verified = res.verified if item is not None else expected_verified actual_conf = res.confidence_score if expected_conf is not None else None assert (res.status, res.reportable, actual_verified, actual_conf) == ( @@ -1423,7 +1428,7 @@ def test_an_unadjudicated_finding_is_not_exported_as_human_reviewed() -> None: { "status": "MITIGATED", "reason": "Quota checked at line 40.", - "mitigating_mechanism": "QuotaChecker", + "mitigating_mechanism": "`QuotaChecker`", "perimeter_files": ["src/quota.py"], }, ("MITIGATED", True), @@ -1431,13 +1436,17 @@ def test_an_unadjudicated_finding_is_not_exported_as_human_reviewed() -> None: ], ) def test_verdicts_are_read_as_the_model_meant_them( - item: dict[str, Any], expected: tuple[str, bool] + item: dict[str, Any], expected: tuple[str, bool], tmp_path: Path ) -> None: """Verify string flags, "none" criteria and contradictions never discard a finding by accident.""" from devops_cli.ai.review.verification import _apply_single_finding_verification + (tmp_path / "src").mkdir() + (tmp_path / "src/quota.py").write_text("class QuotaChecker: ...\n", encoding="utf-8") finding = Finding(title="SQL injection in search", location="app.py:10", severity="HIGH") - result = _apply_single_finding_verification(finding, item, "2026-09-24T00:00:00") + result = _apply_single_finding_verification( + finding, item, "2026-09-24T00:00:00", repo_root=tmp_path + ) assert (result.status, result.reportable) == expected diff --git a/tests/test_verdict_writers.py b/tests/test_verdict_writers.py index 9060b1bc82..72a16145df 100644 --- a/tests/test_verdict_writers.py +++ b/tests/test_verdict_writers.py @@ -22,6 +22,7 @@ _validate_segment_findings, ) from devops_cli.ai.review_schema import ( + CriterionExecutionResult, FileReviewPayload, Finding, ReviewResult, @@ -267,34 +268,35 @@ def test_citation_line_validation_downgrade(tmp_path: Path) -> None: ) == ("INVALIDATED", False, False, "llm", 3) -def test_mitigating_mechanism_annotation() -> None: +def test_mitigating_mechanism_annotation(tmp_path: Path) -> None: """Mitigated verdicts without mechanism degrade to UNVERIFIED with notes.""" + (tmp_path / "q.py").write_text("LIMIT = BoundedSemaphore(10)\n", encoding="utf-8") f = Finding(title="Unbounded queue", location="q.py:10", severity="MEDIUM") item_no_mech = {"status": "MITIGATED", "reason": "Bounded elsewhere"} - res_no_mech = _apply_single_finding_verification(f, item_no_mech, "now") + res_no_mech = _apply_single_finding_verification(f, item_no_mech, "now", repo_root=tmp_path) assert ( res_no_mech.status, res_no_mech.reportable, res_no_mech.mitigated, - "without specified mitigating mechanism" in (res_no_mech.verification_note or ""), - ) == ("UNVERIFIED", True, False, True) + res_no_mech.verification_note, + ) == ("UNVERIFIED", True, False, "mitigation-unproven: no mitigating mechanism named") item_with_mech = { "status": "MITIGATED", - "mitigating_mechanism": "BoundedSemaphore(10)", + "mitigating_mechanism": "`BoundedSemaphore(10)`", "perimeter_files": ["q.py"], "citation_line": 15, "reason": "Bounded by semaphore", } - res_with_mech = _apply_single_finding_verification(f, item_with_mech, "now") + res_with_mech = _apply_single_finding_verification(f, item_with_mech, "now", repo_root=tmp_path) assert ( res_with_mech.status, res_with_mech.reportable, res_with_mech.mitigated, res_with_mech.mitigating_mechanism, res_with_mech.citation_line, - ) == ("MITIGATED", True, True, "BoundedSemaphore(10)", 15) + ) == ("MITIGATED", True, True, "`BoundedSemaphore(10)`", 15) def test_compute_verdict_distributions_citation_rates() -> None: @@ -416,7 +418,7 @@ def test_review_verify_cli_command(tmp_path: Path, monkeypatch: pytest.MonkeyPat assert (f_mit.status, f_mit.reportable, f_mit.verified, f_mit.mitigated, f_mit.verified_by) == ( "MITIGATED", True, - True, + False, True, "human", ) @@ -649,3 +651,552 @@ def test_a_file_whose_verification_raised_says_why_its_findings_have_no_verdict( 6, {"verification-unavailable": 2, "verifier-no-verdict": 2}, ) + + +# ── Verdicts point at evidence the reviewed tree holds (#845) ──────────────────────────────── + +# The probe of #845: a four-line file whose command injection a verifier called mitigated by a +# wrapper in a file that does not exist, citing line 999. +_SHELL_SOURCE = "import os\n\ndef run(cmd):\n os.system(cmd)\n" +_SAFE_EXEC_SOURCE = ( + "import shlex\n\n\ndef safe_exec(argv):\n return ' '.join(shlex.quote(a) for a in argv)\n" +) + + +@pytest.fixture +def reviewed_tree(tmp_path: Path) -> Path: + """A reviewed tree: the finding's file, a real wrapper, a conventions file and a workflow, + with a file beside the tree that a `../` path reaches.""" + root = tmp_path / "project" + for rel, source in { + "app/shell.py": _SHELL_SOURCE, + "app/safe.py": _SAFE_EXEC_SOURCE, + ".devops/review.md": "Commands go through `safe_exec`.\n", + ".github/workflows/ci.yml": "permissions:\n contents: read\n", + }.items(): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_text(source, encoding="utf-8") + (tmp_path / "outside.py").write_text(_SAFE_EXEC_SOURCE, encoding="utf-8") + return root + + +def _injection() -> Finding: + return Finding( + title="Command injection via os.system", + description="`run` passes `cmd` to `os.system` unquoted.", + location="app/shell.py:4", + severity="HIGH", + ) + + +def _mitigation(mechanism: str, *perimeter: str) -> dict[str, object]: + return { + "status": "MITIGATED", + "mitigated": True, + "reason": "Every command goes through a quoting wrapper.", + "mitigating_mechanism": mechanism, + "perimeter_files": list(perimeter), + "citation_line": 4, + } + + +# A model's confirmation of `_injection`, citing the line that holds the defect. +_CONFIRMATION: dict[str, object] = { + "status": "VERIFIED", + "verified": True, + "reason": "Line 4 passes the unquoted `cmd` argument to os.system.", + "citation_line": 4, +} + + +def _judged( + verdict: dict[str, object], root: Path | None, finding: Finding | None = None +) -> Finding: + judged = _apply_single_finding_verification( + finding or _injection(), verdict, "2026-10-03T00:00:00", repo_root=root + ) + assert_verdict_invariants([judged]) + return judged + + +def _note_kind(f: Finding) -> str: + return (f.verification_note or "").split(":", 1)[0] + + +def test_the_probe_fabricated_mitigation_stays_in_the_report(reviewed_tree: Path) -> None: + """The #845 probe gave MITIGATED, verified_by=llm, no note and APPROVE.""" + from devops_cli.ai.review_schema import derive_recommendation + + verdict = _mitigation("shlex.quote wrapper in safe_exec", "src/does/not/exist.py") + judged = _judged({**verdict, "citation_line": 999}, reviewed_tree) + + assert ( + judged.status, + judged.reportable, + judged.verified_by, + judged.mitigated, + judged.citation_line, + _note_kind(judged), + "src/does/not/exist.py" in (judged.verification_note or ""), + derive_recommendation([judged]), + ) == ("UNVERIFIED", True, None, False, None, "mitigation-unproven", True, "REQUEST CHANGES") + + +@pytest.mark.parametrize( + ("mechanism", "perimeter"), + [ + ("shlex.quote wrapper in safe_exec", "app/safe.py"), + # The identifier may sit in the finding's own file rather than the perimeter. + ("`cmd` comes from a fixed allowlist", "app/safe.py"), + # A `.github/...` perimeter keeps its leading dot and resolves to itself. + ("The workflow sets `contents: read`", ".github/workflows/ci.yml"), + ], + ids=["in-perimeter", "in-finding-file", "dot-github"], +) +def test_a_mitigation_whose_perimeter_exists_and_holds_the_mechanism_stays_mitigated( + mechanism: str, perimeter: str, reviewed_tree: Path +) -> None: + """A mitigation that points at code the tree holds is MITIGATED, reported and not verified.""" + judged = _judged(_mitigation(mechanism, perimeter), reviewed_tree) + + assert ( + judged.status, + judged.reportable, + judged.mitigated, + judged.verified, + judged.verified_by, + judged.perimeter_files, + judged.verification_note, + ) == ("MITIGATED", True, True, False, "llm", [perimeter], None) + + +@pytest.mark.parametrize( + "perimeter", + ["absolute", "../outside.py", "/etc/hostname", "app/missing.py", "app"], + ids=["absolute-inside-tree", "dot-dot-escape", "absolute-outside", "missing", "directory"], +) +def test_a_perimeter_that_does_not_resolve_inside_the_reviewed_tree_is_unresolved( + perimeter: str, reviewed_tree: Path +) -> None: + """An absolute path, even to a file in the tree, or a `../` escape names no perimeter.""" + named = str(reviewed_tree / "app/safe.py") if perimeter == "absolute" else perimeter + judged = _judged(_mitigation("shlex.quote wrapper in safe_exec", named), reviewed_tree) + + assert ( + judged.status, + judged.reportable, + _note_kind(judged), + f"`{named}` does not resolve inside the reviewed tree" in (judged.verification_note or ""), + ) == ("UNVERIFIED", True, "mitigation-unproven", True) + + +# Five mechanisms of session 20261001-224227 that describe the defect rather than a mitigation. +# The perimeter holds each one's identifiers, so only the self-negation can fail. +_SELF_NEGATING_MECHANISMS = ( + "The error is caught but not logged or re-raised", + "Rich library's escape_text function is used for title and location but not for severity label", + "The function already attempts to balance brackets but does not fully sanitize nested or " + "malformed bracket sequences.", + "_check_path_traversal function is expected to handle path traversal checks", + "The test is intended to verify that private IP resolution raises an error, but the mock " + "implementation is too permissive", +) + + +@pytest.mark.parametrize("mechanism", _SELF_NEGATING_MECHANISMS) +def test_a_mechanism_that_describes_the_defect_is_no_mitigation( + mechanism: str, reviewed_tree: Path +) -> None: + """Five of session 20261001-224227's 28 mitigations described the defect itself.""" + (reviewed_tree / "app/guard.py").write_text( + "def escape_text(s): ...\ndef _check_path_traversal(p): ...\n", encoding="utf-8" + ) + judged = _judged(_mitigation(mechanism, "app/guard.py"), reviewed_tree) + + assert ( + judged.status, + judged.reportable, + _note_kind(judged), + "describes the defect" in (judged.verification_note or ""), + ) == ("UNVERIFIED", True, "mitigation-unproven", True) + + +@pytest.mark.parametrize( + ("mechanism", "perimeter", "check"), + [ + # 18 of the session's 28 mechanisms named no code identifier. + ("Input validation and sanitization", "app/safe.py", "names no code identifier"), + # 2 of its perimeters were the conventions file; it holds `safe_exec` here. + ("shlex.quote wrapper in safe_exec", ".devops/review.md", "is documentation"), + ("`quote_all` wrapper", "app/safe.py", "none of its identifiers"), + ], + ids=["no-identifier", "conventions-file", "identifier-absent"], +) +def test_a_mitigation_pointing_at_no_code_that_enforces_it_is_unproven( + mechanism: str, perimeter: str, check: str, reviewed_tree: Path +) -> None: + """The note names the check that failed.""" + judged = _judged(_mitigation(mechanism, perimeter), reviewed_tree) + + assert ( + judged.status, + judged.reportable, + _note_kind(judged), + check in (judged.verification_note or ""), + ) == ("UNVERIFIED", True, "mitigation-unproven", True) + + +@pytest.mark.parametrize( + ("citation", "expected"), + [ + (999, ("UNVERIFIED", None, "citation-out-of-range", True)), + (0, ("UNVERIFIED", None, "citation-out-of-range", True)), + (4, ("VERIFIED", "llm", "", True)), + (None, ("VERIFIED", "llm", "", True)), + ], + ids=["past-the-end", "line-zero", "in-range", "no-citation"], +) +def test_a_confirmation_citing_a_line_outside_the_file_is_unverified( + citation: int | None, expected: tuple[str, str | None, str, bool], reviewed_tree: Path +) -> None: + """A model VERIFIED verdict citing line 999 of a four-line file passed unchecked.""" + verdict = {"status": "VERIFIED", "verified": True, "reason": "os.system(cmd) on line 4."} + judged = _judged({**verdict, "citation_line": citation}, reviewed_tree) + + assert ( + judged.status, + judged.verified_by, + _note_kind(judged), + judged.reportable, + ) == expected + + +@pytest.mark.parametrize( + ("located", "verdict", "expected"), + [ + ( + "in-tree", + {**_CONFIRMATION, "citation_line": 999}, + ("UNVERIFIED", None, "citation-out-of-range: line 999 of `{path}` (4 lines)"), + ), + ( + "in-tree", + _mitigation("`cmd` comes from a fixed allowlist", "app/safe.py"), + ("MITIGATED", 4, None), + ), + # A file outside the reviewed tree is not read: the confirmation is left as it was. + ("outside", {**_CONFIRMATION, "citation_line": 999}, ("VERIFIED", 999, None)), + ], + ids=["past-the-end", "identifier-in-finding-file", "outside-the-tree"], +) +def test_a_finding_located_by_an_absolute_path_is_read_from_the_reviewed_tree( + located: str, + verdict: dict[str, object], + expected: tuple[str, int | None, str | None], + reviewed_tree: Path, +) -> None: + """A scanner writes its finding's location absolute; the checks read that file as they read a + relative one, and refuse only a file outside the tree.""" + path = ( + reviewed_tree / "app/shell.py" + if located == "in-tree" + else reviewed_tree.parent / "outside.py" + ).resolve() + finding = _injection().model_copy(update={"location": f"{path}:4"}) + + judged = _judged(verdict, reviewed_tree, finding) + + status, citation, note = expected + assert (judged.status, judged.citation_line, judged.verification_note) == ( + status, + citation, + note.format(path=path) if note else None, + ) + + +# Reasons that deny the claim they confirm or mitigate: the session 20261003-012555 confirmation +# of a Semgrep finding (cache llm_6818ef36), and the same denial of `_injection`'s claim. +_IMPORT_CLAIM = Finding( + title="[python.lang.security.audit.non-literal-import.non-literal-import] Untrusted user " + "input in `importlib.import_module()` function allows an attacker", + location="app/shell.py:4", + severity="MEDIUM", +) + + +@pytest.mark.parametrize( + ("finding", "verdict", "denial"), + [ + ( + _IMPORT_CLAIM, + { + **_CONFIRMATION, + "reason": "The mapping is hardcoded. No user input reaches this point.", + }, + "no user input", + ), + ( + _IMPORT_CLAIM, + {**_CONFIRMATION, "reason": "These are not derived from untrusted user input."}, + "not derived from untrusted user input", + ), + # A mitigation whose perimeter holds its mechanism, but whose reason argues the defect + # away. + ( + None, + { + **_mitigation("shlex.quote wrapper in safe_exec", "app/safe.py"), + "reason": "No command injection is possible: every command goes through safe_exec.", + }, + "no command injection", + ), + ], + ids=["verified-no-user-input", "verified-not-derived-from", "mitigated-provable"], +) +def test_a_verdict_whose_reason_denies_the_claim_is_not_applied( + finding: Finding | None, verdict: dict[str, object], denial: str, reviewed_tree: Path +) -> None: + """The mirror of a self-refutation: a confirmation or mitigation whose own reason denies the + claim leaves the finding unverified and reported, with the denial in its note.""" + judged = _judged(verdict, reviewed_tree, finding) + + assert ( + judged.status, + judged.reportable, + judged.verified_by, + judged.citation_line, + judged.mitigated, + _note_kind(judged), + f"denies the claim ('{denial}')" in (judged.verification_note or ""), + ) == ("UNVERIFIED", True, None, None, False, "verifier-contradiction", True) + + +def _criterion_run(passed: bool) -> CriterionExecutionResult: + return CriterionExecutionResult( + command="python -c 'import app.shell'", + executable=True, + exit_code=0 if passed else 1, + passed=passed, + ) + + +@pytest.mark.parametrize( + ("runs", "expected"), + [ + ([False], ("UNVERIFIED", None, "verifier-contradiction")), + # A criterion that passed, or none run, leaves the reason's claim standing. + ([True], ("VERIFIED", "llm", "")), + ([False, True], ("VERIFIED", "llm", "")), + ([], ("VERIFIED", "llm", "")), + ], + ids=["failed", "passed", "one-passed", "none-run"], +) +def test_a_confirmation_saying_a_failed_criterion_passed_is_not_applied( + runs: list[bool], expected: tuple[str, str | None, str], reviewed_tree: Path +) -> None: + """Session 20261003-005122 confirmed a finding "by the test execution which passes" when that + criterion had failed with `No module named 'pytest'` (cache llm_4617de34).""" + finding = _injection().model_copy( + update={"criteria_execution_results": [_criterion_run(passed) for passed in runs]} + ) + reason = "Line 4 calls os.system, verified by the test execution which passes, confirming it." + + judged = _judged({**_CONFIRMATION, "reason": reason}, reviewed_tree, finding) + + assert (judged.status, judged.verified_by, _note_kind(judged)) == expected + + +@pytest.mark.parametrize( + ("title", "reason"), + [ + ( + "Command injection via os.system", + "Line 4 passes the unquoted `cmd` argument to os.system; no shlex.quote or allowlist " + "guards it.", + ), + # A negated verb: the plain mirror of the self-refutation guard (claim overlap of 0.6 and + # any negation) set aside 318 of 778 cached confirmations and mitigations, this one too + # (cache llm_7b99d901). + ( + "Path Traversal Vulnerability in Custom Persona Loading", + "`Path(persona_name).name` extracts a filename, but this does not prevent path " + "traversal attempts like '../evil.md'.", + ), + # The claim negates the words the reason negates. + ( + "Missing input validation in run", + "run passes cmd to os.system with no input validation.", + ), + ( + "TLS verification disabled in the HTTP client", + "Line 4 sets verify=False, so there is no TLS verification.", + ), + ( + "Command injection via os.system", + "os.system(cmd) runs it without any quoting, and the verification command passes the " + "shell metacharacters through.", + ), + ], + ids=[ + "no-negation", + "negated-verb", + "claim-says-missing", + "claim-says-disabled", + "passes-as-a-verb", + ], +) +def test_a_confirmation_whose_reason_supports_the_claim_is_still_applied( + title: str, reason: str, reviewed_tree: Path +) -> None: + """A supporting confirmation stays VERIFIED, even when its reason negates a guard; a + criterion that failed does not make "passes the ... through" a claim that it passed.""" + finding = _injection().model_copy( + update={"title": title, "criteria_execution_results": [_criterion_run(False)]} + ) + + judged = _judged({**_CONFIRMATION, "reason": reason}, reviewed_tree, finding) + + assert (judged.status, judged.verified_by, judged.citation_line, judged.verification_note) == ( + "VERIFIED", + "llm", + 4, + None, + ) + + +def test_one_fabricated_verdict_leaves_the_rest_of_the_reply_as_it_was( + reviewed_tree: Path, +) -> None: + """Checks are per verdict: the reply is read once and its valid verdicts stand.""" + findings = [ + _injection(), + _injection().model_copy(update={"title": "Unquoted shell argument in run"}), + _injection().model_copy(update={"title": "os.system used instead of subprocess"}), + ] + client = MagicMock() + client.chat.return_value = json.dumps( + [ + {"finding_id": 1, **_mitigation("safe_exec", "src/does/not/exist.py")}, + {"finding_id": 2, **_mitigation("shlex.quote wrapper in safe_exec", "app/safe.py")}, + {"finding_id": 3, "status": "VERIFIED", "verified": True, "citation_line": 4}, + ] + ) + + result, _, _ = _validate_segment_findings( + ReviewResult(findings=findings), [_SHELL_SOURCE], client, repo_root=reviewed_tree + ) + assert_verdict_invariants(result.findings) + + assert ( + [(f.status, f.reportable, _note_kind(f)) for f in result.findings], + client.chat.call_count, + ) == ( + [ + ("UNVERIFIED", True, "mitigation-unproven"), + ("MITIGATED", True, ""), + ("VERIFIED", True, ""), + ], + 1, + ) + + +def test_the_verdict_distributions_count_degraded_mitigations(reviewed_tree: Path) -> None: + """profile.json counts mitigations that pointed at no evidence, those naming none, and + verdicts whose reason contradicts them.""" + judged = [ + _judged(_mitigation("safe_exec", "src/does/not/exist.py"), reviewed_tree), + _judged(_mitigation("Input validation and sanitization", "app/safe.py"), reviewed_tree), + _judged({"status": "MITIGATED", "reason": "Bounded elsewhere"}, reviewed_tree), + _judged(_mitigation("safe_exec", "app/safe.py"), reviewed_tree), + _judged({**_CONFIRMATION, "reason": "No command injection reaches os.system."}, None), + ] + + distributions = compute_verdict_distributions(judged) + + assert (distributions["verification_note"], distributions["status"]) == ( + {"mitigation-unproven": 3, "verifier-contradiction": 1}, + {"UNVERIFIED": 4, "MITIGATED": 1}, + ) + + +@pytest.mark.parametrize("by", ["llm", "human", "agent"]) +def test_a_mitigated_finding_is_not_a_verified_one(by: str) -> None: + """Eleven of session 20261001-224227's mitigations carried verified=True.""" + judged = apply_verdict( + Finding(title="t", location="a.py:1"), + "MITIGATED", + by=by, + reason="r", + mitigating_mechanism="m", + perimeter_files=["a.py"], + ) + + assert (judged.status, judged.verified, judged.mitigated, judged.reportable) == ( + "MITIGATED", + False, + True, + True, + ) + + +@pytest.mark.parametrize( + ("perimeter", "changed", "matched"), + [ + (".github/workflows/ci.yml", ".github/workflows/ci.yml", True), + ("./.github/workflows/ci.yml", ".github/workflows/ci.yml", True), + ("./src/app.py", "src/app.py", True), + ("/etc/hostname", "/etc/hostname", True), + # A scanner's absolute path inside the repository is its repository-relative file. + ("{repo}/src/app.py", "src/app.py", True), + ("{repo}/.github/workflows/ci.yml", ".github/workflows/ci.yml", True), + (".github/workflows/ci.yml", "github/workflows/ci.yml", False), + (".devops/review.md", "devops/review.md", False), + # An absolute path outside the repository matches only itself. + ("/etc/hostname", "etc/hostname", False), + ("{elsewhere}/src/app.py", "src/app.py", False), + ("etc/hostname", "/etc/hostname", False), + ], +) +def test_a_perimeter_path_matches_itself_and_no_other_file( + perimeter: str, changed: str, matched: bool, tmp_path: Path +) -> None: + """`.lstrip("./")` cut the dot off `.github/...` and the root off an absolute path.""" + from devops_cli.ai.review.mitigations import ( + MitigatedFindingEntry, + find_perimeter_changes, + save_mitigated_findings, + ) + + repo = tmp_path / "repo" + named = perimeter.format(repo=repo.resolve(), elsewhere=(tmp_path / "elsewhere").resolve()) + ledger = tmp_path / "mitigated_findings.json" + save_mitigated_findings([MitigatedFindingEntry(title="t", perimeter_files=[named])], ledger) + + assert bool(find_perimeter_changes([changed], ledger, repo_root=repo)) is matched + + +def test_a_person_mitigating_a_scanner_finding_is_warned_when_its_file_changes( + tmp_path: Path, +) -> None: + """A person's MITIGATED verdict on a scanner finding records its absolute location as the + perimeter, which a repository-relative changed file must still reach.""" + from devops_cli.ai.review.mitigations import find_perimeter_changes, record_mitigated_finding + + repo = (tmp_path / "repo").resolve() + ledger = tmp_path / "mitigated_findings.json" + scanner_finding = Finding( + title="Untrusted user input in `importlib.import_module()`", + location=f"{repo}/src/devops_cli/commands/workspace.py:43", + ) + entry = record_mitigated_finding(scanner_finding, reason="fixed mapping", ledger_path=ledger) + + assert ( + entry.perimeter_files, + [ + e.id + for e, _ in find_perimeter_changes( + ["src/devops_cli/commands/workspace.py"], ledger, repo_root=repo + ) + ], + find_perimeter_changes(["src/devops_cli/commands/other.py"], ledger, repo_root=repo), + ) == ([f"{repo}/src/devops_cli/commands/workspace.py"], [entry.id], [])