#!/usr/bin/env python3 """Shared implementation for the private fleet Nix cache release tools. The release envelope is: {"payload": "", "signature": ""} Only the Python standard library is imported here. Runtime commands (nix, openssl, aws, git, ssh) are provided by pkgs/nix-cache-tools.nix; when the scripts are invoked directly from a checkout the caller supplies them. Security notes: * Secret key files are only ever passed to subprocesses by path. * We never print environment variables or subprocess environments. * Subprocess diagnostics are redacted for known credential environment values before they can reach a log. """ from __future__ import annotations import base64 import binascii import collections import errno import fcntl import hashlib import json import os import re import socket import stat import subprocess import sys import tempfile import threading import time import urllib.error import urllib.parse import urllib.request DEFAULT_BUCKET = "nixos-cache" DEFAULT_ENDPOINT = "fsn1.your-objectstorage.com" DEFAULT_REGION = "fsn1" # Hosts CI builds and publishes releases for. Clockwork (aarch64) is left out: # building it on x86_64 meant hours of binfmt emulation, so it builds locally. HOST_SYSTEMS = { "deck": "x86_64-linux", "sayaka": "x86_64-linux", "madoka": "x86_64-linux", "megatron": "x86_64-linux", "homura": "x86_64-linux", "lightbulb": "x86_64-linux", "reef": "x86_64-linux", } HOST_ORDER = [h for h in ("deck", "sayaka", "madoka", "megatron", "homura", "lightbulb", "reef") if h in HOST_SYSTEMS] MAX_ENVELOPE_BYTES = 2 * 1024 * 1024 MAX_PAYLOAD_BYTES = 1024 * 1024 MAX_SIGNATURE_BYTES = 64 STORE_PATH_RE = re.compile( r"^/nix/store/[0-9a-df-np-sv-z]{32}-[A-Za-z0-9+._?=-]{1,211}$" ) HOST_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$") SYSTEM_RE = re.compile(r"^[a-z0-9_]+-[a-z0-9_]+$") REVISION_RE = re.compile(r"^[0-9a-f]{40}$") RELEASE_KEYS = frozenset( {"version", "host", "system", "revision", "toplevel", "publishedAt"} ) ENVELOPE_KEYS = frozenset({"payload", "signature"}) REDACT_ENV = ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_SECURITY_TOKEN") class NixCacheError(Exception): """An operational failure that is safe to show to an operator.""" class VerificationError(NixCacheError): """Untrusted or malformed release metadata.""" class CommandError(NixCacheError): """A required subprocess failed.""" # --------------------------------------------------------------------------- # Small utilities def log(message: str) -> None: print(message, file=sys.stderr, flush=True) def redact(text: str) -> str: for name in REDACT_ENV: value = os.environ.get(name) if value: text = text.replace(value, "") # AWS CLI and OpenSSL should never print these, but a generic heuristic # keeps accidental one-line echoes from reaching a CI log. text = re.sub(r"(?i)(aws_secret_access_key\s*=\s*)\S+", r"\1", text) text = re.sub(r"(?i)(aws_access_key_id\s*=\s*)\S+", r"\1", text) return text def _safe_detail(data: bytes) -> str: detail = redact(data.decode("utf-8", "replace")).strip() if len(detail) > 4000: detail = detail[-4000:] return detail def run(argv, *, input_bytes=None, env=None, check=True, timeout=None, cwd=None, description=None, stream_stderr=False, stall_check=None): """Run a subprocess without ever exposing credential environment values. With stream_stderr, stderr is copied line by line to our stderr as it is produced, so a CI job log shows progress live; only the last lines are kept for error messages. stdout is still returned in full. stall_check (only with stream_stderr) is called every STALL_POLL_SECONDS with the seconds since the last stderr line; when it returns True the process is killed and STALL_MARKER is appended to the returned stderr. """ merged_env = os.environ.copy() if env: merged_env.update(env) if stream_stderr: if input_bytes is not None: raise ValueError("stream_stderr does not support input_bytes") return _run_streaming(argv, env=merged_env, cwd=cwd, timeout=timeout, check=check, description=description, stall_check=stall_check) if stall_check is not None: raise ValueError("stall_check requires stream_stderr") run_kwargs = {} if input_bytes is None: run_kwargs["stdin"] = subprocess.DEVNULL else: run_kwargs["input"] = input_bytes try: proc = subprocess.run( argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=merged_env, cwd=cwd, timeout=timeout, check=False, **run_kwargs, ) except FileNotFoundError as exc: raise CommandError( f"required command not found: {argv[0]}" ) from exc except subprocess.TimeoutExpired as exc: raise CommandError( f"command timed out: {description or argv[0]}" ) from exc if check and proc.returncode != 0: detail = _safe_detail(proc.stderr or proc.stdout) suffix = f": {detail}" if detail else "" raise CommandError( f"command failed ({description or argv[0]}, exit " f"{proc.returncode}){suffix}" ) return proc STREAM_TAIL_LINES = 200 STALL_POLL_SECONDS = 60 STALL_MARKER = "nix-cache: command stalled; killed it" def _run_streaming(argv, *, env, cwd, timeout, check, description, stall_check=None): description = description or argv[0] tail = collections.deque(maxlen=STREAM_TAIL_LINES) # stdout is spooled to a file so it can be read back after stderr has been # drained line by line, without a second reader thread. with tempfile.TemporaryFile(prefix="nix-cache-stdout-") as stdout: try: proc = subprocess.Popen( argv, stdin=subprocess.DEVNULL, stdout=stdout, stderr=subprocess.PIPE, env=env, cwd=cwd, ) except FileNotFoundError as exc: raise CommandError( f"required command not found: {argv[0]}" ) from exc timed_out = threading.Event() stalled = threading.Event() finished = threading.Event() last_line = [time.monotonic()] def expire(): timed_out.set() proc.kill() def watch(): while not finished.wait(STALL_POLL_SECONDS): if stall_check(time.monotonic() - last_line[0]): stalled.set() proc.kill() return timer = threading.Timer(timeout, expire) if timeout is not None else None if timer is not None: timer.start() watcher = threading.Thread(target=watch, daemon=True) if stall_check else None if watcher is not None: watcher.start() try: for raw in proc.stderr: last_line[0] = time.monotonic() line = redact(raw.decode("utf-8", "replace").rstrip("\r\n")) sys.stderr.write(line + "\n") sys.stderr.flush() tail.append(line) returncode = proc.wait() except BaseException: proc.kill() proc.wait() raise finally: finished.set() if timer is not None: timer.cancel() if watcher is not None: watcher.join() proc.stderr.close() if timed_out.is_set(): raise CommandError(f"command timed out: {description}") if stalled.is_set(): tail.append(STALL_MARKER) stdout.seek(0) out = stdout.read() stderr = "\n".join(tail).encode("utf-8") if check and returncode != 0: detail = _safe_detail(stderr) suffix = f": {detail}" if detail else "" raise CommandError( f"command failed ({description}, exit {returncode}){suffix}" ) return subprocess.CompletedProcess(argv, returncode, out, stderr) def require_regular_file(path: str, what: str) -> None: try: info = os.stat(path) except OSError as exc: raise NixCacheError(f"{what} is not readable: {path}") from exc if not stat.S_ISREG(info.st_mode): raise NixCacheError(f"{what} is not a regular file: {path}") if info.st_size == 0: raise NixCacheError(f"{what} is empty: {path}") def require_private_file(path: str, what: str) -> None: require_regular_file(path, what) mode = stat.S_IMODE(os.stat(path).st_mode) if mode & 0o077: raise NixCacheError( f"{what} must not be group/world accessible (required mode 0600): {path}" ) def atomic_write(path: str, data: bytes, mode: int = 0o640) -> None: directory = os.path.dirname(os.path.abspath(path)) or "." os.makedirs(directory, mode=0o750, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=".nix-cache-", dir=directory) try: os.fchmod(fd, mode) with os.fdopen(fd, "wb") as handle: handle.write(data) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) dir_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(dir_fd) finally: os.close(dir_fd) except BaseException: try: os.unlink(temporary) except OSError: pass raise class HostLock: """A per-host exclusive lock, held for the whole activation attempt.""" def __init__(self, state_dir: str, host: str): self.state_dir = state_dir self.host = host self.fd = None self.path = os.path.join(state_dir, f"{host}.lock") def __enter__(self): os.makedirs(self.state_dir, mode=0o750, exist_ok=True) try: os.chmod(self.state_dir, 0o750) except OSError: pass self.fd = os.open( self.path, os.O_CREAT | os.O_RDWR | os.O_CLOEXEC, 0o600 ) try: fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as exc: os.close(self.fd) self.fd = None if exc.errno in (errno.EACCES, errno.EAGAIN): raise NixCacheError( f"another activation for {self.host} is already running" ) from exc raise return self def __exit__(self, exc_type, exc, tb): if self.fd is not None: try: fcntl.flock(self.fd, fcntl.LOCK_UN) finally: os.close(self.fd) self.fd = None return False # --------------------------------------------------------------------------- # Strict JSON and envelope handling def _reject_constant(value): raise VerificationError(f"invalid JSON constant: {value}") def _unique_pairs(pairs): result = {} for key, value in pairs: if key in result: raise VerificationError(f"duplicate JSON key: {key!r}") result[key] = value return result def strict_json(data: bytes, what: str): if len(data) > MAX_ENVELOPE_BYTES: raise VerificationError(f"{what} is too large") try: text = data.decode("utf-8") except UnicodeDecodeError as exc: raise VerificationError(f"{what} is not valid UTF-8") from exc try: return json.loads( text, object_pairs_hook=_unique_pairs, parse_constant=_reject_constant, ) except VerificationError: raise except (ValueError, TypeError) as exc: raise VerificationError(f"{what} is not valid JSON: {exc}") from exc def canonical_json(value) -> bytes: return json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True ).encode("utf-8") def _is_int(value) -> bool: return isinstance(value, int) and not isinstance(value, bool) def _require_exact_keys(value, expected, what: str) -> None: if type(value) is not dict: raise VerificationError(f"{what} must be a JSON object") actual = set(value) if actual != set(expected): missing = sorted(set(expected) - actual) extra = sorted(actual - set(expected)) raise VerificationError( f"{what} has unexpected fields (missing={missing}, extra={extra})" ) def decode_base64(value, what: str) -> bytes: if type(value) is not str or not value: raise VerificationError(f"{what} must be a non-empty base64 string") try: decoded = base64.b64decode(value, validate=True) except (binascii.Error, ValueError) as exc: raise VerificationError(f"{what} is not valid base64") from exc if not decoded: raise VerificationError(f"{what} must not be empty") if base64.b64encode(decoded).decode("ascii") != value: raise VerificationError(f"{what} is not canonical base64") return decoded def encode_base64(data: bytes) -> str: return base64.b64encode(data).decode("ascii") def parse_envelope(raw: bytes): """Return (payload bytes, signature bytes) without trusting either.""" envelope = strict_json(raw, "release envelope") _require_exact_keys(envelope, ENVELOPE_KEYS, "release envelope") payload = decode_base64(envelope["payload"], "envelope payload") signature = decode_base64(envelope["signature"], "envelope signature") if len(payload) > MAX_PAYLOAD_BYTES: raise VerificationError("envelope payload is too large") if len(signature) != MAX_SIGNATURE_BYTES: raise VerificationError( f"Ed25519 signature must be {MAX_SIGNATURE_BYTES} bytes" ) return payload, signature def _openssl_key_is_ed25519(path: str, public: bool) -> None: argv = ["openssl", "pkey"] if public: argv.append("-pubin") argv += ["-in", path, "-text", "-noout"] proc = run(argv, check=False, timeout=30, description="openssl key inspection") text = (proc.stdout + proc.stderr).decode("utf-8", "replace").upper() if proc.returncode != 0 or "ED25519" not in text: raise VerificationError( "release key must be an Ed25519 " + ("public" if public else "private") + " key" ) def ed25519_sign(payload: bytes, private_key_file: str) -> bytes: require_regular_file(private_key_file, "release signing key") _openssl_key_is_ed25519(private_key_file, public=False) with tempfile.TemporaryDirectory(prefix="nix-cache-sign-") as tmp: payload_path = os.path.join(tmp, "payload") signature_path = os.path.join(tmp, "signature") with open(payload_path, "wb") as handle: handle.write(payload) proc = run( [ "openssl", "pkeyutl", "-sign", "-inkey", private_key_file, "-rawin", "-in", payload_path, "-out", signature_path, ], check=False, timeout=60, description="openssl Ed25519 signing", ) if proc.returncode != 0: detail = _safe_detail(proc.stderr or proc.stdout) raise CommandError( "Ed25519 release signing failed" + (f": {detail}" if detail else "") ) with open(signature_path, "rb") as handle: signature = handle.read() if len(signature) != MAX_SIGNATURE_BYTES: raise VerificationError("Ed25519 signing produced an invalid signature length") return signature def ed25519_verify(payload: bytes, signature: bytes, public_key_file: str) -> None: require_regular_file(public_key_file, "release verification key") _openssl_key_is_ed25519(public_key_file, public=True) if len(signature) != MAX_SIGNATURE_BYTES: raise VerificationError("invalid Ed25519 signature length") with tempfile.TemporaryDirectory(prefix="nix-cache-verify-") as tmp: payload_path = os.path.join(tmp, "payload") signature_path = os.path.join(tmp, "signature") with open(payload_path, "wb") as handle: handle.write(payload) with open(signature_path, "wb") as handle: handle.write(signature) proc = run( [ "openssl", "pkeyutl", "-verify", "-pubin", "-inkey", public_key_file, "-rawin", "-in", payload_path, "-sigfile", signature_path, ], check=False, timeout=60, description="openssl Ed25519 verification", ) if proc.returncode != 0: raise VerificationError("release signature verification failed") def verify_envelope(raw: bytes, public_key_file: str) -> bytes: payload, signature = parse_envelope(raw) ed25519_verify(payload, signature, public_key_file) return payload def make_envelope(payload: bytes, private_key_file: str) -> bytes: if len(payload) > MAX_PAYLOAD_BYTES: raise NixCacheError("envelope payload is too large") signature = ed25519_sign(payload, private_key_file) return canonical_json( {"payload": encode_base64(payload), "signature": encode_base64(signature)} ) # --------------------------------------------------------------------------- # Release payloads def validate_host_system(host: str, system: str) -> None: if not HOST_RE.fullmatch(host): raise VerificationError(f"invalid host name: {host!r}") if not SYSTEM_RE.fullmatch(system): raise VerificationError(f"invalid system: {system!r}") expected = HOST_SYSTEMS.get(host) if expected is None: raise VerificationError(f"unknown fleet host: {host!r}") if expected != system: raise VerificationError( f"host {host!r} is configured for {expected}, not {system!r}" ) def validate_store_path(path, what: str = "store path") -> str: if type(path) is not str: raise VerificationError(f"{what} must be a string") if not STORE_PATH_RE.fullmatch(path): raise VerificationError(f"{what} is not a valid /nix/store path") return path def validate_toplevel(path, host: str) -> str: validate_store_path(path, "toplevel") name = path.split("-", 1)[1] prefix = f"nixos-system-{host}-" if not name.startswith(prefix) or len(name) == len(prefix): raise VerificationError( f"toplevel is not the nixos-system toplevel for {host}" ) return path def validate_release_payload(payload: bytes, expected_host: str, expected_system: str): validate_host_system(expected_host, expected_system) value = strict_json(payload, "release payload") _require_exact_keys(value, RELEASE_KEYS, "release payload") if not _is_int(value["version"]) or value["version"] != 1: raise VerificationError("unsupported release payload version") if value["host"] != expected_host: raise VerificationError( f"release is for host {value['host']!r}, expected {expected_host!r}" ) if value["system"] != expected_system: raise VerificationError( f"release is for system {value['system']!r}, expected {expected_system!r}" ) validate_host_system(value["host"], value["system"]) if type(value["revision"]) is not str or not REVISION_RE.fullmatch(value["revision"]): raise VerificationError("release revision must be a 40-character lowercase hex commit") validate_toplevel(value["toplevel"], expected_host) if not _is_int(value["publishedAt"]) or value["publishedAt"] <= 0: raise VerificationError("release publishedAt must be a positive integer epoch") return value def make_release_payload(host: str, system: str, revision: str, toplevel: str, published_at: int) -> bytes: validate_host_system(host, system) if not REVISION_RE.fullmatch(revision): raise NixCacheError(f"invalid git revision: {revision!r}") validate_toplevel(toplevel, host) return canonical_json( { "version": 1, "host": host, "system": system, "revision": revision, "toplevel": toplevel, "publishedAt": int(published_at), } ) # --------------------------------------------------------------------------- # S3 object access def normalize_endpoint(endpoint: str) -> str: if "://" not in endpoint: endpoint = "https://" + endpoint parsed = urllib.parse.urlsplit(endpoint) if parsed.scheme not in ("http", "https") or not parsed.netloc: raise NixCacheError(f"invalid S3 endpoint: {endpoint!r}") if parsed.username or parsed.password: raise NixCacheError("S3 endpoint must not contain credentials") if parsed.path not in ("", "/"): raise NixCacheError("S3 endpoint must not contain a path") return f"{parsed.scheme}://{parsed.netloc}" def endpoint_host(endpoint: str) -> str: return urllib.parse.urlsplit(normalize_endpoint(endpoint)).netloc def make_cache_uri(bucket: str, endpoint: str, region: str, secret_key_file: str | None = None) -> str: host = endpoint_host(endpoint) uri = ( f"s3://{bucket}?endpoint={urllib.parse.quote(host, safe='')}" f"®ion={urllib.parse.quote(region, safe='')}&compression=zstd" ) if secret_key_file: uri += "&secret-key=" + urllib.parse.quote( os.path.abspath(secret_key_file), safe="/" ) return uri def add_destination_signing(uri: str, secret_key_file: str) -> str: """Add Nix's destination `secret-key` parameter to an existing cache URI. Only the key path is placed in the URI; the key value is never passed on the command line and never printed. """ parsed = urllib.parse.urlsplit(uri) if parsed.scheme != "s3": raise NixCacheError("destination signing requires an s3:// cache URI") query = [ (name, value) for name, value in urllib.parse.parse_qsl(parsed.query, keep_blank_values=True) if name != "secret-key" ] query.append(("secret-key", os.path.abspath(secret_key_file))) return urllib.parse.urlunsplit( (parsed.scheme, parsed.netloc, parsed.path, urllib.parse.urlencode(query, safe="/"), parsed.fragment) ) class S3: def __init__(self, bucket: str, endpoint: str, region: str): if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket): raise NixCacheError(f"invalid S3 bucket name: {bucket!r}") if not re.fullmatch(r"[A-Za-z0-9._-]+", region): raise NixCacheError(f"invalid S3 region: {region!r}") self.bucket = bucket self.endpoint = normalize_endpoint(endpoint) self.region = region def _aws(self, *args): return run( [ "aws", "--endpoint-url", self.endpoint, "--region", self.region, *args, ], timeout=300, description="aws s3", ) def put(self, key: str, data: bytes, content_type="application/json") -> None: with tempfile.NamedTemporaryFile(prefix="nix-cache-s3-", delete=False) as handle: temporary = handle.name handle.write(data) handle.flush() try: self._aws( "s3api", "put-object", "--bucket", self.bucket, "--key", key, "--body", temporary, "--content-type", content_type, ) finally: try: os.unlink(temporary) except OSError: pass def get_optional(self, key: str): with tempfile.NamedTemporaryFile(prefix="nix-cache-s3-", delete=False) as handle: temporary = handle.name try: proc = run( [ "aws", "--endpoint-url", self.endpoint, "--region", self.region, "s3api", "get-object", "--bucket", self.bucket, "--key", key, temporary, ], check=False, timeout=300, description="aws s3", ) if proc.returncode != 0: detail = (proc.stderr or b"") + (proc.stdout or b"") lowered = detail.lower() if any( marker in lowered for marker in (b"nosuchkey", b"not found", b"404") ): return None raise CommandError( "S3 get-object failed for " f"{key}: {_safe_detail(detail)}" ) size = os.path.getsize(temporary) if size > MAX_ENVELOPE_BYTES: raise NixCacheError(f"S3 object {key} is too large") with open(temporary, "rb") as handle: return handle.read() finally: try: os.unlink(temporary) except OSError: pass # --------------------------------------------------------------------------- # Nix and git commands def nix_base(): return ["nix", "--extra-experimental-features", "nix-command flakes"] def nix_copy_to(cache_uri: str, paths) -> None: if not paths: raise NixCacheError("refusing to upload an empty path list") run(nix_copy_argv(cache_uri, paths), timeout=None, description="nix copy --to private cache", ) # Uploads go to Hetzner (fsn1), ~100 ms from the fleet. Over HTTP/2 curl # multiplexes every concurrent NAR upload onto ONE TCP connection, which a # single long-RTT stream caps at a few MB/s regardless of the uplink, and # Hetzner's HTTP/2 front end also resets some of those streams (HTTP 400 # "Stream error in the HTTP/2 framing layer"). HTTP/1.1 gives each concurrent # upload its own connection. COPY_OPTIONS = ["--option", "http2", "false", "--option", "http-connections", "64"] def nix_copy_argv(cache_uri: str, paths) -> list[str]: return nix_base() + COPY_OPTIONS + ["copy", "--to", cache_uri, *paths] def nix_store_valid(path: str) -> bool: proc = run( ["nix-store", "--check-validity", path], check=False, timeout=120, description="nix-store --check-validity", ) return proc.returncode == 0 def nix_realise(path: str) -> None: # Activation must be substitution-only. nix-store --realise would # otherwise be allowed to realise a known deriver by building it locally # or via configured remote builders. Disable both and keep normal # public+private cache substitution; missing artifacts fail clearly. run( [ "nix-store", "--option", "max-jobs", "0", "--option", "builders", "", "--option", "substitute", "true", "--realise", path, ], timeout=None, description="nix-store --realise (substitution only)", ) if not nix_store_valid(path): raise NixCacheError(f"store path was not realised correctly: {path}") def git(repo: str, *args, check=True, timeout=120, input_bytes=None): return run( ["git", "-C", repo, *args], check=check, timeout=timeout, input_bytes=input_bytes, env={"GIT_TERMINAL_PROMPT": "0"}, description=f"git {args[0] if args else ''}".strip(), ) class SourceInfo: def __init__(self, repo, revision, flake_url, lock_bytes, branch, staged): self.repo = repo self.revision = revision self.flake_url = flake_url self.lock_bytes = lock_bytes self.branch = branch self.staged = staged @property def lock_sha256(self) -> str: return hashlib.sha256(self.lock_bytes).hexdigest() def _credential_like(name: str) -> bool: base = os.path.basename(name) return base == "s3-nix-spindle-do-not-read.env" or base.endswith(".env") def _refuse_credential_like(names, what: str) -> None: for name in names: if _credential_like(name): raise NixCacheError(f"refusing to build credential-like {what}: {name}") def resolve_source(path: str, branch_hint=None, allow_staged=False) -> SourceInfo: repo = os.path.realpath(os.path.abspath(path)) if not os.path.isdir(repo): raise NixCacheError(f"source is not a directory: {path}") top = git(repo, "rev-parse", "--show-toplevel") top = top.stdout.decode().strip() if os.path.realpath(top) != repo: raise NixCacheError( "--source must be the root of the git repository used for the fleet" ) head_revision = git(repo, "rev-parse", "HEAD").stdout.decode().strip() if not REVISION_RE.fullmatch(head_revision): raise NixCacheError("git HEAD is not a full 40-character commit") staged_check = git(repo, "diff", "--cached", "--quiet", check=False) if staged_check.returncode not in (0, 1): raise NixCacheError("could not inspect the git index") has_staged = staged_check.returncode == 1 if has_staged and not allow_staged: raise NixCacheError( "the git index has staged changes that are absent from HEAD; commit " "them, or pass --allow-staged-source with --allow-unpushed-head for " "a local smoke build" ) if has_staged: # Build exactly the staged tracked tree as an unreferenced commit. This # never uses path: and never includes untracked files, so an ignored # credential file outside the index cannot enter the store. Refuse # credential-looking filenames in the index as a second guard. changed = git(repo, "diff", "--cached", "--name-only", "-z", check=False).stdout.decode("utf-8", "replace") _refuse_credential_like(changed.split("\0"), "staged file") tree = git(repo, "write-tree").stdout.decode().strip() if not re.fullmatch(r"[0-9a-f]{40}(?:[0-9a-f]{24})?", tree): raise NixCacheError("git write-tree returned an invalid tree id") head_timestamp = git( repo, "show", "-s", "--format=%ct", head_revision ).stdout.decode().strip() if not head_timestamp.isdigit(): raise NixCacheError("could not read the HEAD commit timestamp") commit_date = f"{head_timestamp} +0000" commit = run( ["git", "-C", repo, "commit-tree", tree, "-p", head_revision, "-m", "nix-cache staged source"], env={ "GIT_AUTHOR_NAME": "nix-cache", "GIT_AUTHOR_EMAIL": "nix-cache@localhost", "GIT_COMMITTER_NAME": "nix-cache", "GIT_COMMITTER_EMAIL": "nix-cache@localhost", "GIT_AUTHOR_DATE": commit_date, "GIT_COMMITTER_DATE": commit_date, }, timeout=120, description="git commit-tree staged source", ).stdout.decode().strip() if not REVISION_RE.fullmatch(commit): raise NixCacheError("git commit-tree returned an invalid commit id") revision = commit log(f"building staged tracked tree as temporary commit {revision} " f"(HEAD is {head_revision}); this commit is not pushed") else: revision = head_revision unstaged = git(repo, "diff", "--quiet", check=False).returncode if unstaged not in (0, 1): raise NixCacheError("could not inspect unstaged git changes") if unstaged == 1: log("warning: unstaged tracked changes are ignored; only HEAD/index " "content is evaluated") tracked = git(repo, "ls-tree", "-r", "--name-only", "-z", revision, check=False) if tracked.returncode == 0: _refuse_credential_like( tracked.stdout.decode("utf-8", "replace").split("\0"), "tracked file", ) lock_proc = git(repo, "show", f"{revision}:flake.lock", check=False) if lock_proc.returncode != 0: raise NixCacheError("flake.lock is not tracked at the source revision") lock_bytes = lock_proc.stdout branch = branch_hint or os.environ.get("NIX_CACHE_BRANCH") if not branch: symbolic = git(repo, "symbolic-ref", "--quiet", "--short", "HEAD", check=False) if symbolic.returncode == 0: branch = symbolic.stdout.decode().strip() or None if not branch: for candidate in ("main", "master"): local = git(repo, "rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{candidate}", check=False) if local.returncode == 0 and local.stdout.decode().strip() == head_revision: branch = candidate break flake_url = ( "git+file://" + urllib.parse.quote(repo, safe="/") + "?rev=" + revision + "&shallow=1" ) return SourceInfo(repo, revision, flake_url, lock_bytes, branch, has_staged) def check_pushed_head(repo: str, revision: str, branch: str, remote: str, live=False) -> None: if not branch: raise NixCacheError( "cannot determine the current branch for the pushed-HEAD check; " "pass --branch or set NIX_CACHE_BRANCH" ) def remote_head(): listing = git( repo, "ls-remote", "--exit-code", remote, f"refs/heads/{branch}", check=False, timeout=180, ) if listing.returncode != 0: return None fields = listing.stdout.decode().split() return fields[0] if fields else None local_revision = None local = git( repo, "rev-parse", "--verify", "--quiet", f"refs/remotes/{remote}/{branch}", check=False, ) if local.returncode == 0: local_revision = local.stdout.decode().strip() if live: remote_revision = remote_head() if remote_revision is None: raise NixCacheError( f"cannot verify remote {remote}/{branch} HEAD immediately " "before publication; refusing to publish" ) else: remote_revision = local_revision if remote_revision != revision: # A fresh checkout can have a stale remote-tracking ref (or none # at all) for a just-pushed commit. Ask the remote directly. live_revision = remote_head() if live_revision is not None: remote_revision = live_revision elif remote_revision is None: raise NixCacheError( f"cannot verify pushed {remote}/{branch} HEAD; refusing to " "publish an unverified commit (workflow must provide git " "remote access, or pass --allow-unpushed-head for an " "operator-only smoke run)" ) if remote_revision != revision: raise NixCacheError( f"git HEAD {revision} is not the pushed {remote}/{branch} HEAD " f"{remote_revision}; refusing to publish an older build" ) def commit_exists(repo: str, revision: str, remote: str) -> bool: if git(repo, "cat-file", "-e", f"{revision}^{{commit}}", check=False).returncode == 0: return True fetched = git(repo, "fetch", "--quiet", "--no-tags", remote, revision, check=False, timeout=180) return fetched.returncode == 0 and git( repo, "cat-file", "-e", f"{revision}^{{commit}}", check=False ).returncode == 0 def is_ancestor(repo: str, ancestor: str, descendant: str, remote: str): if not commit_exists(repo, descendant, remote): return None proc = git(repo, "merge-base", "--is-ancestor", ancestor, descendant, check=False) if proc.returncode == 0: return True if proc.returncode == 1: return False raise NixCacheError("git merge-base failed while checking release ordering") def toplevel_attr(source: SourceInfo, host: str) -> str: return f"{source.flake_url}#nixosConfigurations.{host}.config.system.build.toplevel" DAEMON_DISCONNECTED = b"Nix daemon disconnected unexpectedly" BUILD_ATTEMPTS = 3 # A build is stalled when nix has printed nothing AND the guest has been idle # (no CPU time and no time waiting on disk) for this long. Silence alone is # normal (a kernel compile prints one "building" line and then nothing for an # hour), and so is a worker blocked on slow disk writeback. BUILD_STALL_SECONDS = 30 * 60 IDLE_CPU_FRACTION = 0.03 def _cpu_jiffies(): """(busy, total) jiffies from /proc/stat; iowait counts as busy.""" with open("/proc/stat", encoding="ascii") as handle: fields = [int(v) for v in handle.readline().split()[1:]] return sum(fields) - fields[3], sum(fields) class IdleStallCheck: """stall_check for run(): silent output plus an idle guest for a window.""" def __init__(self, window=BUILD_STALL_SECONDS, read_jiffies=_cpu_jiffies): self.window = window self.read_jiffies = read_jiffies self.last = read_jiffies() self.idle_for = 0.0 self.at = time.monotonic() def __call__(self, silent_for: float) -> bool: now, current = time.monotonic(), self.read_jiffies() busy = current[0] - self.last[0] total = current[1] - self.last[1] if total > 0 and busy / total > IDLE_CPU_FRACTION: self.idle_for = 0.0 else: self.idle_for += now - self.at self.last, self.at = current, now if min(silent_for, self.idle_for) < self.window: return False log(f"nix build silent and guest idle (no CPU or disk wait) for {int(self.window / 60)} " "minutes; in-flight processes:") proc = run(["ps", "-eo", "pid,ppid,etimes,stat,wchan:30,pcpu,rss,args", "--sort=start_time"], check=False, timeout=60, description="ps") log(_safe_detail(proc.stdout + proc.stderr)) log_daemon_journals() return True def log_daemon_journals() -> None: """Print the guest's nix-daemon, coredump and kernel journal tails. The CI guest adds the workflow user to systemd-journal, so this shows a worker's exit signal, OOM kill or kernel segfault line that the step log otherwise never contains. """ for what, args in ( ("nix-daemon journal", ["-u", "nix-daemon.service", "-n", "60"]), ("coredump journal", ["-t", "systemd-coredump", "-n", "40"]), ("kernel journal", ["-k", "-n", "40"]), ): proc = run(["journalctl", "-b", "--no-pager", "-o", "short-monotonic", *args], check=False, timeout=60, description=f"journalctl {what}") log(f"--- {what} ---\n{_safe_detail(proc.stdout + proc.stderr)}") def nix_eval_toplevel(attr: str) -> tuple: """Evaluate one toplevel in its own process; return (drvPath, outPath). Evaluating writes the .drv files to the store, so the build can then name derivations directly and run without an evaluator holding gigabytes. """ proc = run( nix_base() + ["eval", "--json", "--no-write-lock-file", attr, "--apply", "t: { drv = t.drvPath; out = t.outPath; }"], check=False, timeout=None, description="nix eval toplevel", ) if proc.returncode != 0: raise NixCacheError(f"toplevel did not evaluate: {_safe_detail(proc.stderr)}") try: result = json.loads(proc.stdout.decode("utf-8")) except (UnicodeDecodeError, ValueError) as exc: raise NixCacheError("nix eval returned invalid JSON") from exc if not isinstance(result, dict): raise NixCacheError("nix eval returned an unexpected toplevel result") return (validate_store_path(result.get("drv"), "toplevel derivation"), validate_store_path(result.get("out"), "toplevel output")) def in_binary_cache(cache_uri: str, path: str) -> bool: """Whether path's narinfo exists in cache_uri (our own signed S3 cache). nix copy writes a path's narinfo only after its NAR and after every dependency, so a present toplevel narinfo means its whole closure is there. """ proc = run(nix_base() + ["path-info", "--store", cache_uri, path], check=False, timeout=600, description="nix path-info cache") return proc.returncode == 0 def build_toplevels(source: SourceInfo, hosts, upload_uri: str, cache_uri: str = None) -> dict: """Build every host's toplevel in one nix invocation and upload what built. Each host is evaluated in its own short-lived process first; the build then realises the derivations without evaluating, so no evaluator heap competes with builders for guest memory. A toplevel already present in cache_uri is not realised at all: the guest's store starts empty, so realising it would copy its whole closure (tens of GiB) for nothing. One build invocation lets Nix schedule derivations from all remaining hosts together; --keep-going lets the other hosts finish after one fails. Every toplevel that validates is uploaded to upload_uri before this returns or raises. On any failure it raises NixCacheError, and callers MUST then write no release envelope. Returns {host: store path}. """ # Evaluate the original flake.lock unchanged; Nix fetches the locked inputs # itself (the private git+ssh input uses the GIT_SSH_COMMAND deploy key the # publish service provides). hosts = list(hosts) if not hosts: raise NixCacheError("no hosts to build") for host in hosts: if host not in HOST_SYSTEMS: raise VerificationError(f"unknown fleet host: {host!r}") drvs, paths, reasons = {}, {}, {} for host in hosts: log(f"evaluating {host}") try: drvs[host], paths[host] = nix_eval_toplevel(toplevel_attr(source, host)) except NixCacheError as exc: reasons[host] = str(exc) cached = set() if cache_uri: for host in list(drvs): if in_binary_cache(cache_uri, paths[host]): cached.add(host) del drvs[host] log(f"{host}: toplevel already in the cache, not rebuilding") returncode = 0 if drvs: log(f"building toplevels for {', '.join(drvs)} in one nix build") for attempt in range(1, BUILD_ATTEMPTS + 1): proc = run( nix_base() + ["build", "--no-link", "--keep-going", *(f"{drvs[h]}^out" for h in drvs)], check=False, timeout=None, stream_stderr=True, stall_check=IdleStallCheck(), description="nix build toplevels", ) returncode = proc.returncode crashed = DAEMON_DISCONNECTED in proc.stderr stalled = STALL_MARKER.encode() in proc.stderr if returncode == 0 or not (crashed or stalled): break # Everything realised so far stays in the store, so a rerun # resumes. A stall already printed its diagnostics; a crashed # daemon worker's reason is in the journal. if crashed: log_daemon_journals() if attempt < BUILD_ATTEMPTS: log(f"nix build {'stalled' if stalled else 'lost its daemon'}; " f"resuming (attempt {attempt + 1}/{BUILD_ATTEMPTS})") if returncode != 0: log(f"nix build exited {returncode}; checking each toplevel") built = {} for host in hosts: if host not in paths: continue try: validate_toplevel(paths[host], host) if host not in cached and not nix_store_valid(paths[host]): raise NixCacheError(f"not valid in the local store: {paths[host]}") except NixCacheError as exc: reasons[host] = str(exc) continue built[host] = paths[host] log(f"{'cached' if host in cached else 'built'} {host}: {paths[host]}") for host in hosts: if host in reasons: log(f"toplevel failed for {host}: {reasons[host]}") fresh = [built[h] for h in hosts if h in built and h not in cached] if fresh: log(f"uploading signed closures for {', '.join(h for h in hosts if h in built and h not in cached)} " "to the private S3 cache") nix_copy_to(upload_uri, fresh) if reasons or returncode != 0: failed = ", ".join(h for h in hosts if h in reasons) or "none" raise NixCacheError( f"toplevel build failed (nix exit {returncode}; failed hosts: " f"{failed}); uploaded {len(built)} of {len(hosts)} toplevels; " "no release envelopes will be written" ) return built # --------------------------------------------------------------------------- # Activation def release_url(cache_url: str, host: str) -> str: if host not in HOST_SYSTEMS: raise VerificationError(f"unknown fleet host: {host!r}") validate_host_system(host, HOST_SYSTEMS[host]) base = cache_url.rstrip("/") return f"{base}/releases/{urllib.parse.quote(host, safe='')}/latest.json" def validate_cache_url(cache_url: str) -> str: parsed = urllib.parse.urlsplit(cache_url) if parsed.scheme not in ("http", "https") or not parsed.netloc: raise NixCacheError("--cache-url must be an http(s) URL") if parsed.username or parsed.password: raise NixCacheError("--cache-url must not contain credentials") if parsed.query or parsed.fragment: raise NixCacheError("--cache-url must be a plain base URL without query or fragment") return cache_url.rstrip("/") FETCH_ATTEMPTS = 5 def fetch_limited(url: str, max_bytes=MAX_ENVELOPE_BYTES, timeout=60) -> bytes: """GET release metadata, retrying 5xx and connection errors. The private gateway proxies object storage, which answers transient 503s; one of those must not fail a CI-triggered activation. 4xx (missing or forbidden release) fails immediately. """ parsed = urllib.parse.urlsplit(url) if parsed.scheme not in ("http", "https") or not parsed.netloc: raise NixCacheError("refusing to fetch a non-http(s) release URL") request = urllib.request.Request( url, headers={"User-Agent": "nix-cache-activate/1", "Accept": "application/json"}, ) for attempt in range(1, FETCH_ATTEMPTS + 1): try: with urllib.request.urlopen(request, timeout=timeout) as response: final = urllib.parse.urlsplit(response.geturl()) if final.scheme not in ("http", "https"): raise NixCacheError("release fetch redirected to a non-http(s) URL") if final.username or final.password: raise NixCacheError("release fetch redirected to a URL with credentials") if response.status != 200: raise NixCacheError(f"release fetch returned HTTP {response.status}") data = response.read(max_bytes + 1) break except urllib.error.HTTPError as exc: if exc.code < 500 or attempt == FETCH_ATTEMPTS: raise NixCacheError(f"release fetch failed: HTTP {exc.code}") from exc log(f"release fetch got HTTP {exc.code}; retrying ({attempt}/{FETCH_ATTEMPTS})") except urllib.error.URLError as exc: if attempt == FETCH_ATTEMPTS: raise NixCacheError(f"release fetch failed: {exc.reason}") from exc log(f"release fetch failed ({exc.reason}); retrying ({attempt}/{FETCH_ATTEMPTS})") time.sleep(2 ** attempt) if len(data) > max_bytes: raise NixCacheError("release metadata is too large") return data def activate_toplevel(toplevel: str) -> None: validate_store_path(toplevel, "toplevel") switch = os.path.join(toplevel, "bin", "switch-to-configuration") if not os.path.isfile(switch) or not os.access(switch, os.X_OK): raise NixCacheError( "toplevel has no executable bin/switch-to-configuration; refusing " "to change the system profile" ) # One portable prebuilt activation sequence for every host. It avoids # nixos-rebuild/flake evaluation entirely and works on old and new # NixOS: install the exact generation, then run that generation's own # activation script. Success is only recorded after the second command # exits successfully. run( ["nix-env", "--profile", "/nix/var/nix/profiles/system", "--set", toplevel], timeout=None, description="nix-env --set system profile", ) run( [switch, "switch"], timeout=None, description="switch-to-configuration", ) def write_last_success(state_dir: str, host: str, system: str, meta: dict, cache_url: str) -> None: record = { "version": 1, "host": host, "system": system, "revision": meta["revision"], "toplevel": meta["toplevel"], "publishedAt": meta["publishedAt"], "activatedAt": int(time.time()), "cacheUrl": cache_url, } atomic_write( os.path.join(state_dir, "last-success.json"), canonical_json(record) + b"\n", ) def activation_banner(host: str, system: str, meta: dict) -> str: return ( f"verified release for {host} ({system}): revision {meta['revision']}, " f"toplevel {meta['toplevel']}, publishedAt {meta['publishedAt']}" ) # --------------------------------------------------------------------------- # SSH trigger def parse_pinned_host_key(path: str): require_regular_file(path, "pinned SSH host key") lines = [] with open(path, "r", encoding="utf-8") as handle: for raw in handle: line = raw.strip() if line and not line.startswith("#"): lines.append(line) if len(lines) != 1: raise NixCacheError( f"pinned SSH host key must contain exactly one key: {path}" ) fields = lines[0].split() if len(fields) < 2: raise NixCacheError(f"pinned SSH host key is malformed: {path}") key_type, key_data = fields[0], fields[1] if key_type not in ( "ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", ): raise NixCacheError(f"unsupported pinned SSH host key type: {key_type}") try: base64.b64decode(key_data, validate=True) except (binascii.Error, ValueError) as exc: raise NixCacheError(f"pinned SSH host key is not valid base64: {path}") from exc return key_type, key_data def trigger_activation(host: str, *, ssh_key_file: str, pinned_key_file: str, server: str, port: int, user: str) -> None: if host not in ("homura", "sayaka"): raise NixCacheError(f"host {host!r} is not CI-triggerable") require_private_file(ssh_key_file, "CI trigger SSH key") key_type, key_data = parse_pinned_host_key(pinned_key_file) with tempfile.TemporaryDirectory(prefix="nix-cache-ssh-") as tmp: known_hosts = os.path.join(tmp, "known_hosts") pattern = f"[{server}]:{port}" if port != 22 else server with open(known_hosts, "w", encoding="utf-8") as handle: handle.write(f"{pattern} {key_type} {key_data}\n") os.chmod(known_hosts, 0o600) command = [ "ssh", "-F", "/dev/null", "-T", "-p", str(port), "-i", ssh_key_file, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none", "-o", "StrictHostKeyChecking=yes", "-o", "CheckHostIP=no", "-o", "UpdateHostKeys=no", "-o", f"UserKnownHostsFile={known_hosts}", "-o", "GlobalKnownHostsFile=/dev/null", "-o", "PasswordAuthentication=no", "-o", "KbdInteractiveAuthentication=no", "-o", "ConnectTimeout=30", "-o", "LogLevel=ERROR", f"{user}@{server}", host, ] run(command, timeout=180, description=f"trigger {host} activation") log(f"queued activation for {host}") ACTIVATION_UNIT = "nixos-cache-activate.service" def trigger_local_activation() -> None: """Queue this machine's activation unit (the publisher runs on homura). --no-block returns once the job is queued; the unit then verifies and activates the just-published release itself. Homura's polkit rule allows the publisher user to start exactly this unit and nothing else. """ run(["systemctl", "start", "--no-block", ACTIVATION_UNIT], timeout=60, description="start local activation") log(f"queued activation for {socket.gethostname()}")