From 06ab1c878e86c5110d8911945ef0ade58cac0a0d Mon Sep 17 00:00:00 2001 From: shay Date: Sat, 22 Aug 2026 16:10:26 -0700 Subject: [PATCH] fix(fetcher): guard REST calls so a rate limit can't poison user records The five REST calls parsed `.json()` with no status check, so a 403 {"message": "API rate limit exceeded..."} body was returned as user data. `_is_github_not_found` only matched "Not Found", so it was recorded as a successful fetch and upsert_user overwrote the user's last-good row. Every user touched during the exhaustion window then served a blank card for up to 24h while /metrics reported ok. Reuse the existing `_raise_if_transient` on all five so exhaustion raises GitHubTransientError before the upsert, preserving last-good and letting the caller retry. `_raise_if_transient` was GraphQL-shaped and crashed on the JSON arrays the list endpoints return, so it now ignores non-dict bodies. A rate limit inside the per-repo fan-out aborts the fetch; a 404 on a single repo stays non-fatal. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS --- fetcher/src/api.py | 6 ++ fetcher/src/github.py | 34 +++++++-- fetcher/tests/test_api.py | 11 +++ fetcher/tests/test_github.py | 136 +++++++++++++++++++++++++++++++++++ 4 files changed, 181 insertions(+), 6 deletions(-) diff --git a/fetcher/src/api.py b/fetcher/src/api.py index 88df6e0..8987fe5 100644 --- a/fetcher/src/api.py +++ b/fetcher/src/api.py @@ -242,6 +242,12 @@ def _is_github_not_found(data: dict) -> bool: return True if isinstance(user, dict) and user.get("message") == "Not Found": return True + # An error body (rate limit, abuse detection, anything else GitHub answers + # with a bare {"message": ...}) carries no login. It is not user data and + # must never be recorded as a successful fetch. github.py raises + # GitHubTransientError before we get here in practice; this is the backstop. + if isinstance(user, dict) and "login" not in user: + return True return False diff --git a/fetcher/src/github.py b/fetcher/src/github.py index cbc25c4..e7f2cf3 100644 --- a/fetcher/src/github.py +++ b/fetcher/src/github.py @@ -58,12 +58,18 @@ def _raise_if_transient(resp) -> None: # budget at 0 (or a "secondary rate limit" message). if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0": raise GitHubTransientError("REST rate limit exhausted") + if resp.status_code == 403 and "rate limit" in (resp.text or "").lower(): + raise GitHubTransientError("REST rate limit exhausted") # GraphQL reports rate limits as HTTP 200 with an `errors` array — the same # 200 that a valid response uses — so the body has to be inspected. try: body = resp.json() except ValueError: return + # REST list endpoints (events, repos, contributors) answer with a JSON + # array — only a GraphQL-shaped object can carry an `errors` block. + if not isinstance(body, dict): + return for err in (body.get("errors") or []): if err.get("type") in ("RATE_LIMITED", "SERVICE_UNAVAILABLE"): raise GitHubTransientError(err.get("message") or err.get("type")) @@ -163,23 +169,27 @@ class DirectAPISource: def fetch_user_data(self, username: str) -> dict: """Fetch user profile data.""" _assert_username(username) - return requests.get( + resp = requests.get( f"{self.base}/users/{username}", headers=self.headers, timeout=config.API_TIMEOUT, - ).json() + ) + _raise_if_transient(resp) + return resp.json() def fetch_repos(self, username: str) -> list: """Fetch user repositories (owned + contributed to).""" _assert_username(username) def _get(repo_type: str): - return requests.get( + resp = requests.get( f"{self.base}/users/{username}/repos", headers=self.headers, params={"per_page": 100, "sort": "pushed", "type": repo_type}, timeout=config.API_TIMEOUT, - ).json() + ) + _raise_if_transient(resp) + return resp.json() # The two REST calls are independent — fire them in parallel so the # second isn't waiting on the first to come back. @@ -209,8 +219,10 @@ class DirectAPISource: headers=self.headers, params={"per_page": 100}, timeout=config.API_TIMEOUT, - ).json() - return resp if isinstance(resp, list) else [] + ) + _raise_if_transient(resp) + events = resp.json() + return events if isinstance(events, list) else [] def fetch_commits(self, username: str, repos: list = None) -> list: """ @@ -529,6 +541,7 @@ class DirectAPISource: timeout=config.API_TIMEOUT ) + _raise_if_transient(resp) if resp.ok: contributors = resp.json() # Filter by minimum commits @@ -536,6 +549,8 @@ class DirectAPISource: c for c in contributors if c.get("contributions", 0) >= min_commits ] + except GitHubTransientError: + raise except Exception as e: print(f"Warning: Failed to fetch contributors from {repo_name}: {e}") @@ -622,9 +637,12 @@ class DirectAPISource: headers=self.headers, timeout=config.API_TIMEOUT, ) + _raise_if_transient(resp) if resp.ok: data = resp.json() return data if isinstance(data, dict) else {} + except GitHubTransientError: + raise except Exception: pass return {} @@ -729,6 +747,8 @@ def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None: i = futures[fut] try: repos[i]["language_bytes"] = fut.result() or {} + except GitHubTransientError: + raise except Exception: repos[i]["language_bytes"] = {} @@ -803,6 +823,8 @@ def _fetch_collaborators_data( full_name = futures[fut] try: contributors_by_repo[full_name] = fut.result() or [] + except GitHubTransientError: + raise except Exception as e: print(f" failed to fetch contributors for {full_name}: {e}") contributors_by_repo[full_name] = [] diff --git a/fetcher/tests/test_api.py b/fetcher/tests/test_api.py index 5617258..7c6ca5a 100644 --- a/fetcher/tests/test_api.py +++ b/fetcher/tests/test_api.py @@ -192,3 +192,14 @@ def test_fetch_async_dedupes_inflight(client, monkeypatch): break threading.Event().wait(0.05) assert fetch_calls["n"] == 1 + + +def test_rate_limit_body_is_not_classified_as_valid_user_data(): + # A rate-limit body reaching the classifier must never take the success + # branch — that is what overwrote a good record with a blank card. + data = {"user": {"message": "API rate limit exceeded for user ID 123.", + "documentation_url": "https://docs.github.com/"}} + assert apimod._is_github_not_found(data) is True + assert apimod._is_github_not_found({"user": {"login": "alice"}}) is False + assert apimod._is_github_not_found({"user": {"message": "Not Found"}}) is True + assert apimod._is_github_not_found({"user": None}) is True diff --git a/fetcher/tests/test_github.py b/fetcher/tests/test_github.py index fff8d98..62be102 100644 --- a/fetcher/tests/test_github.py +++ b/fetcher/tests/test_github.py @@ -114,3 +114,139 @@ def test_commit_count_zero_on_not_found_is_not_transient(): ) src = github.DirectAPISource(token="t") assert src.fetch_commit_count("ghost", []) == 0 + + +# --- REST rate-limit guards ------------------------------------------------- +# The REST calls used to hand `.json()` straight back, so a 403 rate-limit body +# ({"message": "API rate limit exceeded for user ID ..."}) was persisted as if +# it were real data, wiping the user's last-good record for up to 24h. + +RATE_LIMIT_BODY = { + "message": "API rate limit exceeded for user ID 123.", + "documentation_url": "https://docs.github.com/rest/overview/rate-limits", +} +RATE_LIMIT_HEADERS = {"X-RateLimit-Remaining": "0"} + + +@responses.activate +def test_fetch_user_data_raises_on_rest_rate_limit(): + responses.add( + responses.GET, "https://api.github.com/users/alice", + json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_user_data("alice") + + +@responses.activate +def test_fetch_user_data_raises_on_rate_limit_without_header(): + # Secondary rate limits come back as 403 without the remaining-budget + # header — the message is the only signal. + responses.add( + responses.GET, "https://api.github.com/users/alice", + json={"message": "You have exceeded a secondary rate limit."}, status=403, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_user_data("alice") + + +@responses.activate +def test_fetch_repos_raises_on_rest_rate_limit(): + responses.add( + responses.GET, "https://api.github.com/users/alice/repos", + json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_repos("alice") + + +@responses.activate +def test_fetch_events_raises_on_rest_rate_limit(): + responses.add( + responses.GET, "https://api.github.com/users/alice/events", + json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_events("alice") + + +@responses.activate +def test_fetch_repo_contributors_raises_on_rest_rate_limit(): + responses.add( + responses.GET, "https://api.github.com/repos/alice/proj/contributors", + json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_repo_contributors("alice/proj") + + +@responses.activate +def test_fetch_repo_languages_raises_on_rest_rate_limit(): + responses.add( + responses.GET, "https://api.github.com/repos/alice/proj/languages", + json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_repo_languages("alice/proj") + + +@responses.activate +def test_single_repo_404_stays_non_fatal(): + # A deleted/renamed repo is a real per-repo answer, not a budget problem: + # it must keep degrading gracefully instead of aborting the whole fetch. + responses.add( + responses.GET, "https://api.github.com/repos/alice/gone/languages", + json={"message": "Not Found"}, status=404, + ) + responses.add( + responses.GET, "https://api.github.com/repos/alice/gone/contributors", + json={"message": "Not Found"}, status=404, + ) + src = github.DirectAPISource(token="t") + assert src.fetch_repo_languages("alice/gone") == {} + assert src.fetch_repo_contributors("alice/gone") == [] + + +@responses.activate +def test_rest_success_path_unchanged(): + responses.add( + responses.GET, "https://api.github.com/users/alice", + json={"login": "alice", "followers": 5}, status=200, + ) + responses.add( + responses.GET, "https://api.github.com/users/alice/events", + json=[{"type": "PushEvent"}], status=200, + ) + responses.add( + responses.GET, "https://api.github.com/repos/alice/proj/languages", + json={"Python": 100}, status=200, + ) + responses.add( + responses.GET, "https://api.github.com/repos/alice/proj/contributors", + json=[{"login": "bob", "contributions": 4}], status=200, + ) + src = github.DirectAPISource(token="t") + assert src.fetch_user_data("alice")["login"] == "alice" + assert src.fetch_events("alice") == [{"type": "PushEvent"}] + assert src.fetch_repo_languages("alice/proj") == {"Python": 100} + assert src.fetch_repo_contributors("alice/proj") == [{"login": "bob", "contributions": 4}] + + +@responses.activate +def test_rate_limited_repo_languages_aborts_whole_fetch(): + # A rate limit inside the per-repo fan-out means the budget is gone, so it + # must propagate rather than being swallowed into an empty breakdown. + responses.add( + responses.GET, "https://api.github.com/repos/alice/proj/languages", + json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS, + ) + src = github.DirectAPISource(token="t") + repos = [{"full_name": "alice/proj"}] + with pytest.raises(github.GitHubTransientError): + github._enrich_repo_languages(repos, src)