diff --git a/README.md b/README.md index c80d86e..ee22e1d 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ The validator checks local Markdown structure, GitHub URL syntax, title/URL cons See [Catalog Schema and Validation](docs/CATALOG_SCHEMA.md) for the record format, taxonomy normalization, and limitations. +To refresh read-only upstream GitHub metadata such as archived status, last push date, and license identifier, use [Upstream Status Refresh](docs/UPSTREAM_STATUS.md). This optional tool uses the GitHub REST API, requires no third-party packages, and is bounded to 50 repositories by default without a token. + ## Research methodology and limits The catalog's historical discovery process used repository metadata and keyword matching. The original PyGithub discovery scripts are not present in this repository, so automated upstream discovery and categorization are not currently reproducible from this checkout. diff --git a/docs/UPSTREAM_STATUS.md b/docs/UPSTREAM_STATUS.md new file mode 100644 index 0000000..900c001 --- /dev/null +++ b/docs/UPSTREAM_STATUS.md @@ -0,0 +1,23 @@ +# Upstream Repository Status Refresh + +Run a bounded GitHub metadata refresh from the catalog root: + +```bash +python scripts/upstream_status.py --limit 25 --output reports/upstream-status.json +``` + +Set `GITHUB_TOKEN` in the environment to use authenticated GitHub API rate limits. A fine-grained token with read-only metadata access is sufficient; no write permission is needed. Never commit the token. Without a token, the default maximum is 50 repositories per run. The tool uses only Python's standard library and makes read-only GitHub REST API requests. + +## Report fields + +For each repository, the report records the API status, archived/disabled flags, default branch, last push timestamp, license SPDX identifier, visibility, and canonical upstream URL when returned. + +## Interpretation + +- `archived=true` means GitHub marks the repository as archived. +- `not_found_or_private` is intentionally ambiguous. A 404 does not reveal whether the repository was deleted, renamed, or made private. +- `pushed_at` is activity metadata, not proof of active maintenance or security. +- `license_spdx_id=null` means the API did not identify a license. It is not permission to reuse the code. +- A successful API response does not establish that the repository is officially operated by the named agency. + +The tool does not clone repositories, inspect source code, run dependencies, check vulnerabilities, or make changes to the catalog. Review the JSON report before updating any cards. diff --git a/scripts/catalog_audit.py b/scripts/catalog_audit.py index d87ded1..eafd83f 100644 --- a/scripts/catalog_audit.py +++ b/scripts/catalog_audit.py @@ -145,6 +145,7 @@ def audit_catalog(root: str | Path) -> dict: return { "catalog_cards_validated": len(records), + "repositories": sorted(paths_by_repo), "errors": errors, "warnings": warnings, "duplicate_repository_references": duplicate_references, diff --git a/scripts/upstream_status.py b/scripts/upstream_status.py new file mode 100644 index 0000000..96ad44d --- /dev/null +++ b/scripts/upstream_status.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Refresh upstream GitHub repository metadata for the local catalog.""" +from __future__ import annotations + +import argparse +import json +import os +import sys +import time +from datetime import datetime, timezone +from pathlib import Path +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + +from scripts.catalog_audit import audit_catalog + + +def fetch_repository_status(repository: str, token: str | None = None, opener=urlopen) -> dict: + request = Request( + f"https://api.github.com/repos/{repository}", + headers={ + "Accept": "application/vnd.github+json", + "User-Agent": "Protocol-Helios-Catalog-Audit", + **({"Authorization": f"Bearer {token}"} if token else {}), + }, + method="GET", + ) + try: + with opener(request, timeout=15) as response: + payload = json.loads(response.read().decode("utf-8")) + if not isinstance(payload, dict): + return {"repository": repository, "status": "invalid_response"} + license_data = payload.get("license") or {} + return { + "repository": repository, + "status": "checked", + "html_url": payload.get("html_url"), + "archived": payload.get("archived"), + "disabled": payload.get("disabled"), + "default_branch": payload.get("default_branch"), + "pushed_at": payload.get("pushed_at"), + "license_spdx_id": license_data.get("spdx_id"), + "visibility": payload.get("visibility"), + } + except HTTPError as error: + if error.code == 404: + status = "not_found_or_private" + elif error.code == 403 and (error.headers or {}).get("X-RateLimit-Remaining") == "0": + status = "rate_limited" + elif error.code == 403: + status = "forbidden" + else: + status = f"http_{error.code}" + return {"repository": repository, "status": status} + except URLError: + return {"repository": repository, "status": "network_error"} + except (UnicodeDecodeError, json.JSONDecodeError): + return {"repository": repository, "status": "invalid_response"} + + +def audit_upstreams( + root: str | Path, + limit: int | None = None, + delay: float | None = None, + token: str | None = None, + opener=urlopen, + sleeper=time.sleep, +) -> dict: + catalog = audit_catalog(root) + if catalog["errors"]: + raise ValueError("Catalog validation errors must be fixed before checking upstream status.") + repositories = catalog["repositories"] + if limit is None: + limit = len(repositories) if token else min(50, len(repositories)) + if limit < 1: + raise ValueError("limit must be at least 1") + selected = repositories[:limit] + if delay is None: + delay = 0.15 if token else 1.1 + if delay < 0: + raise ValueError("delay cannot be negative") + + results = [] + for index, repository in enumerate(selected): + result = fetch_repository_status(repository, token=token, opener=opener) + results.append(result) + if result["status"] == "rate_limited": + break + if index < len(selected) - 1: + sleeper(delay) + + counts = {} + for result in results: + counts[result["status"]] = counts.get(result["status"], 0) + 1 + + return { + "checked_at": datetime.now(timezone.utc).isoformat(), + "source": "GitHub REST API", + "authenticated": bool(token), + "catalog_repository_count": len(repositories), + "requested_limit": limit, + "attempted_count": len(results), + "not_attempted_count": len(repositories) - len(results), + "status_counts": counts, + "results": results, + "limitations": [ + "This checks GitHub repository metadata only; it does not inspect source code, dependencies, releases, or security alerts.", + "A 404 response can mean missing or private; it does not prove why the repository is unavailable.", + "A recent push does not prove active maintenance or security.", + "GitHub API metadata does not establish government affiliation or endorsement.", + "No token checks at most 50 repositories by default to stay within conservative unauthenticated rate limits.", + ], + } + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default=".", help="Catalog repository root") + parser.add_argument("--limit", type=int, help="Maximum repositories to check") + parser.add_argument("--delay", type=float, help="Seconds between API requests") + parser.add_argument("--output", help="Optional JSON report path") + args = parser.parse_args(argv) + + token = os.environ.get("GITHUB_TOKEN") + try: + report = audit_upstreams(args.root, args.limit, args.delay, token) + except (OSError, ValueError) as error: + print(f"Upstream audit failed: {error}", file=sys.stderr) + return 2 + + rendered = json.dumps(report, indent=2, sort_keys=True) + if args.output: + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(rendered + "\n", encoding="utf-8") + print(rendered) + return 1 if report["status_counts"].get("rate_limited") else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_upstream_status.py b/tests/test_upstream_status.py new file mode 100644 index 0000000..234d6e3 --- /dev/null +++ b/tests/test_upstream_status.py @@ -0,0 +1,96 @@ +import json +import unittest +from urllib.error import HTTPError + +from scripts.upstream_status import audit_upstreams, fetch_repository_status + + +class FakeResponse: + def __init__(self, payload): + self.payload = payload + + def read(self): + return json.dumps(self.payload).encode("utf-8") + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + +class UpstreamStatusTests(unittest.TestCase): + def test_parses_archived_and_license_metadata(self): + payload = { + "html_url": "https://github.com/example/project", + "archived": True, + "disabled": False, + "default_branch": "main", + "pushed_at": "2024-01-01T00:00:00Z", + "license": {"spdx_id": "MIT"}, + "visibility": "public", + } + captured = {} + def opener(request, timeout): + captured["request"] = request + return FakeResponse(payload) + + result = fetch_repository_status( + "example/project", + token="read-only-token", + opener=opener, + ) + self.assertEqual(result["status"], "checked") + self.assertEqual(captured["request"].get_header("Authorization"), "Bearer read-only-token") + self.assertTrue(result["archived"]) + self.assertEqual(result["license_spdx_id"], "MIT") + + def test_distinguishes_missing_or_private_from_rate_limit(self): + def not_found(request, timeout): + raise HTTPError(request.full_url, 404, "Not Found", {}, None) + + def rate_limited(request, timeout): + error = HTTPError(request.full_url, 403, "rate limited", {}, None) + error.headers = {"X-RateLimit-Remaining": "0"} + raise error + + self.assertEqual( + fetch_repository_status("example/missing", opener=not_found)["status"], + "not_found_or_private", + ) + self.assertEqual( + fetch_repository_status("example/project", opener=rate_limited)["status"], + "rate_limited", + ) + + def test_defaults_to_small_unauthenticated_batch(self): + calls = [] + + def opener(request, timeout): + calls.append(request.full_url) + return FakeResponse({ + "html_url": request.full_url, + "archived": False, + "disabled": False, + "default_branch": "main", + "pushed_at": None, + "license": None, + "visibility": "public", + }) + + report = audit_upstreams( + root=".", + token=None, + limit=1, + delay=0, + opener=opener, + sleeper=lambda _: None, + ) + self.assertEqual(report["attempted_count"], 1) + self.assertFalse(report["authenticated"]) + self.assertEqual(len(calls), 1) + self.assertEqual(report["not_attempted_count"], report["catalog_repository_count"] - 1) + + +if __name__ == "__main__": + unittest.main()