diff --git a/.github/workflows/test-github-action.yml b/.github/workflows/test-github-action.yml index 38875523..1491b3f0 100644 --- a/.github/workflows/test-github-action.yml +++ b/.github/workflows/test-github-action.yml @@ -227,6 +227,125 @@ jobs: fi echo "PASS: the results fetch retried and completed." + # sable-fgk7 — the results step used to coerce EVERY failure to read the + # report into findings_count=0, which passes every severity threshold and + # renders ":white_check_mark: No security findings detected". A report the + # action cannot read is not a clean scan. Three shapes, each of which used + # to land as a clean green: schema-valid-but-wrong (parses, no key), not + # JSON at all, and a 200 whose body is an error object. + test-results-unreadable-is-not-clean: + name: "Results: an unreadable report is not a clean scan (${{ matrix.shape }})" + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + shape: [missing-key, not-json, error-object] + steps: + - uses: actions/checkout@v4 + + - name: Start mock backend (poll completes; results body is ${{ matrix.shape }}) + env: + PORT: '8791' + FAIL_COUNT: '0' + COMPLETE_AFTER: '1' + RESULTS_SHAPE: ${{ matrix.shape }} + run: | + nohup python3 github-action/tests/mock-rafter-api.py > mock.log 2>&1 & + for _ in $(seq 1 30); do + curl -sf -X POST -d '{}' http://127.0.0.1:8791/api/static/scan >/dev/null && break + sleep 1 + done + curl -sf -X POST -d '{}' http://127.0.0.1:8791/api/static/scan >/dev/null || { + echo "FAIL: mock backend never started"; cat mock.log; exit 1; } + + - name: Run the action against the mock + id: scan + continue-on-error: true + uses: ./github-action + with: + api-key: 'not-a-real-key' + rafter-url: 'http://127.0.0.1:8791' + timeout-minutes: '2' + upload-sarif: 'false' + comment-on-pr: 'false' + + - name: Assert the build failed and no count was fabricated + run: | + cat mock.log + FAIL=0 + if [ "${{ steps.scan.outcome }}" != "failure" ]; then + echo "FAIL: an unreadable report must fail the build (outcome='${{ steps.scan.outcome }}')." + FAIL=1 + fi + if [ "${{ steps.scan.outputs.status }}" != "unreadable" ]; then + echo "FAIL: expected status=unreadable, got '${{ steps.scan.outputs.status }}'." + FAIL=1 + fi + # The floor: a count that was never computed must be ABSENT, not 0. + # '0' here is the bug — it is what a consumer gating on the output + # reads as a clean scan. + if [ -n "${{ steps.scan.outputs.findings-count }}" ]; then + echo "FAIL: findings-count was fabricated as '${{ steps.scan.outputs.findings-count }}' from an unreadable report." + FAIL=1 + fi + [ "$FAIL" -eq 0 ] && echo "PASS: unreadable report (${{ matrix.shape }}) failed the build with status=unreadable and no counts." + exit $FAIL + + # The other half of the floor: when the report IS readable the counts must be + # exactly the report's and the build must pass. Without this, a "validation" + # that rejected everything would also land green above. + test-results-counts-exact: + name: "Results: counts are exactly the report's" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Start mock backend (poll completes; report has 3 findings) + env: + PORT: '8792' + FAIL_COUNT: '0' + COMPLETE_AFTER: '1' + RESULTS_SHAPE: 'with-findings' + run: | + nohup python3 github-action/tests/mock-rafter-api.py > mock.log 2>&1 & + for _ in $(seq 1 30); do + curl -sf -X POST -d '{}' http://127.0.0.1:8792/api/static/scan >/dev/null && break + sleep 1 + done + curl -sf -X POST -d '{}' http://127.0.0.1:8792/api/static/scan >/dev/null || { + echo "FAIL: mock backend never started"; cat mock.log; exit 1; } + + - name: Run the action against the mock + id: scan + continue-on-error: true + uses: ./github-action + with: + api-key: 'not-a-real-key' + rafter-url: 'http://127.0.0.1:8792' + timeout-minutes: '2' + upload-sarif: 'false' + comment-on-pr: 'false' + + - name: Assert every count is the report's, not a default + run: | + cat mock.log + FAIL=0 + check() { + if [ "$2" != "$3" ]; then + echo "FAIL: $1 expected '$3', got '$2'" + FAIL=1 + fi + } + check outcome "${{ steps.scan.outcome }}" "success" + check status "${{ steps.scan.outputs.status }}" "completed" + check findings-count "${{ steps.scan.outputs.findings-count }}" "3" + check critical-count "${{ steps.scan.outputs.critical-count }}" "1" + check high-count "${{ steps.scan.outputs.high-count }}" "1" + check medium-count "${{ steps.scan.outputs.medium-count }}" "0" + check low-count "${{ steps.scan.outputs.low-count }}" "1" + [ "$FAIL" -eq 0 ] && echo "PASS: counts are exactly the report's (3/1/1/0/1)." + exit $FAIL + test-yaml-validity: name: action.yml is valid YAML runs-on: ubuntu-latest diff --git a/github-action/README.md b/github-action/README.md index e9d94c15..eec9bf02 100644 --- a/github-action/README.md +++ b/github-action/README.md @@ -53,12 +53,12 @@ jobs: | Output | Description | |--------|-------------| | `scan-id` | The Rafter scan ID | -| `findings-count` | Total findings | +| `findings-count` | Total findings. Empty, never `0`, when the report could not be read (see `status`) | | `critical-count` | Critical severity findings | | `high-count` | High severity findings | | `medium-count` | Medium severity findings | | `low-count` | Low severity findings | -| `status` | Scan status | +| `status` | `completed`, `failed`, `timeout`, `unreadable` (the scan may have finished but its report could not be read or parsed), or `unreachable` (the API could not be contacted). Count outputs are only written when `completed` | ## Examples diff --git a/github-action/action.yml b/github-action/action.yml index e096efad..8193cc98 100644 --- a/github-action/action.yml +++ b/github-action/action.yml @@ -303,13 +303,28 @@ runs: fetch_results "${{ runner.temp }}/rafter-results.md" "${RAFTER_URL}/api/static/scan?scan_id=${SCAN_ID}&format=md" fetch_results "${{ runner.temp }}/rafter-results.sarif" "${RAFTER_URL}/api/static/scan?scan_id=${SCAN_ID}&format=sarif" - # Extract counts + # A report this step cannot read is NOT a clean scan (sable-fgk7). + # Every count below used to fall back to 0 on any jq failure, so a + # malformed body, a truncated write, or a 200 carrying an error object + # rendered as ":white_check_mark: No security findings detected" and + # passed every severity threshold. Validate the shape first. Once it + # holds, the count expressions cannot fail and need no fallback; if + # jq itself is broken the step fails, which is the correct outcome. RESULTS="${{ runner.temp }}/rafter-results.json" - FINDINGS_COUNT=$(jq '.vulnerabilities | length' "$RESULTS" 2>/dev/null || echo "0") - CRITICAL_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "critical")] | length' "$RESULTS" 2>/dev/null || echo "0") - HIGH_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "error" or .severity == "high")] | length' "$RESULTS" 2>/dev/null || echo "0") - MEDIUM_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "warning" or .severity == "medium")] | length' "$RESULTS" 2>/dev/null || echo "0") - LOW_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "note" or .severity == "low")] | length' "$RESULTS" 2>/dev/null || echo "0") + if ! jq -e 'type == "object" and (.vulnerabilities | type == "array") and all(.vulnerabilities[]; type == "object")' "$RESULTS" >/dev/null 2>&1; then + SNIPPET=$(head -c 300 "$RESULTS" 2>/dev/null | tr -d '\r\n' | cut -c1-200 || true) + echo "::error::Rafter returned a report for scan ${SCAN_ID} that this action cannot read: no 'vulnerabilities' array." + echo "::error::A report that cannot be parsed is not a clean scan, so no counts were produced. Check the scan in your dashboard at ${RAFTER_URL}/dashboard or retry with: rafter get ${SCAN_ID}" + echo "::error::Body started with: ${SNIPPET}" + echo "status=unreadable" >> "$GITHUB_OUTPUT" + exit 1 + fi + + FINDINGS_COUNT=$(jq '.vulnerabilities | length' "$RESULTS") + CRITICAL_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "critical")] | length' "$RESULTS") + HIGH_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "error" or .severity == "high")] | length' "$RESULTS") + MEDIUM_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "warning" or .severity == "medium")] | length' "$RESULTS") + LOW_COUNT=$(jq '[.vulnerabilities[] | select(.severity == "note" or .severity == "low")] | length' "$RESULTS") echo "findings_count=${FINDINGS_COUNT}" >> "$GITHUB_OUTPUT" echo "critical_count=${CRITICAL_COUNT}" >> "$GITHUB_OUTPUT" diff --git a/github-action/tests/mock-rafter-api.py b/github-action/tests/mock-rafter-api.py index 2b77ab97..23af6cc5 100644 --- a/github-action/tests/mock-rafter-api.py +++ b/github-action/tests/mock-rafter-api.py @@ -26,6 +26,19 @@ i.e. as soon as the injected failures are done). Set it higher than the failure window to make the RESULTS fetch fail rather than the poll. + RESULTS_SHAPE what the completed JSON body looks like (sable-fgk7). Default + "ok": {"status":"completed","vulnerabilities":[]}. Others: + with-findings three findings: one critical, one high, one low + missing-key {"scan_id":..,"status":"completed"} — parses, + has no vulnerabilities array at all + not-json a 200 whose body is an HTML error page + error-object a 200 whose body is {"error": ...} + Each of the last three used to make the action report + "No security findings detected" and pass every threshold. + SHAPE_FROM GET index from which the JSON body takes RESULTS_SHAPE + (default COMPLETE_AFTER + 1, so the poll loop sees one healthy + "completed" and the RESULTS fetch gets the shaped body). + md/sarif fetches are never shaped. """ import json import os @@ -38,21 +51,47 @@ FAIL_FOREVER = os.environ.get("FAIL_FOREVER") == "1" FAIL_COUNT = int(os.environ.get("FAIL_COUNT", "1")) COMPLETE_AFTER = int(os.environ.get("COMPLETE_AFTER", str(FAIL_ON))) +RESULTS_SHAPE = os.environ.get("RESULTS_SHAPE", "ok") +SHAPE_FROM = int(os.environ.get("SHAPE_FROM", str(COMPLETE_AFTER + 1))) SCAN_ID = "repro-sable-l10k-0001" +# Severities chosen so every count output is pinned to a distinct value: +# findings=3, critical=1, high=1, medium=0, low=1. +WITH_FINDINGS = [ + {"rule_id": "sql-injection", "severity": "critical", "file_path": "db.php", "line_start": 12}, + {"rule_id": "xss-echo", "severity": "high", "file_path": "view.php", "line_start": 40}, + {"rule_id": "weak-hash", "severity": "low", "file_path": "auth.php", "line_start": 7}, +] + state = {"polls": 0} class Handler(BaseHTTPRequestHandler): def _send(self, code, payload): - body = json.dumps(payload).encode() + self._send_raw(code, json.dumps(payload).encode(), "application/json") + + def _send_raw(self, code, body, content_type): self.send_response(code) - self.send_header("Content-Type", "application/json") + self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) + def _send_shaped_results(self): + """The completed JSON body under RESULTS_SHAPE (never for md/sarif).""" + if RESULTS_SHAPE == "with-findings": + return self._send(200, {"scan_id": SCAN_ID, "status": "completed", + "vulnerabilities": WITH_FINDINGS}) + if RESULTS_SHAPE == "missing-key": + return self._send(200, {"scan_id": SCAN_ID, "status": "completed"}) + if RESULTS_SHAPE == "not-json": + return self._send_raw(200, b"

502 Bad Gateway

", + "text/html") + if RESULTS_SHAPE == "error-object": + return self._send(200, {"error": "Failed to fetch report from storage: Object not found"}) + raise SystemExit(f"unknown RESULTS_SHAPE {RESULTS_SHAPE!r}") + def do_POST(self): if urlparse(self.path).path != "/api/static/scan": return self._send(404, {"error": "not found"}) @@ -84,6 +123,9 @@ def do_GET(self): if n < COMPLETE_AFTER: return self._send(200, {"scan_id": SCAN_ID, "status": "processing"}) + if fmt == "json" and RESULTS_SHAPE != "ok" and n >= SHAPE_FROM: + return self._send_shaped_results() + completed = {"scan_id": SCAN_ID, "status": "completed", "vulnerabilities": []} if fmt == "md": completed["markdown"] = "# Rafter\n\nNo findings.\n" diff --git a/github-action/tests/test-action-yml-defaults.sh b/github-action/tests/test-action-yml-defaults.sh index 59444a34..5bc8740e 100755 --- a/github-action/tests/test-action-yml-defaults.sh +++ b/github-action/tests/test-action-yml-defaults.sh @@ -163,6 +163,43 @@ else failures=$((failures+1)) fi +# ── sable-fgk7: an unreadable report is not a clean scan ───────────────── +# The results step used to coerce every jq failure into findings_count=0, +# which passed every threshold and rendered "No security findings detected". +# Reproduced with a 200 whose body was not JSON, a 200 carrying an error +# object, and a parseable payload with no vulnerabilities key. + +# 14. The payload shape must be validated before any count is computed. +if grep -qF "jq -e 'type == \"object\" and (.vulnerabilities | type == \"array\") and all(.vulnerabilities[]; type == \"object\")'" "$ACTION_YML"; then + echo "PASS: results step validates the payload shape before counting" +else + echo "FAIL: results step no longer validates that .vulnerabilities is an array of objects" + failures=$((failures+1)) +fi + +# 15. No count may fall back to 0 on a jq failure. That fallback IS the bug: +# the error path and the clean path produced the same number. +zero_fallbacks=$(grep -c '|| echo "0"' "$ACTION_YML" || true) +if [ "$zero_fallbacks" -eq 0 ]; then + echo "PASS: no count falls back to 0 on a parse failure" +else + echo "FAIL: ${zero_fallbacks} count(s) still fall back to 0 on a jq failure — an unreadable report would render as clean" + failures=$((failures+1)) +fi + +# 16. The unreadable-payload path must record status=unreadable and exit 1, +# so the declared status output cannot fall back to the poll step's +# 'completed' for a report that was never read. +if awk '/no .vulnerabilities. array/,/^ fi$/' "$ACTION_YML" \ + | grep -q 'status=unreadable' \ + && awk '/no .vulnerabilities. array/,/^ fi$/' "$ACTION_YML" \ + | grep -q 'exit 1'; then + echo "PASS: unreadable payload records status=unreadable and fails the step" +else + echo "FAIL: unreadable-payload branch no longer records status=unreadable and exits 1" + failures=$((failures+1)) +fi + echo "" echo "── results ───────────────────────────────────────────────────────────" echo "Failures: $failures" diff --git a/node/src/commands/issues/from-scan.ts b/node/src/commands/issues/from-scan.ts index 38852bcb..f73f2ba5 100644 --- a/node/src/commands/issues/from-scan.ts +++ b/node/src/commands/issues/from-scan.ts @@ -164,6 +164,36 @@ async function runFromScan(opts: { } } +/** + * The findings list from a scan payload, or an error — never a silent []. + * + * A payload without a `vulnerabilities` array is not "no findings". It is a + * scan that has not completed, a failed scan, or a report this client cannot + * read; filing zero issues from it would report a clean codebase for work + * that was never done (sable-fgk7). An empty array IS a legitimate clean + * result and is returned as such. + */ +export function vulnerabilitiesFromPayload( + data: unknown, + scanId: string +): BackendVulnerability[] { + const payload = data as { vulnerabilities?: unknown; status?: unknown } | null; + if (payload && Array.isArray(payload.vulnerabilities)) { + return payload.vulnerabilities as BackendVulnerability[]; + } + const status = payload && typeof payload.status === "string" ? payload.status : undefined; + if (status && status !== "completed") { + throw new Error( + `Scan ${scanId} is ${status}, not completed — there are no findings to file yet. ` + + `Retry once it completes: rafter get ${scanId}` + ); + } + throw new Error( + `Scan ${scanId} returned no 'vulnerabilities' array; refusing to treat an unreadable ` + + `report as zero findings. Check it with: rafter get ${scanId}` + ); +} + async function draftsFromBackendScan( scanId: string, apiKey?: string @@ -174,8 +204,7 @@ async function draftsFromBackendScan( headers: { "x-api-key": key }, }); - const vulns: BackendVulnerability[] = data.vulnerabilities || []; - return vulns.map(buildFromBackendVulnerability); + return vulnerabilitiesFromPayload(data, scanId).map(buildFromBackendVulnerability); } function draftsFromLocalScan(filePath: string): IssueDraft[] { diff --git a/node/tests/issues.test.ts b/node/tests/issues.test.ts index 4e81f423..aca114fa 100644 --- a/node/tests/issues.test.ts +++ b/node/tests/issues.test.ts @@ -2,6 +2,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import crypto from "crypto"; import fs from "fs"; import { execFileSync } from "child_process"; +// The real function, not a mirror: these tests exist to fail when the source +// changes (sable-fgk7, sable-d2x2). +import { vulnerabilitiesFromPayload } from "../src/commands/issues/from-scan.js"; // ── dedup logic (mirrored from src/commands/issues/dedup.ts) ───────── @@ -657,6 +660,61 @@ describe("from-scan: backend vulnerability drafts", () => { }); }); +// ── from-scan: a payload with no findings list is an error, not zero ── +// +// sable-fgk7. `data.vulnerabilities || []` turned a still-running scan, a +// failed scan, a 200 carrying an error object, and a schema-valid payload with +// no key into "No findings to create issues for". Delete-the-subject test: +// with the fallback restored, every case below except the first two passes +// with [] and this suite fails. + +describe("from-scan: vulnerabilitiesFromPayload (sable-fgk7)", () => { + const SCAN = "scan-abc"; + + it("returns the list when present", () => { + const v = [{ ruleId: "r", level: "error", message: "m", file: "f" }]; + expect(vulnerabilitiesFromPayload({ status: "completed", vulnerabilities: v }, SCAN)).toBe(v); + }); + + it("returns an empty list as a legitimate clean result", () => { + expect(vulnerabilitiesFromPayload({ status: "completed", vulnerabilities: [] }, SCAN)).toEqual([]); + }); + + it("refuses a completed payload with no vulnerabilities key", () => { + expect(() => vulnerabilitiesFromPayload({ scan_id: SCAN, status: "completed" }, SCAN)) + .toThrow(/no 'vulnerabilities' array/); + }); + + it("names the status when the scan has not completed", () => { + expect(() => vulnerabilitiesFromPayload({ status: "processing" }, SCAN)) + .toThrow(/is processing, not completed/); + expect(() => vulnerabilitiesFromPayload({ status: "failed" }, SCAN)) + .toThrow(/is failed, not completed/); + }); + + it("refuses a 200 whose body is an error object", () => { + expect(() => + vulnerabilitiesFromPayload({ error: "Failed to fetch report from storage: Object not found" }, SCAN) + ).toThrow(/no 'vulnerabilities' array/); + }); + + it("refuses a vulnerabilities value that is not a list", () => { + expect(() => vulnerabilitiesFromPayload({ vulnerabilities: "3" }, SCAN)).toThrow(); + expect(() => vulnerabilitiesFromPayload({ vulnerabilities: null }, SCAN)).toThrow(); + }); + + it("refuses non-object payloads", () => { + expect(() => vulnerabilitiesFromPayload(null, SCAN)).toThrow(); + expect(() => vulnerabilitiesFromPayload("502", SCAN)).toThrow(); + }); + + it("points at the scan id in every refusal", () => { + for (const bad of [{ status: "completed" }, { status: "processing" }, {}]) { + expect(() => vulnerabilitiesFromPayload(bad, SCAN)).toThrow(new RegExp(`rafter get ${SCAN}`)); + } + }); +}); + // ── from-scan: --repo flag override ────────────────────────────────── describe("from-scan: repo flag", () => { diff --git a/python/rafter_cli/commands/issues/issues_app.py b/python/rafter_cli/commands/issues/issues_app.py index ec198c47..2e74bc2a 100644 --- a/python/rafter_cli/commands/issues/issues_app.py +++ b/python/rafter_cli/commands/issues/issues_app.py @@ -14,7 +14,7 @@ import requests import typer -from ...utils.api import api_url, API_BASE, api_get, EXIT_GENERAL_ERROR, EXIT_SUCCESS, resolve_key +from ...utils.api import api_url, api_get, EXIT_GENERAL_ERROR, resolve_key from ...utils.formatter import fmt, print_stderr from ...utils.git import detect_repo from .dedup import find_duplicates @@ -74,7 +74,13 @@ def from_scan( # Build drafts if scan_id: - drafts = _drafts_from_backend(scan_id, api_key) + try: + drafts = _drafts_from_backend(scan_id, api_key) + except (UnreadableScanPayload, requests.RequestException, ValueError) as e: + # ValueError covers a non-JSON body from resp.json(). None of these + # is "no findings"; each is a scan whose report could not be read. + print_stderr(fmt.error(str(e))) + raise typer.Exit(code=EXIT_GENERAL_ERROR) else: drafts = _drafts_from_local(from_local) # type: ignore[arg-type] @@ -211,6 +217,33 @@ def from_text( # ── Internal helpers ────────────────────────────────────────────────── +class UnreadableScanPayload(ValueError): + """The scan payload carries no findings list this command can file from.""" + + +def vulnerabilities_from_payload(data: object, scan_id: str) -> list[dict]: + """The findings list from a scan payload, or an error — never a silent []. + + A payload without a ``vulnerabilities`` list is not "no findings". It is a + scan that has not completed, a failed scan, or a report this client cannot + read; filing zero issues from it would report a clean codebase for work + that was never done (sable-fgk7). An empty list IS a legitimate clean + result and is returned as such. + """ + if isinstance(data, dict) and isinstance(data.get("vulnerabilities"), list): + return data["vulnerabilities"] + status = data.get("status") if isinstance(data, dict) else None + if isinstance(status, str) and status != "completed": + raise UnreadableScanPayload( + f"Scan {scan_id} is {status}, not completed — there are no findings to " + f"file yet. Retry once it completes: rafter get {scan_id}" + ) + raise UnreadableScanPayload( + f"Scan {scan_id} returned no 'vulnerabilities' array; refusing to treat an " + f"unreadable report as zero findings. Check it with: rafter get {scan_id}" + ) + + def _drafts_from_backend(scan_id: str, api_key: str | None) -> list[IssueDraft]: key = resolve_key(api_key) resp = api_get( @@ -222,7 +255,7 @@ def _drafts_from_backend(scan_id: str, api_key: str | None) -> list[IssueDraft]: resp.raise_for_status() data = resp.json() - vulns = data.get("vulnerabilities", []) + vulns = vulnerabilities_from_payload(data, scan_id) return [ build_from_backend_vulnerability( BackendVulnerability( diff --git a/python/tests/test_issues.py b/python/tests/test_issues.py index f24bdf2d..5497d0dd 100644 --- a/python/tests/test_issues.py +++ b/python/tests/test_issues.py @@ -683,3 +683,122 @@ def _parse(self, text): def test_labels_are_unique(self): result = self._parse("Critical security vulnerability with credentials and tokens") assert len(result["labels"]) == len(set(result["labels"])) + + +# ── from-scan: a payload with no findings list is an error, not zero ── +# +# sable-fgk7. `data.get("vulnerabilities", [])` turned a still-running scan, a +# failed scan, a 200 carrying an error object, and a schema-valid payload with +# no key into "No findings to create issues for". Delete-the-subject test: +# with the fallback restored, every case below except the first two passes +# with [] and this class fails. Mirrors the Node suite of the same name. + + +class TestVulnerabilitiesFromPayload: + SCAN = "scan-abc" + + def _call(self, data): + from rafter_cli.commands.issues.issues_app import vulnerabilities_from_payload + + return vulnerabilities_from_payload(data, self.SCAN) + + def test_returns_the_list_when_present(self): + v = [{"ruleId": "r", "level": "error", "message": "m", "file": "f"}] + assert self._call({"status": "completed", "vulnerabilities": v}) is v + + def test_empty_list_is_a_legitimate_clean_result(self): + assert self._call({"status": "completed", "vulnerabilities": []}) == [] + + def test_refuses_completed_payload_with_no_key(self): + from rafter_cli.commands.issues.issues_app import UnreadableScanPayload + + with pytest.raises(UnreadableScanPayload, match="no 'vulnerabilities' array"): + self._call({"scan_id": self.SCAN, "status": "completed"}) + + def test_names_the_status_when_not_completed(self): + from rafter_cli.commands.issues.issues_app import UnreadableScanPayload + + with pytest.raises(UnreadableScanPayload, match="is processing, not completed"): + self._call({"status": "processing"}) + with pytest.raises(UnreadableScanPayload, match="is failed, not completed"): + self._call({"status": "failed"}) + + def test_refuses_error_object(self): + from rafter_cli.commands.issues.issues_app import UnreadableScanPayload + + with pytest.raises(UnreadableScanPayload, match="no 'vulnerabilities' array"): + self._call({"error": "Failed to fetch report from storage: Object not found"}) + + def test_refuses_vulnerabilities_that_is_not_a_list(self): + from rafter_cli.commands.issues.issues_app import UnreadableScanPayload + + with pytest.raises(UnreadableScanPayload): + self._call({"vulnerabilities": "3"}) + with pytest.raises(UnreadableScanPayload): + self._call({"vulnerabilities": None}) + + def test_refuses_non_dict_payloads(self): + from rafter_cli.commands.issues.issues_app import UnreadableScanPayload + + with pytest.raises(UnreadableScanPayload): + self._call(None) + with pytest.raises(UnreadableScanPayload): + self._call("502") + + def test_points_at_the_scan_id_in_every_refusal(self): + from rafter_cli.commands.issues.issues_app import UnreadableScanPayload + + for bad in ({"status": "completed"}, {"status": "processing"}, {}): + with pytest.raises(UnreadableScanPayload, match=f"rafter get {self.SCAN}"): + self._call(bad) + + +class TestFromScanCommandRefusesUnreadablePayload: + """The command surface: an unreadable payload exits 1 with the message on + stderr, and never reaches the "No findings to create issues for" path.""" + + def test_unreadable_payload_exits_1(self, monkeypatch, capsys): + from unittest.mock import MagicMock + + import typer + + from rafter_cli.commands.issues import issues_app as mod + + resp = MagicMock() + resp.status_code = 200 + resp.json.return_value = {"scan_id": "scan-abc", "status": "completed"} + resp.raise_for_status.return_value = None + monkeypatch.setattr(mod, "api_get", lambda *a, **k: resp) + monkeypatch.setattr(mod, "resolve_key", lambda _k: "key") + + with pytest.raises(typer.Exit) as exc: + mod.from_scan( + scan_id="scan-abc", from_local=None, repo="org/repo", api_key="k", + no_dedup=True, dry_run=True, quiet=False, + ) + assert exc.value.exit_code == 1 + err = capsys.readouterr().err + assert "no 'vulnerabilities' array" in err + assert "No findings to create issues for" not in err + + def test_non_json_body_exits_1(self, monkeypatch, capsys): + from unittest.mock import MagicMock + + import typer + + from rafter_cli.commands.issues import issues_app as mod + + resp = MagicMock() + resp.status_code = 200 + resp.json.side_effect = ValueError("Expecting value: line 1 column 1 (char 0)") + resp.raise_for_status.return_value = None + monkeypatch.setattr(mod, "api_get", lambda *a, **k: resp) + monkeypatch.setattr(mod, "resolve_key", lambda _k: "key") + + with pytest.raises(typer.Exit) as exc: + mod.from_scan( + scan_id="scan-abc", from_local=None, repo="org/repo", api_key="k", + no_dedup=True, dry_run=True, quiet=False, + ) + assert exc.value.exit_code == 1 + assert "No findings to create issues for" not in capsys.readouterr().err diff --git a/shared-docs/CLI_SPEC.md b/shared-docs/CLI_SPEC.md index cd23373d..ba6e0707 100644 --- a/shared-docs/CLI_SPEC.md +++ b/shared-docs/CLI_SPEC.md @@ -149,6 +149,7 @@ After either budget is exhausted the command exits `1`. If the failures reached - It has no "first poll" distinction: by the time it polls, the trigger step has already returned a `scan_id`, so **every** 404 there is treated as read-after-write lag. A scan id the backend accepted but never persisted therefore fails after the 5-failure budget rather than immediately. - Its poll loop is additionally bounded by a wall-clock deadline derived from `timeout-minutes`. Before v0.11 that input was a poll *count*, so a slow API could overrun it; it is now a real deadline. - Its `status` output is `completed`, `failed`, `timeout`, `unreadable` (the scan may have finished but its report could not be read), or `unreachable` (the API could not be contacted). +- Its results step validates the payload **before** counting. A body with no `vulnerabilities` array — not JSON, a `200` carrying an error object, or a parseable payload missing the key — is `status=unreadable`, the job fails, and **no count outputs are written**: a consumer reading `findings-count` sees an empty string, never a fabricated `0`. A report the action cannot read is not a clean scan. An empty array is a clean scan and counts as `0`. ### rafter usage [OPTIONS] @@ -1245,6 +1246,8 @@ Create GitHub issues from scan results. - `--dry-run` — show issues that would be created without actually creating them - `--quiet` — suppress status messages +**A scan payload without a `vulnerabilities` array is an error, not zero findings.** With `--scan-id`, a response that has no `vulnerabilities` list — the scan is still `processing`, it `failed`, the body is not JSON, or it is an error object — exits `1` with a message on stderr that names the scan id and `rafter get `. It never prints "No findings to create issues for". An empty list is a legitimate clean result. Both runtimes. + #### rafter issues create from-text [OPTIONS] Create a GitHub issue from natural language text (stdin, file, or inline).