vole
Site
Clone
Read only, no credentials:
https://rodent.software/vole.git
Write over SSH with a registered key:
git clone ssh://git@rodent.software/vole.git
Self-hosted forge that lives in your Git repo.
| 1 | #!/usr/bin/env python3 |
| 2 | """Sign a release's packages and the repositories that carry them. |
| 3 | |
| 4 | This script adds the signatures apt and dnf check to a release tree: |
| 5 | |
| 6 | python3 scripts/sign-release.py packages --dist dist |
| 7 | # build apt/ and yum/ from the signed packages |
| 8 | python3 scripts/sign-release.py repositories --dist dist |
| 9 | # write SHA256SUMS |
| 10 | python3 scripts/sign-release.py sums --dist dist |
| 11 | |
| 12 | The private key arrives as the `RELEASE_GPG_KEY` secret, armored. The script |
| 13 | imports it into a temporary GnuPG home, signs, verifies what it signed, exports |
| 14 | the public key beside the repository, and removes the key material before it |
| 15 | exits. `--key-file` does the same from a path, for local testing. |
| 16 | |
| 17 | What is signed, and why: |
| 18 | |
| 19 | - the RPM packages, because dnf checks each package's signature when |
| 20 | `gpgcheck=1`; |
| 21 | - the Arch packages, as a detached `.sig` beside each package, because pacman |
| 22 | checks it with `SigLevel = Required`; |
| 23 | - the apt metadata (`InRelease` and `Release.gpg`), because apt verifies the |
| 24 | `Release` file and the hashes in it authenticate every `.deb` it lists. dpkg |
| 25 | does not check a signature on an individual `.deb`, so signing those files |
| 26 | would be a check nobody performs; |
| 27 | - the RPM repository metadata (`repomd.xml.asc`), because dnf verifies it when |
| 28 | `repo_gpgcheck=1`; |
| 29 | - the pacman databases (`vole.db` and `vole.files`), because pacman verifies |
| 30 | them with `DatabaseRequired`; |
| 31 | - `SHA256SUMS`, so a direct download can be authenticated without the |
| 32 | repository; |
| 33 | - the public key is published as `apt/vole.gpg`, `yum/RPM-GPG-KEY-vole`, and |
| 34 | `vole-release-key.asc`, with its fingerprint in `vole-release-key.fingerprint`. |
| 35 | The armored copies are `packaging/keys/vole-release.asc` verbatim, so |
| 36 | `packaging/install.sh` can pin that file's SHA-256 as well as the fingerprint. |
| 37 | |
| 38 | Signatures carry the tag commit time (`--epoch`) rather than the build clock, so |
| 39 | rebuilding one tag produces the same signed files. GnuPG refuses a signature |
| 40 | time before the key was created, so the time used is the later of the two; that |
| 41 | is also the value both signing tools are given, including `rpmsign` through its |
| 42 | `%_gpg_sign_cmd_extra_args` macro. A key that has expired at that time is an |
| 43 | error: rotate the key rather than sign with it. |
| 44 | |
| 45 | The public key must be committed at `packaging/keys/vole-release.asc`, and the |
| 46 | secret must produce the same fingerprint. A missing key, a rotated key, or a |
| 47 | stale committed key fails here instead of publishing signatures that no |
| 48 | documented key verifies. |
| 49 | """ |
| 50 | |
| 51 | import argparse |
| 52 | import os |
| 53 | import shutil |
| 54 | import subprocess |
| 55 | import sys |
| 56 | import tempfile |
| 57 | import time |
| 58 | from pathlib import Path |
| 59 | |
| 60 | ROOT = Path(__file__).resolve().parent.parent |
| 61 | COMMITTED_KEY = ROOT / "packaging" / "keys" / "vole-release.asc" |
| 62 | GPG = "gpg" |
| 63 | |
| 64 | |
| 65 | def run(cmd: list[str], capture: bool = False) -> subprocess.CompletedProcess: |
| 66 | return subprocess.run(cmd, check=True, text=True, capture_output=capture) |
| 67 | |
| 68 | |
| 69 | def run_bytes(cmd: list[str]) -> bytes: |
| 70 | return subprocess.run(cmd, check=True, capture_output=True).stdout |
| 71 | |
| 72 | |
| 73 | def gpg(home: Path, *args: str, capture: bool = False) -> subprocess.CompletedProcess: |
| 74 | return run([GPG, "--batch", "--no-tty", "--homedir", str(home), *args], capture=capture) |
| 75 | |
| 76 | |
| 77 | def read_key(args: argparse.Namespace) -> str | None: |
| 78 | if args.key_file: |
| 79 | try: |
| 80 | return Path(args.key_file).read_text(encoding="utf-8") |
| 81 | except OSError as err: |
| 82 | sys.exit(f"cannot read the signing key: {err}") |
| 83 | key = os.environ.get("RELEASE_GPG_KEY", "") |
| 84 | if key.strip(): |
| 85 | return key |
| 86 | if args.allow_missing_key and not os.environ.get("VOLE_EVENT"): |
| 87 | # A local run is a build check, not a publication. A pushed tag has an |
| 88 | # event and must sign: an unsigned release is the failure this change |
| 89 | # exists to prevent. |
| 90 | print("RELEASE_GPG_KEY is not set; this local run leaves the release tree unsigned", file=sys.stderr) |
| 91 | return None |
| 92 | sys.exit( |
| 93 | "RELEASE_GPG_KEY is not set: store the armored private release key as a " |
| 94 | "repository secret (see RELEASING.md)" |
| 95 | ) |
| 96 | |
| 97 | |
| 98 | def import_key(home: Path, key: str) -> None: |
| 99 | path = home / "release-key.asc" |
| 100 | path.write_text(key if key.endswith("\n") else key + "\n", encoding="utf-8") |
| 101 | path.chmod(0o600) |
| 102 | try: |
| 103 | gpg(home, "--import", str(path)) |
| 104 | finally: |
| 105 | path.unlink() |
| 106 | |
| 107 | |
| 108 | def secret_key(home: Path, wanted: str | None) -> tuple[str, int, int]: |
| 109 | """Return the fingerprint, creation time, and expiry of the signing key.""" |
| 110 | out = gpg(home, "--with-colons", "--list-secret-keys", capture=True).stdout |
| 111 | keys, current = [], None |
| 112 | for line in out.splitlines(): |
| 113 | fields = line.split(":") |
| 114 | if fields[0] == "sec": |
| 115 | current = {"created": int(fields[5]), "expires": int(fields[6] or 0), "fingerprint": ""} |
| 116 | keys.append(current) |
| 117 | elif fields[0] == "fpr" and current is not None and not current["fingerprint"]: |
| 118 | current["fingerprint"] = fields[9] |
| 119 | if wanted: |
| 120 | keys = [ |
| 121 | key |
| 122 | for key in keys |
| 123 | if wanted.lower() in key["fingerprint"].lower() or wanted.lower() == key["fingerprint"][-16:].lower() |
| 124 | ] |
| 125 | if not keys: |
| 126 | sys.exit("the signing key file has no secret key" + (f" matching {wanted}" if wanted else "")) |
| 127 | if len(keys) > 1: |
| 128 | sys.exit( |
| 129 | "the signing key file holds more than one secret key; keep only the release key " |
| 130 | "in the secret or name it with --key" |
| 131 | ) |
| 132 | key = keys[0] |
| 133 | if not key["fingerprint"]: |
| 134 | sys.exit("cannot read the signing key's fingerprint") |
| 135 | return key["fingerprint"], key["created"], key["expires"] |
| 136 | |
| 137 | |
| 138 | def signing_time(epoch: int, created: int, expires: int, fingerprint: str) -> int: |
| 139 | """The signature time, pinned to the tag but never before the key existed.""" |
| 140 | when = max(epoch, created) |
| 141 | if expires: |
| 142 | expired = time.strftime("%Y-%m-%d", time.gmtime(expires)) |
| 143 | # A signature made with a fake clock before expiry is still rejected by a |
| 144 | # client whose clock says the key has expired, so check both clocks. |
| 145 | if time.time() > expires or when > expires: |
| 146 | sys.exit( |
| 147 | f"the release key {fingerprint} expired at {expired}; rotate it before signing a release" |
| 148 | ) |
| 149 | return when |
| 150 | |
| 151 | |
| 152 | def verify(home: Path, signature: Path, data: Path | None = None) -> None: |
| 153 | args = ["--verify", str(signature)] + ([str(data)] if data else []) |
| 154 | gpg(home, *args) |
| 155 | |
| 156 | |
| 157 | def check_committed_key(home: Path, fingerprint: str) -> None: |
| 158 | if not COMMITTED_KEY.is_file(): |
| 159 | sys.exit( |
| 160 | f"{COMMITTED_KEY.relative_to(ROOT)} is missing: commit the public release key " |
| 161 | "before signing, so clients can compare the fingerprint through Git" |
| 162 | ) |
| 163 | out = gpg( |
| 164 | home, |
| 165 | "--with-colons", |
| 166 | "--import-options", "show-only", |
| 167 | "--import", str(COMMITTED_KEY), |
| 168 | capture=True, |
| 169 | ).stdout |
| 170 | fingerprints = [line.split(":")[9] for line in out.splitlines() if line.startswith("fpr:")] |
| 171 | if not fingerprints: |
| 172 | sys.exit(f"cannot read a fingerprint from {COMMITTED_KEY.relative_to(ROOT)}") |
| 173 | if fingerprints[0].upper() != fingerprint.upper(): |
| 174 | sys.exit( |
| 175 | f"the signing key {fingerprint} does not match " |
| 176 | f"{COMMITTED_KEY.relative_to(ROOT)} ({fingerprints[0]}); " |
| 177 | "publish the new key in the same change that rotates the secret" |
| 178 | ) |
| 179 | |
| 180 | |
| 181 | def sign_packages(dist: Path, home: Path, fingerprint: str, when: int) -> None: |
| 182 | packages = sorted(dist.glob("vole-*.rpm")) |
| 183 | if not packages: |
| 184 | sys.exit(f"no RPM packages to sign in {dist}") |
| 185 | if shutil.which("rpm") is None: |
| 186 | sys.exit("rpm is not installed; the workflow images carry the rpm package that provides rpmsign") |
| 187 | run( |
| 188 | [ |
| 189 | "rpm", "--addsign", |
| 190 | "--define", f"_gpg_name {fingerprint}", |
| 191 | "--define", f"_gpg_path {home}", |
| 192 | "--define", "__gpg /usr/bin/gpg", |
| 193 | # rpmsign asks gpg to sign a detached header/payload signature; this |
| 194 | # is where the tag time reaches gpg so a rebuild is byte-identical. |
| 195 | "--define", f"_gpg_sign_cmd_extra_args --faked-system-time {when}", |
| 196 | *[str(package) for package in packages], |
| 197 | ] |
| 198 | ) |
| 199 | for package in packages: |
| 200 | # A V4 RPM keeps its signature in the immutable header, so SIGPGP and |
| 201 | # SIGGPG are empty even though the package is signed. Check the header |
| 202 | # tags rpm 4.16+ actually writes. |
| 203 | signature = run( |
| 204 | [ |
| 205 | "rpm", "-qp", |
| 206 | "--qf", "%{RSAHEADER:pgpsig}|%{DSAHEADER:pgpsig}|%{SIGPGP:pgpsig}|%{SIGGPG:pgpsig}", |
| 207 | str(package), |
| 208 | ], |
| 209 | capture=True, |
| 210 | ).stdout.strip() |
| 211 | if not signature or all(part == "(none)" for part in signature.split("|")): |
| 212 | sys.exit(f"{package} is still unsigned after rpm --addsign") |
| 213 | |
| 214 | # An Arch package carries a detached .sig beside it rather than a signature |
| 215 | # inside the archive. repo-add records that signature in %PGPSIG%, and pacman |
| 216 | # checks it when the package is downloaded. |
| 217 | arch_packages = sorted(dist.glob("vole-*.pkg.tar.zst")) |
| 218 | if not arch_packages: |
| 219 | sys.exit(f"no Arch packages to sign in {dist}") |
| 220 | for package in arch_packages: |
| 221 | signature = package.with_name(package.name + ".sig") |
| 222 | gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint, |
| 223 | "--detach-sign", "--output", str(signature), str(package)) |
| 224 | verify(home, signature, package) |
| 225 | |
| 226 | |
| 227 | def sign_repositories(dist: Path, home: Path, fingerprint: str, when: int, |
| 228 | committed: bool = False) -> None: |
| 229 | release = dist / "apt" / "Release" |
| 230 | repomd = dist / "yum" / "repodata" / "repomd.xml" |
| 231 | for required in (release, repomd): |
| 232 | if not required.is_file(): |
| 233 | sys.exit(f"{required} is missing; build the repositories before signing them") |
| 234 | |
| 235 | pacman_dirs = sorted(directory for directory in (dist / "pacman").glob("*") if directory.is_dir()) |
| 236 | if not pacman_dirs: |
| 237 | sys.exit(f"no pacman repositories in {dist}") |
| 238 | for directory in pacman_dirs: |
| 239 | for name in ("vole.db", "vole.files"): |
| 240 | if not (directory / name).is_file(): |
| 241 | sys.exit(f"{directory / name} is missing; build the pacman repository before signing it") |
| 242 | |
| 243 | inrelease = release.with_name("InRelease") |
| 244 | release_gpg = release.with_name("Release.gpg") |
| 245 | repomd_sig = repomd.with_name("repomd.xml.asc") |
| 246 | |
| 247 | gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint, |
| 248 | "--armor", "--clearsign", "--output", str(inrelease), str(release)) |
| 249 | gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint, |
| 250 | "--armor", "--detach-sign", "--output", str(release_gpg), str(release)) |
| 251 | gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint, |
| 252 | "--armor", "--detach-sign", "--output", str(repomd_sig), str(repomd)) |
| 253 | |
| 254 | verify(home, inrelease) |
| 255 | verify(home, release_gpg, release) |
| 256 | verify(home, repomd_sig, repomd) |
| 257 | |
| 258 | # Pacman database signatures are detached binary files named after the |
| 259 | # database. SigLevel = Required DatabaseRequired checks both. |
| 260 | for directory in pacman_dirs: |
| 261 | # The database's %PGPSIG% comes from the package signature repo-add read. |
| 262 | # A release must not publish a database whose packages are unsigned. |
| 263 | for package in sorted(directory.glob("*.pkg.tar.zst")): |
| 264 | signature = package.with_name(package.name + ".sig") |
| 265 | if not signature.is_file(): |
| 266 | sys.exit(f"{package} has no signature; sign the packages before signing the pacman database") |
| 267 | verify(home, signature, package) |
| 268 | for name in ("vole.db", "vole.files"): |
| 269 | path = directory / name |
| 270 | signature = path.with_name(name + ".sig") |
| 271 | gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint, |
| 272 | "--detach-sign", "--output", str(signature), str(path)) |
| 273 | verify(home, signature, path) |
| 274 | |
| 275 | # apt wants a keyring file, not armored text, in signed-by=. dnf and the |
| 276 | # release page are easier to read armored, so both forms are published. The |
| 277 | # real release publishes the committed key verbatim: install.sh pins that |
| 278 | # file's SHA-256, so a fresh export with different armor would break the pin. |
| 279 | # A local --key-file is a test key and is exported from the temporary home. |
| 280 | binary = run_bytes([GPG, "--batch", "--no-tty", "--homedir", str(home), "--export", fingerprint]) |
| 281 | if committed: |
| 282 | armored = COMMITTED_KEY.read_text(encoding="utf-8") |
| 283 | if not armored.endswith("\n"): |
| 284 | armored += "\n" |
| 285 | else: |
| 286 | armored = gpg(home, "--armor", "--export", fingerprint, capture=True).stdout |
| 287 | (dist / "apt" / "vole.gpg").write_bytes(binary) |
| 288 | (dist / "yum" / "RPM-GPG-KEY-vole").write_text(armored, encoding="utf-8") |
| 289 | (dist / "vole-release-key.asc").write_text(armored, encoding="utf-8") |
| 290 | (dist / "vole-release-key.fingerprint").write_text(fingerprint.upper() + "\n", encoding="utf-8") |
| 291 | |
| 292 | |
| 293 | def sign_sums(dist: Path, home: Path, fingerprint: str, when: int) -> None: |
| 294 | sums = dist / "SHA256SUMS" |
| 295 | if not sums.is_file(): |
| 296 | sys.exit(f"{sums} is missing; write the checksums before signing them") |
| 297 | signature = dist / "SHA256SUMS.asc" |
| 298 | gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint, |
| 299 | "--armor", "--detach-sign", "--output", str(signature), str(sums)) |
| 300 | verify(home, signature, sums) |
| 301 | |
| 302 | |
| 303 | def main() -> None: |
| 304 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 305 | subparsers = parser.add_subparsers(dest="command", required=True) |
| 306 | for name, text in ( |
| 307 | ("packages", "sign the RPM and Arch packages in the release tree"), |
| 308 | ("repositories", "sign apt, yum, and pacman metadata and export the public key"), |
| 309 | ("sums", "sign SHA256SUMS"), |
| 310 | ): |
| 311 | sub = subparsers.add_parser(name, help=text) |
| 312 | sub.add_argument("--dist", default="dist", help="release tree (default: dist)") |
| 313 | sub.add_argument( |
| 314 | "--epoch", |
| 315 | type=int, |
| 316 | default=int(os.environ.get("SOURCE_DATE_EPOCH") or time.time()), |
| 317 | help="tag commit time in seconds (default: SOURCE_DATE_EPOCH, else the clock)", |
| 318 | ) |
| 319 | sub.add_argument("--key", help="fingerprint of the secret key to use when the file holds more than one") |
| 320 | sub.add_argument("--key-file", help="read the armored private key from this file instead of RELEASE_GPG_KEY") |
| 321 | sub.add_argument( |
| 322 | "--allow-missing-key", |
| 323 | action="store_true", |
| 324 | help="a local run (no VOLE_EVENT) may continue unsigned when RELEASE_GPG_KEY is unset", |
| 325 | ) |
| 326 | args = parser.parse_args() |
| 327 | |
| 328 | dist = Path(args.dist).resolve() |
| 329 | if not dist.is_dir(): |
| 330 | sys.exit(f"{args.dist} is not a directory") |
| 331 | key = read_key(args) |
| 332 | if key is None: |
| 333 | return |
| 334 | with tempfile.TemporaryDirectory(prefix="vole-sign-") as temporary: |
| 335 | home = Path(temporary) |
| 336 | home.chmod(0o700) |
| 337 | try: |
| 338 | import_key(home, key) |
| 339 | fingerprint, created, expires = secret_key(home, args.key) |
| 340 | # A key file is a local test key; the committed public key describes |
| 341 | # the repository's release key, which the secret must match. |
| 342 | if not args.key_file: |
| 343 | check_committed_key(home, fingerprint) |
| 344 | when = signing_time(args.epoch, created, expires, fingerprint) |
| 345 | print(f"signing with {fingerprint} at {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(when))}") |
| 346 | if args.command == "packages": |
| 347 | sign_packages(dist, home, fingerprint, when) |
| 348 | elif args.command == "repositories": |
| 349 | sign_repositories(dist, home, fingerprint, when, committed=not args.key_file) |
| 350 | else: |
| 351 | sign_sums(dist, home, fingerprint, when) |
| 352 | finally: |
| 353 | gpgconf = shutil.which("gpgconf") |
| 354 | if gpgconf: |
| 355 | subprocess.run([gpgconf, "--homedir", str(home), "--kill", "all"], check=False, |
| 356 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 357 | |
| 358 | |
| 359 | if __name__ == "__main__": |
| 360 | main() |
| 361 |