|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# (c) Copyright IBM Corp. 2026 |
| 3 | + |
| 4 | +""" |
| 5 | +Downgrades any installed packages that were released within the 5-day grace |
| 6 | +period to their latest safe version. Run after pip install so that CI tests |
| 7 | +only exercise versions that have cleared the supply-chain safety window. |
| 8 | +
|
| 9 | +Usage: |
| 10 | + python scripts/pin_safe_versions.py [requirements_file] |
| 11 | +
|
| 12 | +If a requirements file is given, only the packages listed there are checked. |
| 13 | +Otherwise every installed package is checked (slow). |
| 14 | +""" |
| 15 | +from typing import Any, Union |
| 16 | + |
| 17 | + |
| 18 | +import re |
| 19 | +import subprocess |
| 20 | +import sys |
| 21 | +from datetime import datetime, timedelta |
| 22 | + |
| 23 | +import requests |
| 24 | +from packaging.specifiers import SpecifierSet |
| 25 | +from packaging.version import Version |
| 26 | + |
| 27 | +GRACE_PERIOD_DAYS = 5 |
| 28 | + |
| 29 | + |
| 30 | +def _get_pypi_releases(package_name: str) -> list[Any]: |
| 31 | + try: |
| 32 | + r = requests.get(f"https://pypi.org/pypi/{package_name}/json", timeout=10) |
| 33 | + r.raise_for_status() |
| 34 | + data = r.json() |
| 35 | + except Exception: |
| 36 | + return [] |
| 37 | + |
| 38 | + current_python = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" |
| 39 | + |
| 40 | + result = [] |
| 41 | + for ver, files in data["releases"].items(): |
| 42 | + if not files or re.search(r"(a|b|rc|dev)\d*$", ver, re.I): |
| 43 | + continue |
| 44 | + try: |
| 45 | + Version(ver) |
| 46 | + except Exception: |
| 47 | + continue |
| 48 | + requires_python = next( |
| 49 | + (f["requires_python"] for f in files if f.get("requires_python")), None |
| 50 | + ) |
| 51 | + if requires_python: |
| 52 | + try: |
| 53 | + if not SpecifierSet(requires_python).contains(current_python): |
| 54 | + continue |
| 55 | + except Exception: |
| 56 | + pass |
| 57 | + upload_time = files[-1].get("upload_time_iso_8601", "") |
| 58 | + match = re.search(r"([\d-]+)T", upload_time) |
| 59 | + if not match: |
| 60 | + continue |
| 61 | + date = datetime.strptime(match[1], "%Y-%m-%d").date() |
| 62 | + result.append((ver, date)) |
| 63 | + result.sort(key=lambda x: (x[1], Version(x[0])), reverse=True) |
| 64 | + return result |
| 65 | + |
| 66 | + |
| 67 | +def _get_safe_version(releases: list[Any]) -> Union[tuple[Any, Any], tuple[None, None]]: |
| 68 | + today = datetime.today().date() |
| 69 | + grace_cutoff = today - timedelta(days=GRACE_PERIOD_DAYS) |
| 70 | + for i, (ver, date) in enumerate(releases): |
| 71 | + grace_end = date + timedelta(days=GRACE_PERIOD_DAYS) |
| 72 | + superseded = any(nd < grace_end for _, nd in releases[:i]) |
| 73 | + if not superseded and date <= grace_cutoff: |
| 74 | + return ver, date |
| 75 | + return None, None |
| 76 | + |
| 77 | + |
| 78 | +def _installed_packages() -> dict[Any, Any]: |
| 79 | + result = subprocess.run(["pip", "freeze"], capture_output=True, text=True, check=True) |
| 80 | + packages = {} |
| 81 | + for line in result.stdout.strip().splitlines(): |
| 82 | + if "==" in line: |
| 83 | + pkg, ver = line.split("==", 1) |
| 84 | + packages[pkg.lower()] = ver.strip() |
| 85 | + return packages |
| 86 | + |
| 87 | + |
| 88 | +def _parse_req_file(path: str) -> set[str]: |
| 89 | + names = set() |
| 90 | + try: |
| 91 | + with open(path) as f: |
| 92 | + for line in f: |
| 93 | + line = line.strip() |
| 94 | + if not line or line.startswith("#"): |
| 95 | + continue |
| 96 | + if line.startswith("-r "): |
| 97 | + # Recurse into included requirement files (same directory) |
| 98 | + import os |
| 99 | + included = os.path.join(os.path.dirname(path), line[3:].strip()) |
| 100 | + names |= _parse_req_file(included) |
| 101 | + continue |
| 102 | + if line.startswith("-"): |
| 103 | + continue |
| 104 | + name = re.split(r"[><=!;[\s]", line)[0].strip().lower() |
| 105 | + if name: |
| 106 | + names.add(name) |
| 107 | + except FileNotFoundError: |
| 108 | + print(f"Warning: requirements file '{path}' not found.") |
| 109 | + return names |
| 110 | + |
| 111 | + |
| 112 | +def main() -> None: |
| 113 | + packages_to_check = None |
| 114 | + if len(sys.argv) > 1: |
| 115 | + packages_to_check = _parse_req_file(sys.argv[1]) |
| 116 | + print(f"Checking {len(packages_to_check)} packages from {sys.argv[1]}") |
| 117 | + |
| 118 | + installed = _installed_packages() |
| 119 | + today = datetime.today().date() |
| 120 | + grace_cutoff = today - timedelta(days=GRACE_PERIOD_DAYS) |
| 121 | + |
| 122 | + to_pin = [] |
| 123 | + for pkg, installed_ver in installed.items(): |
| 124 | + if packages_to_check is not None and pkg not in packages_to_check: |
| 125 | + continue |
| 126 | + |
| 127 | + releases = _get_pypi_releases(pkg) |
| 128 | + if not releases: |
| 129 | + continue |
| 130 | + |
| 131 | + installed_date = next((d for v, d in releases if v == installed_ver), None) |
| 132 | + if installed_date is None or installed_date <= grace_cutoff: |
| 133 | + continue |
| 134 | + |
| 135 | + safe_ver, safe_date = _get_safe_version(releases) |
| 136 | + if safe_ver is None: |
| 137 | + print( |
| 138 | + f"[grace-period] {pkg}=={installed_ver} (released {installed_date}) " |
| 139 | + f"is within grace period but no safe version exists — skipping" |
| 140 | + ) |
| 141 | + continue |
| 142 | + |
| 143 | + print( |
| 144 | + f"[grace-period] {pkg}: {installed_ver} (released {installed_date}) " |
| 145 | + f"→ pinning to {safe_ver} (released {safe_date})" |
| 146 | + ) |
| 147 | + to_pin.append(f"{pkg}=={safe_ver}") |
| 148 | + |
| 149 | + if to_pin: |
| 150 | + print(f"\nPinning {len(to_pin)} package(s) to grace-period-safe versions...") |
| 151 | + subprocess.run(["pip", "install"] + to_pin, check=True) |
| 152 | + print("Grace period enforcement complete.") |
| 153 | + else: |
| 154 | + print("All checked packages comply with the grace period.") |
| 155 | + |
| 156 | + |
| 157 | +if __name__ == "__main__": |
| 158 | + main() |
0 commit comments