diff --git a/pkgs/id/scripts/update-nixpkgs-inputs.py b/pkgs/id/scripts/update-nixpkgs-inputs.py index c9d0ec2edd..56788c98e1 100755 --- a/pkgs/id/scripts/update-nixpkgs-inputs.py +++ b/pkgs/id/scripts/update-nixpkgs-inputs.py @@ -19,13 +19,157 @@ ./scripts/update-nixpkgs-inputs.py master # master (or no ref) inputs ./scripts/update-nixpkgs-inputs.py nixos-unstable # nixos-unstable inputs ./scripts/update-nixpkgs-inputs.py master nixos-unstable # both categories, combined summary + +Cache gate (#4553): inputs whose original.ref is "nixos-unstable" are NOT +updated to branch HEAD — HEAD runs days ahead of what Hydra has built and +cache.nixos.org serves, so a HEAD pin can turn the next system build into +a multi-day source build (see #2715). Gated inputs are pinned instead to +the newest revision Hydra has fully built for the channel: the `tested` +job of jobset nixos:unstable, resolved via + GET /job/nixos/unstable/tested/latest-finished -> jobsetevals[0] + GET /eval/ -> jobsetevalinputs.nixpkgs.revision +The pin rewrites only the input's `locked` entry (rev + narHash + +lastModified from a real `nix flake metadata` fetch of that revision); +`original` — including ref "nixos-unstable" — is left untouched so input +discovery keeps matching. The gate fails closed: if the Hydra lookups +fail or return an unexpected shape, the script exits non-zero before +touching flake.lock. The Hydra base URL can be overridden with the +UPDATE_NIXPKGS_HYDRA_URL environment variable (used by the tests). """ import json +import os +import re +import ssl import subprocess import sys +import urllib.request from pathlib import Path +GATED_REF = "nixos-unstable" +HYDRA_BASE_URL_ENV = "UPDATE_NIXPKGS_HYDRA_URL" +DEFAULT_HYDRA_BASE_URL = "https://hydra.nixos.org" +HYDRA_LATEST_FINISHED_PATH = "/job/nixos/unstable/tested/latest-finished" +REV_RE = re.compile(r"^[0-9a-f]{40}$") + + +class HydraGateError(Exception): + """The Hydra cache gate could not produce a trustworthy revision.""" + + +def https_context(): + """SSL context for Hydra requests, with verification ON. + + The .py shebang runs under `uv run --script`, whose standalone + Python builds can fail to locate a CA bundle at all (0 certs + loaded, every HTTPS request CERTIFICATE_VERIFY_FAILED) even on a + healthy system. When the default context comes up empty, point it + at the usual system bundle locations instead of failing.""" + ctx = ssl.create_default_context() + if ctx.get_ca_certs(): + return ctx + for cafile in ( + os.environ.get("SSL_CERT_FILE"), + "/etc/ssl/certs/ca-certificates.crt", # Debian / NixOS + "/etc/pki/tls/certs/ca-bundle.crt", # RHEL family + "/etc/ssl/cert.pem", # macOS / Alpine + ): + if cafile and os.path.exists(cafile): + return ssl.create_default_context(cafile=cafile) + return ctx + + +def fetch_hydra_json(url): + """GET a Hydra JSON endpoint (follows redirects; Hydra content- + negotiates on the Accept header and serves HTML without it).""" + req = urllib.request.Request(url, headers={"Accept": "application/json"}) + with urllib.request.urlopen(req, timeout=60, context=https_context()) as resp: + return json.load(resp) + + +def parse_latest_finished_eval_id(data): + """Extract the jobset eval id from a latest-finished build payload.""" + if not isinstance(data, dict): + raise HydraGateError("latest-finished payload is not a JSON object") + status = data.get("buildstatus") + if status is not None and status != 0: + raise HydraGateError( + f"latest finished 'tested' build did not succeed (buildstatus={status})" + ) + evals = data.get("jobsetevals") + if not isinstance(evals, list) or not evals: + raise HydraGateError("latest-finished payload has no jobsetevals") + eval_id = evals[0] + if isinstance(eval_id, str) and eval_id.isdigit(): + eval_id = int(eval_id) + if not isinstance(eval_id, int) or isinstance(eval_id, bool): + raise HydraGateError(f"unexpected jobsetevals[0]: {eval_id!r}") + return eval_id + + +def parse_eval_revision(data): + """Extract the nixpkgs revision from a Hydra eval payload.""" + if not isinstance(data, dict): + raise HydraGateError("eval payload is not a JSON object") + inputs = data.get("jobsetevalinputs") + if not isinstance(inputs, dict): + raise HydraGateError("eval payload has no jobsetevalinputs") + nixpkgs = inputs.get("nixpkgs") + if not isinstance(nixpkgs, dict): + raise HydraGateError("eval payload has no nixpkgs jobset eval input") + rev = nixpkgs.get("revision") + if not isinstance(rev, str) or not REV_RE.match(rev): + raise HydraGateError(f"unexpected nixpkgs revision: {rev!r}") + return rev + + +def hydra_cached_revision(base_url=None): + """Newest nixos-unstable revision Hydra has fully built. + + Returns (revision, eval_id). Raises HydraGateError on any lookup + failure or unexpected response shape — callers must fail closed. + """ + base = ( + base_url or os.environ.get(HYDRA_BASE_URL_ENV) or DEFAULT_HYDRA_BASE_URL + ).rstrip("/") + try: + latest = fetch_hydra_json(base + HYDRA_LATEST_FINISHED_PATH) + except Exception as e: + raise HydraGateError( + f"cannot fetch {base + HYDRA_LATEST_FINISHED_PATH}: {e}" + ) from e + eval_id = parse_latest_finished_eval_id(latest) + try: + eval_data = fetch_hydra_json(f"{base}/eval/{eval_id}") + except Exception as e: + raise HydraGateError(f"cannot fetch {base}/eval/{eval_id}: {e}") from e + return parse_eval_revision(eval_data), eval_id + + +def fetch_locked_for_rev(rev): + """Fetch github:NixOS/nixpkgs@ with nix and return the locked + attrs (rev, narHash, lastModified, ...) a flake.lock entry needs. + Returns None if the fetch fails or the result does not check out.""" + result = subprocess.run( + ["nix", "flake", "metadata", f"github:NixOS/nixpkgs/{rev}", "--json"], + capture_output=True, + text=True, + ) + if result.returncode != 0: + return None + try: + locked = json.loads(result.stdout)["locked"] + except (ValueError, KeyError, TypeError): + return None + if not isinstance(locked, dict): + return None + # `nix flake metadata` annotates its result with __final; flake.lock + # locked entries do not carry it. + locked = {k: v for k, v in locked.items() if k != "__final"} + if locked.get("rev") != rev or not locked.get("narHash"): + return None + return locked + def load_flake_lock(repo_dir): """Load and parse flake.lock.""" @@ -67,6 +211,31 @@ def get_input_info(lock_data, input_name): return (rev, url, ref_display) +def get_input_node(lock_data, input_name): + """Return the lock node for a root input name, or None.""" + root_inputs = lock_data.get("nodes", {}).get("root", {}).get("inputs", {}) + node_name = root_inputs.get(input_name) + if not isinstance(node_name, str): + return None + return lock_data.get("nodes", {}).get(node_name) + + +def get_input_ref(lock_data, input_name): + """Return the input's original.ref (None when unset / not found).""" + node = get_input_node(lock_data, input_name) + if not node: + return None + return node.get("original", {}).get("ref") + + +def get_locked_rev(lock_data, input_name): + """Return the input's full locked revision (None when not locked).""" + node = get_input_node(lock_data, input_name) + if not node: + return None + return node.get("locked", {}).get("rev") + + def discover_inputs(lock_data, ref): """Discover NixOS/nixpkgs inputs by parsing flake.lock directly. @@ -127,6 +296,22 @@ def update_input(input_name, repo_dir): return result.returncode == 0 +def pin_input(input_name, repo_dir, locked): + """Pin an input to a pre-fetched locked entry, rewriting only the + node's `locked` in flake.lock (`original` stays untouched, so the + input's ref — and therefore discovery — is preserved). The dump + format matches nix's own flake.lock formatting byte for byte. + Returns True on success.""" + lock_data = load_flake_lock(repo_dir) + node = get_input_node(lock_data, input_name) + if node is None: + return False + node["locked"] = dict(locked) + with open(repo_dir / "flake.lock", "w") as f: + f.write(json.dumps(lock_data, indent=2) + "\n") + return get_locked_rev(load_flake_lock(repo_dir), input_name) == locked["rev"] + + def format_result_lines(results): """Format result detail lines grouped by source URL.""" url_order = [] @@ -233,25 +418,62 @@ def main(): refs = sys.argv[1:] if len(sys.argv) > 1 else [None] + # Planning pass: resolve, against the pristine lock, which inputs each + # requested ref will process (same discovery + cross-ref dedupe as the + # execution pass below). The cache gate must be resolved — and must + # fail closed — before any input is touched, so gated inputs are + # identified up front. + plan = [] seen_inputs = set() + gated_inputs = set() + initial_lock = load_flake_lock(repo_dir) + for ref in refs: + inputs = discover_inputs(initial_lock, ref) + new_inputs = [i for i in inputs if i not in seen_inputs] + seen_inputs.update(new_inputs) + plan.append((ref, inputs, new_inputs)) + for name in new_inputs: + if get_input_ref(initial_lock, name) == GATED_REF: + gated_inputs.add(name) + + gate_rev = None + gate_locked = None + if gated_inputs: + try: + gate_rev, gate_eval = hydra_cached_revision() + except HydraGateError as e: + print( + f"ERROR: Hydra cache gate failed: {e}\n" + f"Refusing to update {GATED_REF} inputs to uncached " + "revisions; flake.lock left untouched.", + file=sys.stderr, + ) + sys.exit(1) + gate_locked = fetch_locked_for_rev(gate_rev) + if gate_locked is None: + print( + f"ERROR: could not fetch github:NixOS/nixpkgs@{gate_rev} " + "with nix flake metadata; flake.lock left untouched.", + file=sys.stderr, + ) + sys.exit(1) + print( + f"Hydra gate: {GATED_REF} inputs pin to {gate_rev[:12]} " + f"(newest revision fully built by Hydra jobset nixos:unstable, " + f"eval {gate_eval})" + ) + all_ref_data = [] - for ref in refs: + for ref, inputs, new_inputs in plan: label = ref if ref else "all" ref_data = {"label": label, "results": [], "not_found": False} - lock_data = load_flake_lock(repo_dir) - inputs = discover_inputs(lock_data, ref) - if not inputs: ref_data["not_found"] = True all_ref_data.append(ref_data) continue - # Filter out already-seen inputs - new_inputs = [i for i in inputs if i not in seen_inputs] - seen_inputs.update(new_inputs) - if not new_inputs: all_ref_data.append(ref_data) continue @@ -264,6 +486,48 @@ def main(): lock_data = load_flake_lock(repo_dir) old_rev, source_url, input_ref = get_input_info(lock_data, input_name) + if input_name in gated_inputs: + if get_locked_rev(lock_data, input_name) == gate_rev: + ref_data["results"].append( + { + "name": input_name, + "status": "skipped", + "old_rev": old_rev, + "new_rev": None, + "url": source_url, + "ref": input_ref, + } + ) + elif pin_input(input_name, repo_dir, gate_locked): + lock_data = load_flake_lock(repo_dir) + new_rev, _, _ = get_input_info(lock_data, input_name) + ref_data["results"].append( + { + "name": input_name, + "status": "updated", + "old_rev": old_rev, + "new_rev": new_rev, + "url": source_url, + "ref": input_ref, + } + ) + else: + ref_data["results"].append( + { + "name": input_name, + "status": "failed", + "old_rev": old_rev, + "new_rev": None, + "url": source_url, + "ref": input_ref, + } + ) + print( + f"WARNING: failed to pin {input_name} to {gate_rev}", + file=sys.stderr, + ) + continue + if update_input(input_name, repo_dir): lock_data = load_flake_lock(repo_dir) new_rev, _, _ = get_input_info(lock_data, input_name) diff --git a/scripts/tests/test_update_nixpkgs_inputs.py b/scripts/tests/test_update_nixpkgs_inputs.py index d4532e7568..cd190b259c 100644 --- a/scripts/tests/test_update_nixpkgs_inputs.py +++ b/scripts/tests/test_update_nixpkgs_inputs.py @@ -19,6 +19,12 @@ propagate the exit status, and never re-run after a genuine failure (the update body executes exactly once). +- The #4553 cache-gate contract is pinned for BOTH .py copies: inputs + with original.ref "nixos-unstable" pin to the newest Hydra-fully-built + revision (never branch HEAD), only their `locked` entry is rewritten, + an already-pinned input is a no-op, and a Hydra failure exits non-zero + with flake.lock untouched. + Run: python3 -m unittest discover -s scripts/tests -p 'test_update_nixpkgs_inputs.py' """ @@ -370,3 +376,305 @@ def test_pkgs_id_copy(self): if __name__ == "__main__": unittest.main() + +import contextlib +import http.server +import threading + +# --- #4553 cache gate --------------------------------------------------- + +GATE_OLD_REV = "1" * 40 +GATE_TARGET_REV = "2" * 40 +GATE_OTHER_REV = "3" * 40 +GATE_NAR_HASH = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" +GATE_EVAL_ID = 424242 + +GATE_FLAKE_LOCK = { + "nodes": { + "root": { + "inputs": {"nixpkgs": "nixpkgs", "nixpkgs-unstable": "nixpkgs-unstable"} + }, + "nixpkgs": { + "original": {"type": "github", "owner": "NixOS", "repo": "nixpkgs"}, + "locked": { + "type": "github", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": GATE_OTHER_REV, + "narHash": "sha256-BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=", + "lastModified": 1700000000, + }, + }, + "nixpkgs-unstable": { + "original": { + "type": "github", + "owner": "NixOS", + "repo": "nixpkgs", + "ref": "nixos-unstable", + }, + "locked": { + "type": "github", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": GATE_OLD_REV, + "narHash": "sha256-CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC=", + "lastModified": 1700000001, + }, + }, + }, + "root": "root", + "version": 7, +} + + +class _HydraHandler(http.server.BaseHTTPRequestHandler): + payloads = {} + + def do_GET(self): + body = self.payloads.get(self.path) + if body is None: + self.send_response(404) + self.end_headers() + return + data = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *args): + pass + + +@contextlib.contextmanager +def _hydra_server(payloads=None): + if payloads is None: + payloads = { + "/job/nixos/unstable/tested/latest-finished": { + "buildstatus": 0, + "jobsetevals": [GATE_EVAL_ID], + }, + f"/eval/{GATE_EVAL_ID}": { + "jobsetevalinputs": {"nixpkgs": {"revision": GATE_TARGET_REV}} + }, + } + handler = type("Handler", (_HydraHandler,), {"payloads": payloads}) + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + server.server_close() + + +class TestHydraGateParsing(unittest.TestCase): + """Black-box: hydra_cached_revision runs against a local HTTP server + (via its base-URL parameter), so the real fetch + parse + fail-closed + behaviour is exercised without the network.""" + + GOOD_PAYLOADS = { + "/job/nixos/unstable/tested/latest-finished": { + "buildstatus": 0, + "jobsetevals": [GATE_EVAL_ID], + }, + f"/eval/{GATE_EVAL_ID}": { + "jobsetevalinputs": {"nixpkgs": {"revision": GATE_TARGET_REV}} + }, + } + + def _check_copy(self, label: str, script_dir: Path): + mod = runpy.run_path(str(script_dir / "update-nixpkgs-inputs.py")) + gate_error = mod["HydraGateError"] + resolve = mod["hydra_cached_revision"] + + with self.subTest(copy=label, case="happy path resolves eval + revision"): + with _hydra_server(self.GOOD_PAYLOADS) as base: + rev, eval_id = resolve(base) + self.assertEqual(rev, GATE_TARGET_REV) + self.assertEqual(eval_id, GATE_EVAL_ID) + + with self.subTest(copy=label, case="unreachable hydra is a gate error"): + with self.assertRaises(gate_error): + resolve("http://127.0.0.1:9") + + with self.subTest(copy=label, case="bad latest-finished shapes fail closed"): + for bad in ( + {"buildstatus": 1, "jobsetevals": [GATE_EVAL_ID]}, + {"buildstatus": 0, "jobsetevals": []}, + {"buildstatus": 0}, + ["not", "an", "object"], + ): + payloads = dict(self.GOOD_PAYLOADS) + payloads["/job/nixos/unstable/tested/latest-finished"] = bad + with _hydra_server(payloads) as base: + with self.assertRaises(gate_error): + resolve(base) + + with self.subTest(copy=label, case="bad eval shapes fail closed"): + for bad_eval in ( + {"jobsetevalinputs": {"nixpkgs": {"revision": "not-a-rev"}}}, + {"jobsetevalinputs": {}}, + {}, + ): + payloads = dict(self.GOOD_PAYLOADS) + payloads[f"/eval/{GATE_EVAL_ID}"] = bad_eval + with _hydra_server(payloads) as base: + with self.assertRaises(gate_error): + resolve(base) + + def test_root_copy(self): + self._check_copy("root", COPIES["root"]) + + def test_pkgs_id_copy(self): + self._check_copy("pkgs/id", COPIES["pkgs/id"]) + + +class GateTree: + """One copy of the tool staged with a two-input flake.lock (one + no-ref input, one nixos-unstable input) and a stub `nix` whose + `flake metadata` answers with a canned locked entry for + GATE_TARGET_REV. Every nix invocation is counted.""" + + def __init__(self, src_dir: Path): + self._tmp = tempfile.TemporaryDirectory() + base = Path(self._tmp.name) + self.repo_dir = base / "repo" + scripts = self.repo_dir / "scripts" + scripts.mkdir(parents=True) + shutil.copy2(src_dir / "update-nixpkgs-inputs.py", scripts) + shutil.copy2(src_dir / "update-nixpkgs-inputs.sh", scripts) + self.lock_path = self.repo_dir / "flake.lock" + self.lock_path.write_text(json.dumps(GATE_FLAKE_LOCK, indent=2) + "\n") + self.bin = base / "bin" + self.bin.mkdir() + self.counter = base / "nix-calls" + metadata = json.dumps( + { + "locked": { + "__final": True, + "lastModified": 1793540411, + "narHash": GATE_NAR_HASH, + "owner": "NixOS", + "repo": "nixpkgs", + "rev": GATE_TARGET_REV, + "type": "github", + } + } + ) + _write_executable( + self.bin / "nix", + "#!/bin/sh\n" + f'echo call >> "{self.counter}"\n' + 'if [ "$1" = flake ] && [ "$2" = metadata ]; then\n' + f" printf '%s' '{metadata}'\n" + "fi\n" + "exit 0\n", + ) + _write_executable( + self.bin / "uv", + "#!/bin/sh\n" + '[ "$1" = run ] && shift\n' + '[ "$1" = --script ] && shift\n' + 'exec python3 "$@"\n', + ) + + def cleanup(self): + self._tmp.cleanup() + + def nix_calls(self) -> int: + if not self.counter.exists(): + return 0 + return len(self.counter.read_text().splitlines()) + + def run_py(self, hydra_url: str) -> subprocess.CompletedProcess: + env = dict( + os.environ, + PATH=f"{self.bin}:{os.environ['PATH']}", + UPDATE_NIXPKGS_HYDRA_URL=hydra_url, + ) + return subprocess.run( + [ + sys.executable, + str(self.repo_dir / "scripts" / "update-nixpkgs-inputs.py"), + "nixos-unstable", + ], + env=env, + capture_output=True, + text=True, + timeout=60, + ) + + +class TestGatedPinEndToEnd(unittest.TestCase): + def _check_copy(self, label: str, src_dir: Path): + with self.subTest(copy=label, case="pin rewrites only the gated locked entry"): + tree = GateTree(src_dir) + try: + with _hydra_server() as hydra_url: + r = tree.run_py(hydra_url) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("Hydra gate", r.stdout) + self.assertIn("Failed: 0", r.stdout) + lock = json.loads(tree.lock_path.read_text()) + unstable = lock["nodes"]["nixpkgs-unstable"] + self.assertEqual(unstable["locked"]["rev"], GATE_TARGET_REV) + self.assertEqual(unstable["locked"]["narHash"], GATE_NAR_HASH) + self.assertEqual(unstable["locked"]["lastModified"], 1793540411) + self.assertNotIn("__final", unstable["locked"]) + self.assertEqual( + unstable["original"], + GATE_FLAKE_LOCK["nodes"]["nixpkgs-unstable"]["original"], + ) + self.assertEqual( + lock["nodes"]["nixpkgs"], GATE_FLAKE_LOCK["nodes"]["nixpkgs"] + ) + # Exactly one nix call: the metadata fetch. The gated + # input must never go through `nix flake update` (HEAD). + self.assertEqual(tree.nix_calls(), 1) + + with self.subTest(case="second run is a byte-identical no-op"): + before = tree.lock_path.read_bytes() + with _hydra_server() as hydra_url: + r2 = tree.run_py(hydra_url) + self.assertEqual(r2.returncode, 0, r2.stdout + r2.stderr) + self.assertIn("already up-to-date", r2.stdout) + self.assertEqual(tree.lock_path.read_bytes(), before) + finally: + tree.cleanup() + + with self.subTest( + copy=label, case="hydra failure exits non-zero, lock untouched" + ): + tree = GateTree(src_dir) + try: + before = tree.lock_path.read_bytes() + # Port 9 (discard) is closed: the lookup fails fast. + r = tree.run_py("http://127.0.0.1:9") + self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("Hydra cache gate failed", r.stderr) + self.assertEqual(tree.lock_path.read_bytes(), before) + self.assertEqual(tree.nix_calls(), 0) + finally: + tree.cleanup() + + def test_root_copy(self): + self._check_copy("root", COPIES["root"]) + + def test_pkgs_id_copy(self): + self._check_copy("pkgs/id", COPIES["pkgs/id"]) + self._check_copy("pkgs/id", COPIES["pkgs/id"]) + + +class TestHttpsContext(unittest.TestCase): + def test_verification_stays_on_in_both_copies(self): + import ssl + + for label, script_dir in COPIES.items(): + with self.subTest(copy=label): + mod = runpy.run_path(str(script_dir / "update-nixpkgs-inputs.py")) + ctx = mod["https_context"]() + self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) + self.assertTrue(ctx.check_hostname) diff --git a/scripts/update-nixpkgs-inputs.py b/scripts/update-nixpkgs-inputs.py index c9d0ec2edd..56788c98e1 100755 --- a/scripts/update-nixpkgs-inputs.py +++ b/scripts/update-nixpkgs-inputs.py @@ -19,13 +19,157 @@ ./scripts/update-nixpkgs-inputs.py master # master (or no ref) inputs ./scripts/update-nixpkgs-inputs.py nixos-unstable # nixos-unstable inputs ./scripts/update-nixpkgs-inputs.py master nixos-unstable # both categories, combined summary + +Cache gate (#4553): inputs whose original.ref is "nixos-unstable" are NOT +updated to branch HEAD — HEAD runs days ahead of what Hydra has built and +cache.nixos.org serves, so a HEAD pin can turn the next system build into +a multi-day source build (see #2715). Gated inputs are pinned instead to +the newest revision Hydra has fully built for the channel: the `tested` +job of jobset nixos:unstable, resolved via + GET /job/nixos/unstable/tested/latest-finished -> jobsetevals[0] + GET /eval/ -> jobsetevalinputs.nixpkgs.revision +The pin rewrites only the input's `locked` entry (rev + narHash + +lastModified from a real `nix flake metadata` fetch of that revision); +`original` — including ref "nixos-unstable" — is left untouched so input +discovery keeps matching. The gate fails closed: if the Hydra lookups +fail or return an unexpected shape, the script exits non-zero before +touching flake.lock. The Hydra base URL can be overridden with the +UPDATE_NIXPKGS_HYDRA_URL environment variable (used by the tests). """ import json +import os +import re +import ssl import subprocess import sys +import urllib.request from pathlib import Path +GATED_REF = "nixos-unstable" +HYDRA_BASE_URL_ENV = "UPDATE_NIXPKGS_HYDRA_URL" +DEFAULT_HYDRA_BASE_URL = "https://hydra.nixos.org" +HYDRA_LATEST_FINISHED_PATH = "/job/nixos/unstable/tested/latest-finished" +REV_RE = re.compile(r"^[0-9a-f]{40}$") + + +class HydraGateError(Exception): + """The Hydra cache gate could not produce a trustworthy revision.""" + + +def https_context(): + """SSL context for Hydra requests, with verification ON. + + The .py shebang runs under `uv run --script`, whose standalone + Python builds can fail to locate a CA bundle at all (0 certs + loaded, every HTTPS request CERTIFICATE_VERIFY_FAILED) even on a + healthy system. When the default context comes up empty, point it + at the usual system bundle locations instead of failing.""" + ctx = ssl.create_default_context() + if ctx.get_ca_certs(): + return ctx + for cafile in ( + os.environ.get("SSL_CERT_FILE"), + "/etc/ssl/certs/ca-certificates.crt", # Debian / NixOS + "/etc/pki/tls/certs/ca-bundle.crt", # RHEL family + "/etc/ssl/cert.pem", # macOS / Alpine + ): + if cafile and os.path.exists(cafile): + return ssl.create_default_context(cafile=cafile) + return ctx + + +def fetch_hydra_json(url): + """GET a Hydra JSON endpoint (follows redirects; Hydra content- + negotiates on the Accept header and serves HTML without it).""" + req = urllib.request.Request(url, headers={"Accept": "application/json"}) + with urllib.request.urlopen(req, timeout=60, context=https_context()) as resp: + return json.load(resp) + + +def parse_latest_finished_eval_id(data): + """Extract the jobset eval id from a latest-finished build payload.""" + if not isinstance(data, dict): + raise HydraGateError("latest-finished payload is not a JSON object") + status = data.get("buildstatus") + if status is not None and status != 0: + raise HydraGateError( + f"latest finished 'tested' build did not succeed (buildstatus={status})" + ) + evals = data.get("jobsetevals") + if not isinstance(evals, list) or not evals: + raise HydraGateError("latest-finished payload has no jobsetevals") + eval_id = evals[0] + if isinstance(eval_id, str) and eval_id.isdigit(): + eval_id = int(eval_id) + if not isinstance(eval_id, int) or isinstance(eval_id, bool): + raise HydraGateError(f"unexpected jobsetevals[0]: {eval_id!r}") + return eval_id + + +def parse_eval_revision(data): + """Extract the nixpkgs revision from a Hydra eval payload.""" + if not isinstance(data, dict): + raise HydraGateError("eval payload is not a JSON object") + inputs = data.get("jobsetevalinputs") + if not isinstance(inputs, dict): + raise HydraGateError("eval payload has no jobsetevalinputs") + nixpkgs = inputs.get("nixpkgs") + if not isinstance(nixpkgs, dict): + raise HydraGateError("eval payload has no nixpkgs jobset eval input") + rev = nixpkgs.get("revision") + if not isinstance(rev, str) or not REV_RE.match(rev): + raise HydraGateError(f"unexpected nixpkgs revision: {rev!r}") + return rev + + +def hydra_cached_revision(base_url=None): + """Newest nixos-unstable revision Hydra has fully built. + + Returns (revision, eval_id). Raises HydraGateError on any lookup + failure or unexpected response shape — callers must fail closed. + """ + base = ( + base_url or os.environ.get(HYDRA_BASE_URL_ENV) or DEFAULT_HYDRA_BASE_URL + ).rstrip("/") + try: + latest = fetch_hydra_json(base + HYDRA_LATEST_FINISHED_PATH) + except Exception as e: + raise HydraGateError( + f"cannot fetch {base + HYDRA_LATEST_FINISHED_PATH}: {e}" + ) from e + eval_id = parse_latest_finished_eval_id(latest) + try: + eval_data = fetch_hydra_json(f"{base}/eval/{eval_id}") + except Exception as e: + raise HydraGateError(f"cannot fetch {base}/eval/{eval_id}: {e}") from e + return parse_eval_revision(eval_data), eval_id + + +def fetch_locked_for_rev(rev): + """Fetch github:NixOS/nixpkgs@ with nix and return the locked + attrs (rev, narHash, lastModified, ...) a flake.lock entry needs. + Returns None if the fetch fails or the result does not check out.""" + result = subprocess.run( + ["nix", "flake", "metadata", f"github:NixOS/nixpkgs/{rev}", "--json"], + capture_output=True, + text=True, + ) + if result.returncode != 0: + return None + try: + locked = json.loads(result.stdout)["locked"] + except (ValueError, KeyError, TypeError): + return None + if not isinstance(locked, dict): + return None + # `nix flake metadata` annotates its result with __final; flake.lock + # locked entries do not carry it. + locked = {k: v for k, v in locked.items() if k != "__final"} + if locked.get("rev") != rev or not locked.get("narHash"): + return None + return locked + def load_flake_lock(repo_dir): """Load and parse flake.lock.""" @@ -67,6 +211,31 @@ def get_input_info(lock_data, input_name): return (rev, url, ref_display) +def get_input_node(lock_data, input_name): + """Return the lock node for a root input name, or None.""" + root_inputs = lock_data.get("nodes", {}).get("root", {}).get("inputs", {}) + node_name = root_inputs.get(input_name) + if not isinstance(node_name, str): + return None + return lock_data.get("nodes", {}).get(node_name) + + +def get_input_ref(lock_data, input_name): + """Return the input's original.ref (None when unset / not found).""" + node = get_input_node(lock_data, input_name) + if not node: + return None + return node.get("original", {}).get("ref") + + +def get_locked_rev(lock_data, input_name): + """Return the input's full locked revision (None when not locked).""" + node = get_input_node(lock_data, input_name) + if not node: + return None + return node.get("locked", {}).get("rev") + + def discover_inputs(lock_data, ref): """Discover NixOS/nixpkgs inputs by parsing flake.lock directly. @@ -127,6 +296,22 @@ def update_input(input_name, repo_dir): return result.returncode == 0 +def pin_input(input_name, repo_dir, locked): + """Pin an input to a pre-fetched locked entry, rewriting only the + node's `locked` in flake.lock (`original` stays untouched, so the + input's ref — and therefore discovery — is preserved). The dump + format matches nix's own flake.lock formatting byte for byte. + Returns True on success.""" + lock_data = load_flake_lock(repo_dir) + node = get_input_node(lock_data, input_name) + if node is None: + return False + node["locked"] = dict(locked) + with open(repo_dir / "flake.lock", "w") as f: + f.write(json.dumps(lock_data, indent=2) + "\n") + return get_locked_rev(load_flake_lock(repo_dir), input_name) == locked["rev"] + + def format_result_lines(results): """Format result detail lines grouped by source URL.""" url_order = [] @@ -233,25 +418,62 @@ def main(): refs = sys.argv[1:] if len(sys.argv) > 1 else [None] + # Planning pass: resolve, against the pristine lock, which inputs each + # requested ref will process (same discovery + cross-ref dedupe as the + # execution pass below). The cache gate must be resolved — and must + # fail closed — before any input is touched, so gated inputs are + # identified up front. + plan = [] seen_inputs = set() + gated_inputs = set() + initial_lock = load_flake_lock(repo_dir) + for ref in refs: + inputs = discover_inputs(initial_lock, ref) + new_inputs = [i for i in inputs if i not in seen_inputs] + seen_inputs.update(new_inputs) + plan.append((ref, inputs, new_inputs)) + for name in new_inputs: + if get_input_ref(initial_lock, name) == GATED_REF: + gated_inputs.add(name) + + gate_rev = None + gate_locked = None + if gated_inputs: + try: + gate_rev, gate_eval = hydra_cached_revision() + except HydraGateError as e: + print( + f"ERROR: Hydra cache gate failed: {e}\n" + f"Refusing to update {GATED_REF} inputs to uncached " + "revisions; flake.lock left untouched.", + file=sys.stderr, + ) + sys.exit(1) + gate_locked = fetch_locked_for_rev(gate_rev) + if gate_locked is None: + print( + f"ERROR: could not fetch github:NixOS/nixpkgs@{gate_rev} " + "with nix flake metadata; flake.lock left untouched.", + file=sys.stderr, + ) + sys.exit(1) + print( + f"Hydra gate: {GATED_REF} inputs pin to {gate_rev[:12]} " + f"(newest revision fully built by Hydra jobset nixos:unstable, " + f"eval {gate_eval})" + ) + all_ref_data = [] - for ref in refs: + for ref, inputs, new_inputs in plan: label = ref if ref else "all" ref_data = {"label": label, "results": [], "not_found": False} - lock_data = load_flake_lock(repo_dir) - inputs = discover_inputs(lock_data, ref) - if not inputs: ref_data["not_found"] = True all_ref_data.append(ref_data) continue - # Filter out already-seen inputs - new_inputs = [i for i in inputs if i not in seen_inputs] - seen_inputs.update(new_inputs) - if not new_inputs: all_ref_data.append(ref_data) continue @@ -264,6 +486,48 @@ def main(): lock_data = load_flake_lock(repo_dir) old_rev, source_url, input_ref = get_input_info(lock_data, input_name) + if input_name in gated_inputs: + if get_locked_rev(lock_data, input_name) == gate_rev: + ref_data["results"].append( + { + "name": input_name, + "status": "skipped", + "old_rev": old_rev, + "new_rev": None, + "url": source_url, + "ref": input_ref, + } + ) + elif pin_input(input_name, repo_dir, gate_locked): + lock_data = load_flake_lock(repo_dir) + new_rev, _, _ = get_input_info(lock_data, input_name) + ref_data["results"].append( + { + "name": input_name, + "status": "updated", + "old_rev": old_rev, + "new_rev": new_rev, + "url": source_url, + "ref": input_ref, + } + ) + else: + ref_data["results"].append( + { + "name": input_name, + "status": "failed", + "old_rev": old_rev, + "new_rev": None, + "url": source_url, + "ref": input_ref, + } + ) + print( + f"WARNING: failed to pin {input_name} to {gate_rev}", + file=sys.stderr, + ) + continue + if update_input(input_name, repo_dir): lock_data = load_flake_lock(repo_dir) new_rev, _, _ = get_input_info(lock_data, input_name)