diff --git a/.watchmanconfig b/.watchmanconfig new file mode 100644 index 0000000..b795b21 --- /dev/null +++ b/.watchmanconfig @@ -0,0 +1,11 @@ +{ + "ignore_dirs": [ + ".pytest_cache", + ".ruff_cache", + ".venv", + "__pycache__", + "node/runtime/__pycache__", + "node/tests/__pycache__", + "temp" + ] +} diff --git a/docs/shared-defaults.md b/docs/shared-defaults.md index 016a720..df45001 100644 --- a/docs/shared-defaults.md +++ b/docs/shared-defaults.md @@ -65,6 +65,21 @@ All three source fields are required. Change `repository` and `path` to use your own file. `ref` can be a branch, tag, or full commit SHA. Sources are fetched without credentials; private defaults repositories are not supported. +Fetching each source allows up to three attempts within a 90-second retry +budget, with a socket inactivity timeout of at most 15 seconds. The budget +limits retries, not total transfer time; a slowly arriving response body can +exceed it. Only HTTP 429, identified +HTTP 403 throttling, and HTTP 500/502/503/504 are retried. Retries honor +`Retry-After` and exhausted-quota reset times. Without a server delay, +throttling waits 60 seconds and server errors wait one second. A delay beyond +the remaining budget stops immediately with a retry-later diagnostic. +Other access errors and redirects stop without retry or a source fallback. + +HTTP failures retain a bounded GitHub JSON error message, rate-limit headers, +`Retry-After`, and the GitHub request ID for diagnosis. Other response headers +and non-JSON response bodies are not copied into reports. A fetch failure +does not by itself show that the project's declarations are invalid. + **Replace the basic setup's explicit policy fields rather than appending this source to them.** Local fields keep overriding the source. In particular, the basic `security-only` mode conflicts with inherited nonempty upgrade schedules. diff --git a/node/runtime/configuration.py b/node/runtime/configuration.py index 41e6735..91e7992 100644 --- a/node/runtime/configuration.py +++ b/node/runtime/configuration.py @@ -1,11 +1,14 @@ """Resolve public GitHub defaults as bounded JSON data, without credentials.""" +import http.client import json import re import runpy +import time import urllib.error import urllib.parse import urllib.request +from email.utils import parsedate_to_datetime from pathlib import Path SCHEDULING = runpy.run_path(str(Path(__file__).with_name("scheduling.py"))) @@ -16,6 +19,8 @@ MAX_SOURCES = 8 SHARED_KEYS = {"toolchain", "maintenance", "minimumReleaseAgeDays", "schedule"} LOCAL_KEYS = {"directory", "validationScript", "localPatches", "advisoryNotes"} +FETCH_ATTEMPTS = 3 +FETCH_BUDGET = 90 def json_object(data, location, max_bytes=MAX_BYTES): @@ -124,29 +129,100 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): return None +def http_failure(error): + def clean(value, limit): + return re.sub(r"[\x00-\x1f\x7f-\x9f]", " ", str(value))[:limit] + + retained = { + key.lower(): clean(value, 128) + for key, value in (error.headers or {}).items() + if key.lower() + in { + "x-ratelimit-limit", + "x-ratelimit-remaining", + "x-ratelimit-reset", + "x-ratelimit-resource", + "retry-after", + "x-github-request-id", + } + } + message = "" + try: + body = json.loads(error.read(4096)) + if isinstance(body, dict) and isinstance(body.get("message"), str): + message = clean(body["message"], 512) + except (OSError, http.client.HTTPException, ValueError, RecursionError): + pass + finally: + error.close() + detail = f"HTTP {error.code}" + if message: + detail += f"; GitHub message: {message}" + detail += "".join(f"; {key}={value}" for key, value in retained.items()) + + now = time.time() + delays = [] + retry_after = retained.get("retry-after", "") + if retry_after.isascii() and retry_after.isdigit(): + delays.append(int(retry_after)) + elif retry_after: + try: + delays.append(parsedate_to_datetime(retry_after).timestamp() - now) + except (ValueError, TypeError, OverflowError): + pass + exhausted = retained.get("x-ratelimit-remaining") == "0" + reset = retained.get("x-ratelimit-reset", "") + if exhausted and reset.isascii() and reset.isdigit(): + delays.append(int(reset) - now + 1) + throttled = error.code == 429 or ( + error.code == 403 + and ( + exhausted + or any( + marker in message.lower() + for marker in ("api rate limit exceeded", "secondary rate limit") + ) + or bool(delays) + ) + ) + if throttled or error.code in {500, 502, 503, 504}: + return detail, max(1, max(delays) if delays else (60 if throttled else 1)) + return detail, None + + def public_read(url, accept="application/json"): # Never attach GITHUB_TOKEN: only public sources are supported. Redirects # fail rather than sending a request to a different origin or repository. request = urllib.request.Request( url, headers={"Accept": accept, "User-Agent": "node-audit-shared-defaults"} ) - try: - with urllib.request.build_opener(NoRedirect()).open( - request, timeout=15 - ) as response: - data = response.read(MAX_BYTES + 1) - except urllib.error.HTTPError as error: - raise ValueError( - f"Cannot read public defaults source {url}: HTTP {error.code}; " - "check public access, repository, path and ref" - ) from error - except (OSError, urllib.error.URLError) as error: - raise ValueError( - f"Cannot read public defaults source {url}: {error}" - ) from error - if len(data) > MAX_BYTES: - raise ValueError(f"{url}: defaults response exceeds {MAX_BYTES} bytes") - return data + deadline = time.monotonic() + FETCH_BUDGET + for attempt in range(1, FETCH_ATTEMPTS + 1): + try: + with urllib.request.build_opener(NoRedirect()).open( + request, timeout=min(15, max(0.001, deadline - time.monotonic())) + ) as response: + data = response.read(MAX_BYTES + 1) + except urllib.error.HTTPError as error: + detail, delay = http_failure(error) + if delay is not None: + if attempt < FETCH_ATTEMPTS and delay < deadline - time.monotonic(): + time.sleep(delay) + if time.monotonic() < deadline: + continue + advice = f"remote service unavailable or throttled; retry later (stopped after {attempt} attempts within the {FETCH_BUDGET}s retry budget)" + else: + advice = "check public access, repository, path and ref" + raise ValueError( + f"Cannot read public defaults source {url}: {detail}; {advice}" + ) from error + except (OSError, urllib.error.URLError) as error: + raise ValueError( + f"Cannot read public defaults source {url}: {error}" + ) from error + if len(data) > MAX_BYTES: + raise ValueError(f"{url}: defaults response exceeds {MAX_BYTES} bytes") + return data def merge_shared(inherited, explicit, *, inherit_schedule=True): diff --git a/node/tests/test_shared_defaults.py b/node/tests/test_shared_defaults.py index e878819..bb2e11c 100644 --- a/node/tests/test_shared_defaults.py +++ b/node/tests/test_shared_defaults.py @@ -1,3 +1,5 @@ +import io +import http.client import json import re import runpy @@ -5,6 +7,7 @@ import sys import urllib.error from pathlib import Path +from types import SimpleNamespace import pytest @@ -528,18 +531,269 @@ def open(self, request, timeout): assert "Authorization" not in requests[0].headers -def test_http_failure_is_actionable_without_a_fallback(monkeypatch): +@pytest.mark.parametrize("status", [302, 401, 403, 404, 501]) +def test_http_failure_is_actionable_without_a_fallback(monkeypatch, status): client = runpy.run_path(str(RUNTIME / "configuration.py")) + calls = [] + + class Opener: + def open(self, request, timeout): + calls.append(request.full_url) + raise urllib.error.HTTPError(request.full_url, status, "denied", {}, None) + + monkeypatch.setattr( + client["urllib"].request, "build_opener", lambda handler: Opener() + ) + with pytest.raises(ValueError, match=rf"HTTP {status}.*public access"): + client["public_read"]("https://api.github.com/example") + assert calls == ["https://api.github.com/example"] + + +@pytest.fixture +def fetch_clock(monkeypatch): + client = runpy.run_path(str(RUNTIME / "configuration.py")) + clock, sleeps = [1000.0], [] + + def sleep(seconds): + sleeps.append(seconds) + clock[0] += seconds + + monkeypatch.setitem( + client["public_read"].__globals__, + "time", + SimpleNamespace(time=lambda: clock[0], monotonic=lambda: clock[0], sleep=sleep), + ) + return client, clock, sleeps + + +@pytest.mark.parametrize( + "status,headers,message,delay", + [ + (500, {}, "", 1), + (502, {}, "", 1), + (503, {"Retry-After": "2"}, "", 2), + (504, {}, "", 1), + (429, {}, "", 60), + (429, {"Retry-After": "invalid"}, "", 60), + (403, {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "1004"}, "", 5), + (403, {"Retry-After": "4"}, "", 4), + (403, {}, "You have exceeded a secondary rate limit", 60), + (503, {"Retry-After": "Thu, 01 Jan 1970 00:16:44 GMT"}, "", 4), + ], +) +def test_public_fetch_recovers_without_credentials_or_source_fallback( + monkeypatch, fetch_clock, status, headers, message, delay +): + client, _, sleeps = fetch_clock + requests = [] + failure_body = io.BytesIO(json.dumps({"message": message}).encode()) + + class Opener: + def open(self, request, timeout): + assert 0 < timeout <= 15 + requests.append(request) + if len(requests) == 1: + raise urllib.error.HTTPError( + request.full_url, status, "failed", headers, failure_body + ) + return io.BytesIO(b"{}") + + def opener(handler): + assert isinstance(handler, client["NoRedirect"]) + return Opener() + + monkeypatch.setenv("GITHUB_TOKEN", "must-not-be-sent") + monkeypatch.setattr(client["urllib"].request, "build_opener", opener) + assert client["public_read"]("https://api.github.com/example") == b"{}" + assert sleeps == [delay] + assert len(requests) == 2 + assert all( + request.full_url == "https://api.github.com/example" for request in requests + ) + assert all(request.get_header("Authorization") is None for request in requests) + assert failure_body.closed + + +def truncated_error_response(status, headers): + reasons = {404: "Not Found", 503: "Service Unavailable"} + header_lines = "".join(f"{key}: {value}\r\n" for key, value in headers.items()) + payload = ( + f"HTTP/1.1 {status} {reasons[status]}\r\n" + f"Transfer-Encoding: chunked\r\n{header_lines}\r\n4\r\noo" + ).encode() + + class InMemorySocket: + def makefile(self, mode): + assert mode == "rb" + return io.BytesIO(payload) + + response = http.client.HTTPResponse(InMemorySocket()) + response.begin() + return response + + +def test_public_fetch_recovers_after_truncated_chunked_error(monkeypatch, fetch_clock): + client, _, sleeps = fetch_clock + calls = [] + failed_responses = [] + + class Opener: + def open(self, request, timeout): + calls.append(request.full_url) + if len(calls) == 1: + response = truncated_error_response(503, {"Retry-After": "1"}) + failed_responses.append(response) + raise urllib.error.HTTPError( + request.full_url, 503, "failed", response.headers, response + ) + return io.BytesIO(b"{}") + + monkeypatch.setattr( + client["urllib"].request, "build_opener", lambda handler: Opener() + ) + assert client["public_read"]("https://api.github.com/example") == b"{}" + assert calls == ["https://api.github.com/example"] * 2 + assert sleeps == [1] + assert failed_responses[0].closed + + +def test_public_fetch_caps_retries_after_persistent_truncated_chunked_error( + monkeypatch, fetch_clock +): + client, _, sleeps = fetch_clock + calls = [] + failed_responses = [] + + class Opener: + def open(self, request, timeout): + calls.append(request.full_url) + response = truncated_error_response( + 503, + {"Retry-After": "2", "X-GitHub-Request-Id": "request-id"}, + ) + failed_responses.append(response) + raise urllib.error.HTTPError( + request.full_url, 503, "failed", response.headers, response + ) + + monkeypatch.setattr( + client["urllib"].request, "build_opener", lambda handler: Opener() + ) + with pytest.raises(ValueError, match=r"HTTP 503.*retry-after=2.*3 attempts.*90s"): + client["public_read"]("https://api.github.com/example") + assert len(calls) == 3 + assert sleeps == [2, 2] + assert all(response.closed for response in failed_responses) + + +def test_public_fetch_reports_nonretryable_truncated_chunked_error( + monkeypatch, fetch_clock +): + client, _, sleeps = fetch_clock + calls = [] + failed_responses = [] + + class Opener: + def open(self, request, timeout): + calls.append(request.full_url) + response = truncated_error_response( + 404, {"X-GitHub-Request-Id": "request-id"} + ) + failed_responses.append(response) + raise urllib.error.HTTPError( + request.full_url, 404, "failed", response.headers, response + ) + + monkeypatch.setattr( + client["urllib"].request, "build_opener", lambda handler: Opener() + ) + with pytest.raises( + ValueError, match=r"HTTP 404.*x-github-request-id=request-id.*public access" + ): + client["public_read"]("https://api.github.com/example") + assert calls == ["https://api.github.com/example"] + assert sleeps == [] + assert failed_responses[0].closed + + +@pytest.mark.parametrize( + "status,headers,oversleep,attempts,waits", + [ + (503, {}, 0, 3, [1, 1]), + (429, {"Retry-After": "91"}, 0, 1, []), + (403, {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "4600"}, 0, 1, []), + (503, {"Retry-After": "50"}, 0, 2, [50]), + (503, {"Retry-After": "1"}, 90, 1, [1]), + ], +) +def test_public_fetch_stops_at_attempt_or_time_budget( + monkeypatch, fetch_clock, status, headers, oversleep, attempts, waits +): + client, clock, sleeps = fetch_clock + calls = [] + real_sleep = client["public_read"].__globals__["time"].sleep + + def delayed_sleep(seconds): + real_sleep(seconds) + clock[0] += oversleep + + client["public_read"].__globals__["time"].sleep = delayed_sleep + + class Opener: + def open(self, request, timeout): + calls.append(request.full_url) + raise urllib.error.HTTPError( + request.full_url, status, "failed", headers, None + ) + + monkeypatch.setattr( + client["urllib"].request, "build_opener", lambda handler: Opener() + ) + with pytest.raises( + ValueError, match=rf"HTTP {status}.*retry later.*{attempts} attempts.*90s" + ): + client["public_read"]("https://api.github.com/example") + assert len(calls) == attempts + assert sleeps == waits + + +def test_public_failure_retains_only_bounded_sanitized_diagnostics(monkeypatch): + client = runpy.run_path(str(RUNTIME / "configuration.py")) + reads = [] + + class Body(io.BytesIO): + def read(self, size): + reads.append(size) + return super().read(size) + + body = Body(json.dumps({"message": "denied\n\x1b" + "x" * 600}).encode()) + headers = { + "X-GitHub-Request-Id": "request\n\x1b-id", + "X-RateLimit-Limit": "60", + "X-RateLimit-Remaining": "38", + "X-RateLimit-Reset": "2000", + "X-RateLimit-Resource": "core", + "Set-Cookie": "must-not-be-retained", + } class Opener: def open(self, request, timeout): - raise urllib.error.HTTPError(request.full_url, 404, "missing", {}, None) + raise urllib.error.HTTPError(request.full_url, 403, "failed", headers, body) monkeypatch.setattr( client["urllib"].request, "build_opener", lambda handler: Opener() ) - with pytest.raises(ValueError, match="HTTP 404.*public access"): + with pytest.raises(ValueError) as result: client["public_read"]("https://api.github.com/example") + diagnostic = str(result.value) + assert "GitHub message: denied " in diagnostic + assert "x" * 513 not in diagnostic + assert "x-github-request-id=request -id" in diagnostic + for key in ("limit", "remaining", "reset", "resource"): + assert f"x-ratelimit-{key}=" in diagnostic + assert "must-not-be-retained" not in diagnostic + assert "\n" not in diagnostic and "\x1b" not in diagnostic + assert reads == [4096] and body.closed def test_pinned_source_uses_the_exact_commit_without_resolving_a_branch(