Files
pipelines/scripts/update_signing.py
T
alan 9f38e38f6a Sign the app update feed with Ed25519 and verify it in the app
Each installation generates a private Ed25519 key once (0600, under
~/.config/pipelines), signs version.json with a detached version.json.sig
when publishing APK and desktop builds, and embeds its own and listed
trusted public keys in app builds. The app verifies the feed signature
before trusting the artifact sha256, refuses unsigned or foreign feeds when
it has keys, and requires the sha256 and Android signer in signed feeds.
2026-11-10 00:51:16 +00:00

190 lines
7.3 KiB
Python

"""Ed25519 signing for the app update feed.
Each installation owns one private key, generated once into a 0600 file under
~/.config/pipelines/ (never in the repository). App builds embed the public key
(`--dart-define=PIPELINES_UPDATE_PUBLIC_KEY`, comma separated) together with any
other servers' keys listed one per line in
~/.config/pipelines/update-trusted-keys. Publishing writes `version.json` and a
detached `version.json.sig` over its exact bytes; the app verifies that
signature with an embedded key before it trusts the artifact sha256 inside.
The OpenSSL 3 command line does the cryptography (the system Python has no
`cryptography` package and macOS's LibreSSL has no Ed25519), so the tool is
looked up explicitly: PIPELINES_OPENSSL, Homebrew's openssl@3, then PATH.
"""
import base64
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
KEY_NAME = "update-signing-key.pem"
TRUSTED_NAME = "update-trusted-keys"
SIGNATURE_SUFFIX = ".sig"
DEFINE = "PIPELINES_UPDATE_PUBLIC_KEY"
CANDIDATES = ("/opt/homebrew/opt/openssl@3/bin/openssl", "/usr/local/opt/openssl@3/bin/openssl")
# DER SubjectPublicKeyInfo for Ed25519 is this 12-byte prefix plus the raw key.
SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")
def config_dir():
return Path.home() / ".config/pipelines"
def key_path(environ=None):
environ = os.environ if environ is None else environ
explicit = environ.get("PIPELINES_UPDATE_SIGNING_KEY")
return Path(explicit).expanduser() if explicit else config_dir() / KEY_NAME
def _supports_ed25519(tool):
try:
result = subprocess.run([tool, "genpkey", "-algorithm", "ed25519"],
capture_output=True, timeout=30)
except (OSError, subprocess.TimeoutExpired):
return False
return result.returncode == 0 and b"PRIVATE KEY" in result.stdout
def openssl(environ=None):
"""An OpenSSL executable with Ed25519 support, or a clear error."""
environ = os.environ if environ is None else environ
found = [environ.get("PIPELINES_OPENSSL"), *CANDIDATES, shutil.which("openssl")]
for tool in dict.fromkeys(t for t in found if t):
if _supports_ed25519(tool):
return tool
raise ValueError("Update signing needs OpenSSL 3 with Ed25519 (LibreSSL lacks it): "
"install openssl@3 (brew install openssl@3) or set PIPELINES_OPENSSL")
def _check_private(path):
if path.is_symlink() or not path.is_file():
raise ValueError(f"Update signing key must be a regular file: {path}")
if path.stat().st_mode & 0o077:
raise ValueError(f"Update signing key must be private (chmod 600): {path}")
def ensure_key(environ=None):
"""The installation's signing key, generated once (0600) when absent."""
path = key_path(environ)
if path.exists() or path.is_symlink():
_check_private(path)
return path
tool = openssl(environ)
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix=".update-key-", dir=path.parent)
os.close(descriptor)
try:
os.chmod(temporary, 0o600)
result = subprocess.run([tool, "genpkey", "-algorithm", "ed25519", "-out", temporary],
capture_output=True, text=True, timeout=30)
if result.returncode:
raise ValueError("Could not generate the update signing key: " + result.stderr.strip())
os.chmod(temporary, 0o600)
# Never replace a key another process created meanwhile.
os.link(temporary, path)
finally:
Path(temporary).unlink(missing_ok=True)
_check_private(path)
return path
def public_key(key, environ=None):
"""The raw 32-byte public key, base64 encoded."""
result = subprocess.run([openssl(environ), "pkey", "-in", str(key), "-pubout", "-outform", "DER"],
capture_output=True, timeout=30)
der = result.stdout
if result.returncode or len(der) != 44 or not der.startswith(SPKI_PREFIX):
raise ValueError(f"Could not read the Ed25519 public key from {key}")
return base64.b64encode(der[len(SPKI_PREFIX):]).decode()
def valid_public_key(text):
try:
return len(base64.b64decode(text, validate=True)) == 32
except ValueError:
return False
def trusted_keys(environ=None):
"""This installation's key first, then other servers' keys it trusts."""
keys = [public_key(ensure_key(environ), environ)]
listed = config_dir() / TRUSTED_NAME
if listed.is_file():
for number, line in enumerate(listed.read_text().splitlines(), 1):
line = line.split("#", 1)[0].strip()
if not line:
continue
if not valid_public_key(line):
raise ValueError(f"{listed}:{number} is not a base64 Ed25519 public key")
keys.append(line)
return list(dict.fromkeys(keys))
def dart_defines(environ=None):
"""The build argument embedding the trusted update keys."""
return (f"--dart-define={DEFINE}={','.join(trusted_keys(environ))}",)
def sign(data, key, environ=None):
"""A raw 64-byte Ed25519 signature over [data]."""
with tempfile.NamedTemporaryFile(prefix="pipelines-feed-") as message:
message.write(data)
message.flush()
result = subprocess.run([openssl(environ), "pkeyutl", "-sign", "-rawin", "-inkey", str(key),
"-in", message.name], capture_output=True, timeout=30)
if result.returncode or len(result.stdout) != 64:
raise ValueError("Could not sign the update feed: " + result.stderr.decode(errors="replace").strip())
return result.stdout
def signature_document(data, key, environ=None):
"""The detached `version.json.sig` content for feed bytes [data]."""
return (json.dumps({"algorithm": "ed25519", "publicKey": public_key(key, environ),
"signature": base64.b64encode(sign(data, key, environ)).decode()}) + "\n").encode()
class Signer:
"""Signs feeds with one key file; the installer's key unless given."""
def __init__(self, key=None, environ=None):
self.environ = environ
self.key = Path(key) if key else ensure_key(environ)
_check_private(self.key)
def __call__(self, data):
return signature_document(data, self.key, self.environ)
def write_atomic(path, content, mode=0o644):
descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", dir=path.parent)
try:
with os.fdopen(descriptor, "wb") as output:
output.write(content)
output.flush()
os.fsync(output.fileno())
os.chmod(temporary, mode)
os.replace(temporary, path)
finally:
Path(temporary).unlink(missing_ok=True)
def publish_feed(directory, metadata, signer):
"""Writes the signature, then the feed it covers, both atomically.
A reader racing a publish may see a new signature with the old feed for a
moment; that verification fails and the next check succeeds."""
data = (json.dumps(metadata) + "\n").encode()
signature = signer(data)
write_atomic(directory / ("version.json" + SIGNATURE_SUFFIX), signature)
write_atomic(directory / "version.json", data)
return data
if __name__ == "__main__":
# Prints this installation's public key, for another server's
# update-trusted-keys file (generating the key on first use).
print(public_key(ensure_key()))