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 954dcf9..d90ab4e 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, object, 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. @@ -270,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 @@ -655,10 +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). `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: @@ -684,34 +712,47 @@ 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") + # 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": last_error if is_server_error else None, + "error": error, } @@ -765,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) @@ -781,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.**" @@ -791,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 12c3061..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 @@ -138,6 +139,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("""{ @@ -607,6 +628,96 @@ 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" + + +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} @@ -650,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"] is not None or r["level"] == "unknown" + 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 @@ -746,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