Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
89 changes: 70 additions & 19 deletions scripts/hfw_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -45,6 +46,7 @@
import os
import re
import sys
import time
import tomllib
import urllib.error
import urllib.parse
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Comment on lines +180 to +184

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM P59-FD-2302: Per-coordinate 429 retries can exhaust the CI job time budget

./dependency-scan/scripts/hfw_report.py:180-184 http_get_json sleeps for the server-selected delay and retries each HTTP 429 up to the default six times. A pull-request author only needs to add many distinct syntactically valid coordinates to a supported manifest, and the verdict service must rate-limit the resulting request burst. The scan can then spend up to 360 seconds sleeping for each coordinate while the executor processes the queued work in four-worker waves. This delays the report step and can make the dependency check hit the workflow job timeout before it produces a verdict.

Steps to Reproduce
  1. Create a pull-request branch whose base revision does not contain package-lock.json. Run the separate Python script in the python_script field at the repository root to create a supported head manifest with 100 distinct package coordinates.

  2. Run the composite action with HFW_RATE_LIMIT_RETRIES unset so it uses the default six retries and with the default HFW_PARALLEL value of four. Configure the inherited HFW_SERVER environment variable to a test verdict endpoint that returns HTTP 429 and Retry-After: 1 for every /verdict/... request. The same behavior can be observed against the normal verdict service when this pull request causes it to rate-limit the request burst.

  3. Check the report-step logs for querying verdicts for 100 package(s) ... parallel=4, and check the test endpoint request log for repeated requests for each coordinate. Each coordinate should receive its initial request plus six retries, with a one-second sleep between retry attempts.

  4. Check that the report step remains active while the four worker threads sleep and drain the queued coordinates. With Retry-After: 60, the same response pattern permits up to 360 seconds of sleep per coordinate and can prevent the workflow from completing before its job timeout.

import json
from pathlib import Path

count = 100
packages = {
    "": {
        "name": "rate-limit-retry-poc",
        "version": "1.0.0",
    }
}
for index in range(count):
    packages[f"node_modules/@hfw-poc/package-{index:04d}"] = {
        "version": "1.0.0"
    }

Path("package-lock.json").write_text(
    json.dumps(
        {
            "name": "rate-limit-retry-poc",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "requires": True,
            "packages": packages,
        },
        indent=2,
    )
    + "\n",
    encoding="utf-8",
)
Fix with AI

Open in Cursor Open in Claude

A security vulnerability was found by Hacktron.

File: scripts/hfw_report.py
Lines: 180-184
Severity: medium

Vulnerability: Per-coordinate 429 retries can exhaust the CI job time budget

Description:
[./dependency-scan/scripts/hfw_report.py:180-184](./dependency-scan/scripts/hfw_report.py:180-184) `http_get_json` sleeps for the server-selected delay and retries each HTTP 429 up to the default six times. A pull-request author only needs to add many distinct syntactically valid coordinates to a supported manifest, and the verdict service must rate-limit the resulting request burst. The scan can then spend up to 360 seconds sleeping for each coordinate while the executor processes the queued work in four-worker waves. This delays the report step and can make the dependency check hit the workflow job timeout before it produces a verdict.

Proof of Concept:
**Steps to Reproduce**

1. Create a pull-request branch whose base revision does not contain `package-lock.json`. Run the separate Python script in the `python_script` field at the repository root to create a supported head manifest with 100 distinct package coordinates.

2. Run the composite action with `HFW_RATE_LIMIT_RETRIES` unset so it uses the default six retries and with the default `HFW_PARALLEL` value of four. Configure the inherited `HFW_SERVER` environment variable to a test verdict endpoint that returns HTTP 429 and `Retry-After: 1` for every `/verdict/...` request. The same behavior can be observed against the normal verdict service when this pull request causes it to rate-limit the request burst.

3. Check the report-step logs for `querying verdicts for 100 package(s) ... parallel=4`, and check the test endpoint request log for repeated requests for each coordinate. Each coordinate should receive its initial request plus six retries, with a one-second sleep between retry attempts.

4. Check that the report step remains active while the four worker threads sleep and drain the queued coordinates. With `Retry-After: 60`, the same response pattern permits up to 360 seconds of sleep per coordinate and can prevent the workflow from completing before its job timeout.

```python
import json
from pathlib import Path

count = 100
packages = {
    "": {
        "name": "rate-limit-retry-poc",
        "version": "1.0.0",
    }
}
for index in range(count):
    packages[f"node_modules/@hfw-poc/package-{index:04d}"] = {
        "version": "1.0.0"
    }

Path("package-lock.json").write_text(
    json.dumps(
        {
            "name": "rate-limit-retry-poc",
            "version": "1.0.0",
            "lockfileVersion": 3,
            "requires": True,
            "packages": packages,
        },
        indent=2,
    )
    + "\n",
    encoding="utf-8",
)
```

Affected Code:
        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)

Acceptance criteria:
- Acceptance is defined by the **actual reported behavior**, not by tests passing.
- Reproduce the issue, or narrow the exact code path that produces it, *before* changing code. State what you confirmed.
- Fix the underlying cause. Mitigations that paper over the reported behavior do not count as a fix.
- Add a regression test that fails on the unpatched code and passes on the fix. If a regression test is genuinely impractical (e.g. race condition, infra-level issue), say so and explain why.
- Existing tests passing is **not** the bar. Do not declare done on tests-pass theatre.

Only change what is necessary to fix this vulnerability. Do not refactor adjacent code or modify unrelated files.

Triage: Reply !fp <reason> (false positive), !valid (confirmed), !accepted_risk <reason>, or !fixed (resolved). Any other reply is saved as a triage note.
Reason is optional but improves future scans — e.g. !fp internal endpoint, not user-facing.

View finding in Hacktron

try:
return (
exc.code,
Expand All @@ -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-<window> 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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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,
}


Expand Down Expand Up @@ -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)
Expand All @@ -781,7 +823,11 @@ def render(
lines.append(f"<sub>Scanned {len(projects)} project(s): {scanned}</sub>")
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.**"
Expand All @@ -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("")
Expand Down
Loading
Loading