From 21905fd08f01686875744ea2b96d17a0b30bb122 Mon Sep 17 00:00:00 2001 From: Cheryl Aurelia <135518448+cherylaurelia@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:49:56 -0500 Subject: [PATCH 1/4] fix: fail the scan when the verdict API returns no verdict probe() marked a response with no verdict status as a server error but returned last_error, which is None when the error body is JSON. A 429 from the API's throttler ({"statusCode":429,...}) therefore came back as an advisory "unknown", error_count stayed 0, the comment said every dependency looked clean, and the workflow passed. Report the HTTP status as the error so these runs end in ERROR, as the README describes. Co-authored-by: Claude --- scripts/hfw_report.py | 9 +++++++-- tests/test_hfw_report.py | 16 +++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/scripts/hfw_report.py b/scripts/hfw_report.py index 954dcf9..96244b4 100644 --- a/scripts/hfw_report.py +++ b/scripts/hfw_report.py @@ -656,7 +656,8 @@ def probe(ecosystem: str, name: str, version: str) -> dict: max wait per request) until the total budget WAIT_SECONDS is exhausted. `error` is set when the request never produced a usable verdict (network - failure, auth, 5xx). `level` is "unknown" when the server simply hasn't + failure, auth, 5xx, or any response without a verdict status, such as the + throttler's JSON 429). `level` is "unknown" when the server simply hasn't finished scanning in time -- those two cases are very different and main() treats `error` as a hard failure but `unknown` as advisory. """ @@ -701,6 +702,10 @@ def probe(ecosystem: str, name: str, version: str) -> dict: # to us properly. We explicitly demand a parseable verdict envelope before # declaring success. is_server_error = last_error is not None or not last_body.get("status") + error = None + if is_server_error: + # A JSON error body (e.g. the throttler's 429) leaves last_error unset. + error = last_error or f"http error {last_status}" return { "ecosystem": ecosystem, @@ -711,7 +716,7 @@ def probe(ecosystem: str, name: str, version: str) -> dict: "level": (last_body.get("level") or "unknown"), "summary": (last_body.get("summary") or ""), "cached": last_body.get("cached", False), - "error": last_error if is_server_error else None, + "error": error, } diff --git a/tests/test_hfw_report.py b/tests/test_hfw_report.py index 12c3061..30049d4 100644 --- a/tests/test_hfw_report.py +++ b/tests/test_hfw_report.py @@ -607,6 +607,20 @@ def fake_get(url: str, timeout: float): assert r["error"] == "name resolution failed" +def test_probe_treats_rate_limited_json_body_as_error(monkeypatch): + """The throttler's 429 has a JSON body but no verdict; it must fail the + run, not count as a passing 'unknown'.""" + + def fake_get(url: str, timeout: float): + return 429, {"statusCode": 429, "message": "Too Many Requests"}, None + + monkeypatch.setattr(hfw, "http_get_json", fake_get) + monkeypatch.setattr(hfw, "WAIT_SECONDS", 1) + r = hfw.probe("npm", "debug", "4.4.2") + assert r["error"] == "http error 429" + assert r["level"] == "unknown" + + def test_probe_no_error_when_server_returns_pending(monkeypatch): """A 'pending' verdict means the scan is running; that's not an error.""" calls = {"n": 0} @@ -650,7 +664,7 @@ def fake_get(url: str, timeout: float): monkeypatch.setattr(hfw, "http_get_json", fake_get) monkeypatch.setattr(hfw, "WAIT_SECONDS", 1) r = hfw.probe("pypi", "fastapi", "0.136.1") - assert r["error"] is not None or r["level"] == "unknown" + assert r["error"] == "http error 200" assert r["verdict_status"] is None From 9eb025a303d088550dbf9a8de1eed59836d238a1 Mon Sep 17 00:00:00 2001 From: Cheryl Aurelia <135518448+cherylaurelia@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:35:12 -0500 Subject: [PATCH 2/4] fix: retry verdict lookups the API rate-limited The verdict API allows about 100 lookups a minute per IP, so a PR that adds or regenerates a lockfile (432 packages for a new Next.js app) got 429s for most lookups. With the fail-closed commit those runs end in ERROR; retrying after the server's retry-after-* window (1-60 s), at most HFW_RATE_LIMIT_RETRIES times per lookup (default 6), lets them finish with a verdict for every package. Co-authored-by: Claude --- scripts/hfw_report.py | 25 +++++++++++-- tests/test_hfw_report.py | 76 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 2 deletions(-) diff --git a/scripts/hfw_report.py b/scripts/hfw_report.py index 96244b4..e69dc90 100644 --- a/scripts/hfw_report.py +++ b/scripts/hfw_report.py @@ -30,6 +30,7 @@ HFW_VERDICT_WAIT_SECONDS seconds to wait for in-progress scans (default 0) HFW_PARALLEL concurrent verdict requests (default 4) + HFW_RATE_LIMIT_RETRIES retries per lookup after an HTTP 429 (default 6) HFW_IGNORE_FILE optional allowlist (one name@version per line) HFW_REPORT_OUT where to write the comment markdown @@ -45,6 +46,7 @@ import os import re import sys +import time import tomllib import urllib.error import urllib.parse @@ -95,6 +97,7 @@ def detect_ecosystem(path: Path) -> str | None: AUTH_FAIL_CODES = {401, 403} +RATE_LIMIT_RETRIES = int(os.environ.get("HFW_RATE_LIMIT_RETRIES", "6")) # Package-name / version validators. Lockfile contents are attacker-controlled @@ -158,9 +161,12 @@ def _package_detail_url(ecosystem: str, name: str, version: str) -> str: ) -def http_get_json(url: str, timeout: float) -> tuple[int, dict, str | None]: +def http_get_json( + url: str, timeout: float, retries: int = RATE_LIMIT_RETRIES +) -> tuple[int, dict, str | None]: """Return (http_status, body_json, error_message). error_message is None - on a clean HTTP response (even 4xx with JSON body).""" + on a clean HTTP response (even 4xx with JSON body). A 429 is retried after + the server's retry-after window, at most `retries` times.""" headers = {"User-Agent": "hfw-ci-report/1.0"} req = urllib.request.Request(url, headers=headers) try: @@ -171,6 +177,11 @@ def http_get_json(url: str, timeout: float) -> tuple[int, dict, str | None]: except json.JSONDecodeError: return resp.status, {}, f"non-json body (status={resp.status})" except urllib.error.HTTPError as exc: + if exc.code == 429 and retries > 0: + wait = _retry_after_seconds(exc.headers) + exc.close() + time.sleep(wait) + return http_get_json(url, timeout, retries - 1) try: return ( exc.code, @@ -183,6 +194,16 @@ def http_get_json(url: str, timeout: float) -> tuple[int, dict, str | None]: return -1, {}, str(exc) +def _retry_after_seconds(headers) -> int: + """Longest Retry-After / Retry-After- value, clamped to 1-60s.""" + waits = [ + int(value) + for key, value in (headers or {}).items() + if key.lower().startswith("retry-after") and value.strip().isdigit() + ] + return max(1, min(max(waits, default=1), 60)) + + def parse_pnpm_lock(path: Path) -> set[tuple[str, str]]: """Return distinct (name, version) tuples from a pnpm v9 lockfile. diff --git a/tests/test_hfw_report.py b/tests/test_hfw_report.py index 30049d4..0451bbe 100644 --- a/tests/test_hfw_report.py +++ b/tests/test_hfw_report.py @@ -621,6 +621,82 @@ def fake_get(url: str, timeout: float): assert r["level"] == "unknown" +class _FakeResponse: + status = 200 + + def __init__(self, body: bytes): + self._body = body + + def read(self) -> bytes: + return self._body + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def _http_429(retry_after: str): + import email.message + import io + import urllib.error + + headers = email.message.Message() + headers["retry-after-short"] = retry_after + return urllib.error.HTTPError( + "https://example.test", 429, "Too Many Requests", headers, io.BytesIO(b"{}") + ) + + +def test_http_get_json_retries_after_rate_limit(monkeypatch): + responses = [_http_429("2"), _FakeResponse(b'{"status": "ready"}')] + sleeps: list[float] = [] + + def fake_urlopen(req, timeout): + item = responses.pop(0) + if isinstance(item, Exception): + raise item + return item + + monkeypatch.setattr(hfw.urllib.request, "urlopen", fake_urlopen) + monkeypatch.setattr(hfw.time, "sleep", sleeps.append) + assert hfw.http_get_json("https://example.test", 5) == ( + 200, + {"status": "ready"}, + None, + ) + assert sleeps == [2] + + +def test_http_get_json_gives_up_after_rate_limit_retries(monkeypatch): + calls = {"n": 0} + + def fake_urlopen(req, timeout): + calls["n"] += 1 + raise _http_429("1") + + monkeypatch.setattr(hfw.urllib.request, "urlopen", fake_urlopen) + monkeypatch.setattr(hfw.time, "sleep", lambda s: None) + status, _body, _err = hfw.http_get_json("https://example.test", 5) + assert status == 429 + assert calls["n"] == hfw.RATE_LIMIT_RETRIES + 1 + + +@pytest.mark.parametrize( + ("headers", "expected"), + [ + ({}, 1), + ({"retry-after-short": "1", "retry-after-long": "30"}, 30), + ({"Retry-After": "0"}, 1), + ({"retry-after-long": "120"}, 60), + ({"retry-after-medium": "soon"}, 1), + ], +) +def test_retry_after_seconds_takes_longest_window_clamped(headers, expected): + assert hfw._retry_after_seconds(headers) == expected + + def test_probe_no_error_when_server_returns_pending(monkeypatch): """A 'pending' verdict means the scan is running; that's not an error.""" calls = {"n": 0} From e7fe9b10239117182c0bb5a84b354a030866e3ed Mon Sep 17 00:00:00 2001 From: Cheryl Aurelia <135518448+cherylaurelia@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:20:49 -0500 Subject: [PATCH 3/4] fix: look up npm aliases by their registry name npm writes `foo@npm:bar@1.0.0` as node_modules/foo with "name": "bar". The package-lock parser used the key, so an aliased package was checked under the alias name and a malicious version passed. Use `name` when present, as hacktron.ai/tools/package already does. Co-authored-by: Claude --- scripts/hfw_report.py | 9 ++++++++- tests/test_hfw_report.py | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/scripts/hfw_report.py b/scripts/hfw_report.py index e69dc90..cb8db99 100644 --- a/scripts/hfw_report.py +++ b/scripts/hfw_report.py @@ -291,7 +291,14 @@ def parse_package_lock_json(path: Path) -> set[tuple[str, str]]: idx = key.rfind(marker) if idx < 0: continue - name = key[idx + len(marker) :] + # npm aliases (`foo@npm:bar@1.0.0`) key the entry by the alias and + # record the registry package in `name`. + alias_of = meta.get("name") + name = ( + alias_of + if isinstance(alias_of, str) and alias_of + else key[idx + len(marker) :] + ) if name: out.add((name, version)) return out diff --git a/tests/test_hfw_report.py b/tests/test_hfw_report.py index 0451bbe..ac0a92e 100644 --- a/tests/test_hfw_report.py +++ b/tests/test_hfw_report.py @@ -138,6 +138,26 @@ def test_parse_package_lock_v3_handles_nested_node_modules(tmp_path: Path): assert ("diff", "5.0.0") in parsed +def test_parse_package_lock_v3_uses_real_name_for_npm_alias(tmp_path: Path): + """`npm install http-client@npm:axios@1.14.1` writes the alias as the key + and the registry package as `name`; the verdict must be for axios.""" + lock = tmp_path / "package-lock.json" + lock.write_text( + """{ + "name": "demo", "version": "1.0.0", "lockfileVersion": 3, + "packages": { + "": {"name": "demo", "dependencies": {"http-client": "npm:axios@1.14.1"}}, + "node_modules/http-client": {"name": "axios", "version": "1.14.1"}, + "node_modules/lodash": {"version": "4.17.21"} + } + }""" + ) + assert hfw.parse_package_lock_json(lock) == { + ("axios", "1.14.1"), + ("lodash", "4.17.21"), + } + + def test_parse_package_lock_v3_skips_workspace_links(tmp_path: Path): lock = tmp_path / "package-lock.json" lock.write_text("""{ From 7071ccf28d593802b2e9186ea63e6129d28376a5 Mon Sep 17 00:00:00 2001 From: "Zeyu (Zayne) Zhang" Date: Thu, 19 Nov 2026 15:09:23 +0000 Subject: [PATCH 4/4] fix: reject failed and malformed verdict envelopes --- README.md | 12 +++++ scripts/hfw_report.py | 60 +++++++++++++-------- tests/test_hfw_report.py | 111 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 161 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index b5a4c67..5e5401a 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,18 @@ auto-discovered from tracked files. Suspicious package signals are shown in the PR comment, but only malicious packages fail the workflow by default. +HTTP 429 responses are retried after the longest numeric `Retry-After` or +`Retry-After-*` header, bounded to 1–60 seconds per retry. Each lookup retries +up to six times by default; set the `HFW_RATE_LIMIT_RETRIES` environment +variable to override this count. Exhausted retries, other HTTP errors, and +malformed or failed verdict responses produce `ERROR`, even when +`fail-on-malicious` is disabled. Error runs stop before posting a PR comment. +Valid `pending` or `scanning` responses remain advisory and are shown as +dependencies without a verdict, rather than described as clean. + +For npm lockfiles with a `packages` map, aliases are checked using the registry +package name recorded in the entry's `name` field. + ## Inputs | Input | Default | Description | diff --git a/scripts/hfw_report.py b/scripts/hfw_report.py index cb8db99..d90ab4e 100644 --- a/scripts/hfw_report.py +++ b/scripts/hfw_report.py @@ -163,7 +163,7 @@ def _package_detail_url(ecosystem: str, name: str, version: str) -> str: def http_get_json( url: str, timeout: float, retries: int = RATE_LIMIT_RETRIES -) -> tuple[int, dict, str | None]: +) -> tuple[int, object, str | None]: """Return (http_status, body_json, error_message). error_message is None on a clean HTTP response (even 4xx with JSON body). A 429 is retried after the server's retry-after window, at most `retries` times.""" @@ -683,11 +683,10 @@ def probe(ecosystem: str, name: str, version: str) -> dict: """Ask the verdict server for an opinion. Polls in 8s windows (server's max wait per request) until the total budget WAIT_SECONDS is exhausted. - `error` is set when the request never produced a usable verdict (network - failure, auth, 5xx, or any response without a verdict status, such as the - throttler's JSON 429). `level` is "unknown" when the server simply hasn't - finished scanning in time -- those two cases are very different and - main() treats `error` as a hard failure but `unknown` as advisory. + `error` is set for network/HTTP failures and malformed or failed verdicts. + Without an error, `level` is "unknown" only for valid pending/scanning + responses that did not finish in time. main() treats errors as hard + failures and in-progress scans as advisory. """ coord_error = _validate_coord(ecosystem, name, version) if coord_error: @@ -713,35 +712,44 @@ def probe(ecosystem: str, name: str, version: str) -> dict: url = _verdict_url(ecosystem, name, version, per_request_wait) status, body, err = http_get_json(url, timeout=per_request_wait + 10) last_status = status - last_body = body + last_body = body if isinstance(body, dict) else {} last_error = err - if err is not None and status in AUTH_FAIL_CODES: + if not isinstance(body, dict): + last_error = err or f"non-object JSON body (status={status})" break - if err is not None and status < 0: + if err is not None or not 200 <= status < 300: break verdict_status = body.get("status") - if verdict_status not in {"pending", "scanning"}: + if verdict_status not in ("pending", "scanning"): break spent += per_request_wait if spent >= deadline: break - # Any non-JSON body or unknown verdict status means the server didn't talk - # to us properly. We explicitly demand a parseable verdict envelope before - # declaring success. - is_server_error = last_error is not None or not last_body.get("status") - error = None - if is_server_error: - # A JSON error body (e.g. the throttler's 429) leaves last_error unset. - error = last_error or f"http error {last_status}" + # A JSON error body can have a truthy `status` (e.g. HFW's scan errors), + # so require both HTTP success and a recognized verdict envelope. + verdict_status = last_body.get("status") + level = last_body.get("level") + error = last_error + if error is None: + if not 200 <= last_status < 300: + error = f"http error {last_status}" + elif verdict_status not in ("ready", "pending", "scanning"): + error = f"invalid verdict status {verdict_status!r} (status={last_status})" + elif verdict_status == "ready" and level not in ( + "clean", + "suspicious", + "malicious", + ): + error = f"invalid verdict level {level!r} (status={last_status})" return { "ecosystem": ecosystem, "name": name, "version": version, "http": last_status, - "verdict_status": last_body.get("status"), - "level": (last_body.get("level") or "unknown"), + "verdict_status": verdict_status, + "level": level if error is None and verdict_status == "ready" else "unknown", "summary": (last_body.get("summary") or ""), "cached": last_body.get("cached", False), "error": error, @@ -798,6 +806,7 @@ def render( unknown = [ r for r in results if r["level"] not in {"malicious", "suspicious", "clean"} ] + errored = [r for r in results if r["error"]] multi = len(projects) > 1 total_diff = len(results) @@ -814,7 +823,11 @@ def render( lines.append(f"Scanned {len(projects)} project(s): {scanned}") return "\n".join(lines) + "\n" - if malicious: + if errored: + lines.append( + f"**Scan failed — could not get verdicts for {len(errored)} package(s).**" + ) + elif malicious: lines.append( "**Blocking — " f"{len(malicious)} malicious package(s) introduced by this PR.**" @@ -824,6 +837,11 @@ def render( f"Review — {len(suspicious)} suspicious package(s) introduced by " "this PR. Merge is allowed." ) + elif unknown: + lines.append( + "No malicious packages found in completed lookups; " + f"{len(unknown)} dependency(ies) still have no verdict." + ) else: lines.append(f"All {total_diff} new/changed dependencies look clean.") lines.append("") diff --git a/tests/test_hfw_report.py b/tests/test_hfw_report.py index ac0a92e..4f6d598 100644 --- a/tests/test_hfw_report.py +++ b/tests/test_hfw_report.py @@ -8,6 +8,7 @@ from __future__ import annotations import importlib.util +import json import sys from pathlib import Path @@ -760,10 +761,110 @@ def fake_get(url: str, timeout: float): monkeypatch.setattr(hfw, "http_get_json", fake_get) monkeypatch.setattr(hfw, "WAIT_SECONDS", 1) r = hfw.probe("pypi", "fastapi", "0.136.1") - assert r["error"] == "http error 200" + assert r["error"] is not None assert r["verdict_status"] is None +@pytest.mark.parametrize( + ("status", "body"), + [ + (401, {"status": "error"}), + (403, {"status": "ready", "level": "clean"}), + (404, {"status": "unknown"}), + (422, {"status": "error", "error": "download failed"}), + (429, {"status": "pending"}), + (503, {"status": "error"}), + (200, {"status": "error"}), + (200, {"status": "unexpected"}), + (200, {"status": ["ready"]}), + (200, {"status": "ready"}), + (200, {"status": "ready", "level": "error"}), + (200, {"status": "ready", "level": "unexpected"}), + (200, {"status": "ready", "level": ["clean"]}), + (200, []), + (200, None), + (200, "upstream error"), + ], +) +def test_probe_rejects_unusable_verdicts(monkeypatch, status, body): + calls = [] + + def fake_get(url, timeout): + calls.append(url) + return status, body, None + + monkeypatch.setattr(hfw, "http_get_json", fake_get) + monkeypatch.setattr(hfw, "WAIT_SECONDS", 16) + result = hfw.probe("npm", "debug", "4.4.2") + assert result["error"] + assert result["level"] == "unknown" + assert len(calls) == 1 + + +@pytest.mark.parametrize("level", ["clean", "suspicious", "malicious"]) +def test_probe_accepts_completed_verdicts(monkeypatch, level): + monkeypatch.setattr( + hfw, + "http_get_json", + lambda url, timeout: (200, {"status": "ready", "level": level}, None), + ) + result = hfw.probe("npm", "debug", "4.4.2") + assert result["error"] is None + assert result["level"] == level + + +def test_probe_polls_scanning_until_ready(monkeypatch): + responses = iter( + [ + (202, {"status": "scanning"}, None), + (200, {"status": "ready", "level": "malicious"}, None), + ] + ) + monkeypatch.setattr(hfw, "http_get_json", lambda url, timeout: next(responses)) + monkeypatch.setattr(hfw, "WAIT_SECONDS", 16) + result = hfw.probe("npm", "debug", "4.4.2") + assert result["error"] is None + assert result["level"] == "malicious" + + +def test_main_fails_when_rate_limit_retries_are_exhausted( + monkeypatch, tmp_path, capsys +): + head = tmp_path / "package-lock.json" + head.write_text('{"packages":{"node_modules/debug":{"version":"4.4.2"}}}') + output = tmp_path / "outputs.txt" + report = tmp_path / "comment.md" + monkeypatch.setenv( + "HFW_PROJECTS", + json.dumps( + [ + { + "label": "root", + "head": str(head), + "base": str(tmp_path / "base" / "package-lock.json"), + "ecosystem": "npm", + } + ] + ), + ) + monkeypatch.setenv("GITHUB_OUTPUT", str(output)) + monkeypatch.setattr(hfw, "OUT_PATH", report) + monkeypatch.setattr(hfw, "IGNORE_FILE", tmp_path / ".hfwignore") + monkeypatch.setattr(hfw.time, "sleep", lambda seconds: None) + calls = [] + + def fake_urlopen(req, timeout): + calls.append(req.full_url) + raise _http_429("1") + + monkeypatch.setattr(hfw.urllib.request, "urlopen", fake_urlopen) + assert hfw.main() == 3 + assert len(calls) == hfw.RATE_LIMIT_RETRIES + 1 + assert "error_count=1\n" in output.read_text() + assert "http error 429" in capsys.readouterr().err + assert "look clean" not in report.read_text() + + # --------------------------------------------------------------------------- # multi-project: HFW_PROJECTS parsing @@ -856,6 +957,14 @@ def test_render_empty_diff_single_project_omits_scanned_footer(): assert "Scanned" not in md +def test_render_incomplete_lookups_does_not_claim_clean(): + result = _result("root", "debug", "4.4.2", "unknown") + result["verdict_status"] = "pending" + md = hfw.render([{"label": "root"}], [result], set()) + assert "look clean" not in md + assert "still have no verdict" in md + + # --------------------------------------------------------------------------- # Name / version validation -- guards against path traversal in URL building. # An attacker-controlled lockfile must not be able to make probe() request