#!/usr/bin/env python3 """Publish Echoion's signed channel catalog and per-component feeds.""" from __future__ import annotations import argparse import base64 from datetime import datetime, timedelta, timezone import hashlib import json import os from pathlib import Path import re import stat import subprocess import tempfile from typing import Any, NoReturn from urllib.parse import quote, urlsplit CHANNELS = {"stable", "beta", "nightly"} SHA256 = re.compile(r"^[0-9a-f]{64}$") GIT_SHA = re.compile(r"^[0-9a-f]{40}$") SEMVER = re.compile( r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" ) TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$") def fail(message: str) -> NoReturn: raise SystemExit(f"publish-component-feeds: {message}") def canonical(document: Any) -> bytes: return ( json.dumps( document, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(",", ":"), ).encode("utf-8") + b"\n" ) def readable(document: Any) -> bytes: return ( json.dumps( document, ensure_ascii=False, allow_nan=False, sort_keys=True, indent=2, ).encode("utf-8") + b"\n" ) def load_object(path: Path, label: str) -> dict[str, Any]: try: document = json.loads(path.read_text(encoding="utf-8")) except (OSError, UnicodeError, json.JSONDecodeError) as error: fail(f"cannot read {label} {path}: {error}") if not isinstance(document, dict): fail(f"{label} must be a JSON object: {path}") return document def regular_file(path: Path, label: str, *, private: bool = False) -> Path: try: metadata = path.lstat() except OSError as error: fail(f"cannot inspect {label} {path}: {error}") if not stat.S_ISREG(metadata.st_mode) or path.is_symlink(): fail(f"{label} is not a regular file: {path}") if private and metadata.st_mode & 0o077: fail(f"{label} must not be accessible by group or others") return path.resolve(strict=True) def digest(path: Path) -> str: value = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): value.update(chunk) return value.hexdigest() def parse_time(value: str | None) -> datetime: if value is None: source_epoch = os.environ.get("SOURCE_DATE_EPOCH") if source_epoch and source_epoch.isdigit(): return datetime.fromtimestamp(int(source_epoch), timezone.utc) return datetime.now(timezone.utc).replace(microsecond=0) try: parsed = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") except ValueError: fail("--generated-at must use UTC YYYY-MM-DDTHH:MM:SSZ") return parsed.replace(tzinfo=timezone.utc) def format_time(value: datetime) -> str: return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def run_openssl(arguments: list[str], label: str) -> None: try: completed = subprocess.run( ["openssl", *arguments], check=False, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except FileNotFoundError: fail("openssl is required to sign component feeds") if completed.returncode != 0: detail = completed.stderr.decode("utf-8", errors="replace").strip() fail(f"OpenSSL could not {label}: {detail}") class Signer: def __init__(self, private_key: Path, key_id: str) -> None: self.private_key = regular_file(private_key, "private key", private=True) self.key_id = key_id self.temporary = tempfile.TemporaryDirectory( prefix="echoion-component-feed." ) self.directory = Path(self.temporary.name) self.public_key = self.directory / "public.pem" run_openssl( [ "pkey", "-in", os.fspath(self.private_key), "-pubout", "-out", os.fspath(self.public_key), ], "derive the feed public key", ) def close(self) -> None: self.temporary.cleanup() def envelope(self, payload: dict[str, Any]) -> bytes: payload_bytes = canonical(payload) payload_path = self.directory / "payload.json" signature_path = self.directory / "signature.bin" payload_path.write_bytes(payload_bytes) run_openssl( [ "pkeyutl", "-sign", "-rawin", "-inkey", os.fspath(self.private_key), "-in", os.fspath(payload_path), "-out", os.fspath(signature_path), ], "sign a component feed", ) signature = signature_path.read_bytes() if len(signature) != 64: fail("OpenSSL returned a non-Ed25519 signature") return readable( { "schemaVersion": 3, "keyId": self.key_id, "document": payload, "signedPayload": base64.urlsafe_b64encode(payload_bytes) .rstrip(b"=") .decode("ascii"), "signature": base64.urlsafe_b64encode(signature) .rstrip(b"=") .decode("ascii"), } ) def verify(self, envelope_bytes: bytes, label: str) -> dict[str, Any]: try: envelope = json.loads(envelope_bytes) schema = envelope.get("schemaVersion") if schema == 2: encoded_payload = envelope["payload"] displayed_document = None elif schema == 3: encoded_payload = envelope["signedPayload"] displayed_document = envelope["document"] if not isinstance(displayed_document, dict): raise TypeError("document is not an object") else: raise ValueError("unsupported envelope schema") payload = base64.urlsafe_b64decode( str(encoded_payload) + "=" * (-len(encoded_payload) % 4) ) signature = base64.urlsafe_b64decode( str(envelope["signature"]) + "=" * (-len(envelope["signature"]) % 4) ) except (KeyError, ValueError, TypeError, json.JSONDecodeError) as error: fail(f"invalid existing {label}: {error}") if ( envelope.get("keyId") != self.key_id or len(signature) != 64 ): fail(f"existing {label} has the wrong schema, key, or signature") if displayed_document is not None and canonical(displayed_document) != payload: fail(f"existing {label} readable document differs from signed payload") payload_path = self.directory / "verify-payload.json" signature_path = self.directory / "verify-signature.bin" payload_path.write_bytes(payload) signature_path.write_bytes(signature) run_openssl( [ "pkeyutl", "-verify", "-rawin", "-pubin", "-inkey", os.fspath(self.public_key), "-in", os.fspath(payload_path), "-sigfile", os.fspath(signature_path), ], f"verify existing {label}", ) try: document = json.loads(payload) except (UnicodeError, json.JSONDecodeError) as error: fail(f"invalid existing {label} payload: {error}") if not isinstance(document, dict): fail(f"existing {label} payload is not an object") return document class PublicKeyVerifier: verify = Signer.verify def __init__(self, public_key: Path, key_id: str) -> None: self.public_key = regular_file(public_key, "public key") self.key_id = key_id self.temporary = tempfile.TemporaryDirectory( prefix="echoion-component-feed-verify." ) self.directory = Path(self.temporary.name) run_openssl( [ "pkey", "-pubin", "-in", os.fspath(self.public_key), "-noout", ], "validate the feed public key", ) def close(self) -> None: self.temporary.cleanup() def validate_https(value: str, label: str) -> str: parsed = urlsplit(value) if ( parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment ): fail(f"{label} must be a credential-free HTTPS base URL") return value.rstrip("/") def component_path(registry: dict[str, Any], component_id: str) -> Path: entry = registry["components"][component_id] if entry["kind"] == "plugin": return Path("plugins") / entry["pluginId"] return Path(entry["packageId"]) def channel_version(stable: str, channel: str, sequence: int) -> str: if not SEMVER.fullmatch(stable) or "-" in stable: fail(f"locked component version is not stable SemVer: {stable!r}") if channel == "stable": return stable return f"{stable}-{channel}.{sequence}" def validate_metadata( registry: dict[str, Any], lock: dict[str, Any] ) -> list[str]: if registry.get("schemaVersion") != 1 or lock.get("schemaVersion") != 2: fail("unsupported component registry or lock schema") registry_components = registry.get("components") lock_components = lock.get("components") if not isinstance(registry_components, dict) or not isinstance( lock_components, dict ): fail("component metadata has no components object") if set(registry_components) != set(lock_components): fail("component registry and lock contain different component IDs") if not SEMVER.fullmatch(str(lock.get("productVersion", ""))): fail("lock productVersion is not stable SemVer") for component_id in sorted(registry_components): if not TOKEN.fullmatch(component_id): fail(f"invalid component ID: {component_id!r}") definition = registry_components[component_id] locked = lock_components[component_id] if definition.get("repository") != locked.get("repository"): fail(f"repository mismatch for {component_id}") if not GIT_SHA.fullmatch(str(locked.get("revision", ""))): fail(f"invalid source revision for {component_id}") if definition.get("kind") == "plugin" and not TOKEN.fullmatch( str(definition.get("pluginId", "")) ): fail(f"invalid plugin ID for {component_id}") return sorted(registry_components) def load_packages( artifacts: Path, registry: dict[str, Any], lock: dict[str, Any], component_ids: list[str], channel: str, sequence: int, ) -> dict[str, tuple[Path, dict[str, Any]]]: packages: dict[str, tuple[Path, dict[str, Any]]] = {} for manifest_path in sorted(artifacts.glob("*.manifest.json")): manifest = load_object(manifest_path, "component package manifest") component_id = manifest.get("componentId") if component_id not in registry["components"]: fail(f"manifest has unknown componentId: {component_id!r}") if component_id in packages: fail(f"duplicate package manifest for {component_id}") expected_version = channel_version( lock["components"][component_id]["componentVersion"], channel, sequence, ) expected = { "schemaVersion": 1, "componentId": component_id, "packageId": registry["components"][component_id]["packageId"], "kind": registry["components"][component_id]["kind"], "productVersion": manifest.get("productVersion"), "componentVersion": expected_version, "sourceSha": lock["components"][component_id]["revision"], "sourceTreeHash": lock["components"][component_id]["sourceTreeHash"], "abiHash": lock["components"][component_id]["abiHash"], "activation": registry["components"][component_id]["activation"], "dependencies": registry["components"][component_id][ "dependencies" ], "platform": "linux", "architecture": "x86_64", "buildType": "RelWithDebInfo", } for field, value in expected.items(): if manifest.get(field) != value: fail( f"{component_id} manifest {field} does not match the lock" ) archive = manifest_path.with_name( manifest_path.name.removesuffix(".manifest.json") + ".tar.zst" ) packages[component_id] = ( regular_file(archive, f"{component_id} package"), manifest, ) missing = set(component_ids) - set(packages) if missing: fail(f"missing package manifests: {', '.join(sorted(missing))}") return packages def atomic_write(path: Path, content: bytes) -> None: path.parent.mkdir(parents=True, exist_ok=True) descriptor, temporary_name = tempfile.mkstemp( prefix=f".{path.name}.", dir=path.parent ) temporary = Path(temporary_name) try: os.fchmod(descriptor, 0o644) with os.fdopen(descriptor, "wb", closefd=True) as stream: descriptor = -1 stream.write(content) stream.flush() os.fsync(stream.fileno()) os.replace(temporary, path) finally: if descriptor >= 0: os.close(descriptor) temporary.unlink(missing_ok=True) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--registry", type=Path, default=Path("components.json")) parser.add_argument( "--lock", type=Path, default=Path("components.lock.json") ) parser.add_argument("--artifacts", type=Path, required=True) parser.add_argument("--feed-root", type=Path, required=True) parser.add_argument("--base-url", required=True) parser.add_argument("--artifact-base-url", required=True) parser.add_argument("--channel", choices=sorted(CHANNELS), required=True) parser.add_argument("--sequence", type=int, required=True) parser.add_argument("--generated-at") parser.add_argument("--valid-days", type=int, default=45) parser.add_argument("--key-id", required=True) parser.add_argument("--private-key", type=Path, required=True) arguments = parser.parse_args() if not TOKEN.fullmatch(arguments.key_id): fail("invalid key ID") if arguments.sequence < 1 or arguments.sequence > (1 << 63) - 1: fail("--sequence must be between 1 and 2^63-1") if arguments.valid_days < 1 or arguments.valid_days > 365: fail("--valid-days must be between 1 and 365") base_url = validate_https(arguments.base_url, "--base-url") artifact_base_url = validate_https( arguments.artifact_base_url, "--artifact-base-url" ) registry = load_object(arguments.registry, "component registry") lock = load_object(arguments.lock, "component lock") component_ids = validate_metadata(registry, lock) artifacts = arguments.artifacts.resolve(strict=True) packages = load_packages( artifacts, registry, lock, component_ids, arguments.channel, arguments.sequence, ) product_versions = { manifest["productVersion"] for _, manifest in packages.values() } if len(product_versions) != 1: fail("component package manifests disagree on productVersion") product_version = product_versions.pop() if not isinstance(product_version, str) or not SEMVER.fullmatch( product_version ): fail("component package productVersion is not canonical SemVer") generated = parse_time(arguments.generated_at) expires = generated + timedelta(days=arguments.valid_days) generated_at = format_time(generated) expires_at = format_time(expires) feed_root = arguments.feed_root.resolve() signer = Signer(arguments.private_key, arguments.key_id) writes: dict[Path, bytes] = {} catalog_components: list[dict[str, Any]] = [] try: for component_id in component_ids: definition = registry["components"][component_id] locked = lock["components"][component_id] archive, manifest = packages[component_id] version = manifest["componentVersion"] archive_sha = digest(archive) manifest_sha = hashlib.sha256(canonical(manifest)).hexdigest() state_path = ( feed_root / "state" / "components" / f"{component_id}.json" ) state = ( load_object(state_path, "component state") if state_path.exists() else { "schemaVersion": 1, "componentId": component_id, "channels": {}, } ) channels = state.setdefault("channels", {}) old_channel = channels.get(arguments.channel, {}) old_sequence = old_channel.get("sequence", 0) if not isinstance(old_sequence, int) or old_sequence >= arguments.sequence: fail( f"{component_id} {arguments.channel} sequence is not monotonic" ) if arguments.channel == "stable": if ( state.get("lastSourceSha") == locked["revision"] and state.get("artifactHash") not in (None, archive_sha) ): fail( f"{component_id} changed artifact for an unchanged source SHA" ) state.update( { "lastSourceSha": locked["revision"], "semVer": version, "abiSchema": locked["abiHash"], "artifactHash": archive_sha, "sequence": arguments.sequence, } ) channels[arguments.channel] = { "version": version, "artifactHash": archive_sha, "sequence": arguments.sequence, } state_bytes = canonical(state) relative = component_path(registry, component_id) version_path = ( feed_root / "feeds" / arguments.channel / relative / f"{version}.json" ) latest_path = version_path.with_name("latest.json") artifact_name = archive.name artifact = { "name": artifact_name, "url": f"{artifact_base_url}/{quote(artifact_name)}", "sha256": archive_sha, "size": archive.stat().st_size, "manifestSha256": manifest_sha, "packageType": "tar.zst", } payload = { "schemaVersion": 2, "document": "echoion-component-release", "channel": arguments.channel, "sequence": arguments.sequence, "generatedAt": generated_at, "expiresAt": expires_at, "productVersion": product_version, "componentId": component_id, "pluginId": definition.get("pluginId"), "kind": definition["kind"], "componentVersion": version, "sourceSha": locked["revision"], "sourceTreeHash": locked["sourceTreeHash"], "abiHash": locked["abiHash"], "artifactIdentity": manifest["artifactIdentity"], "activation": definition["activation"], "platform": manifest["platform"], "architecture": manifest["architecture"], "buildType": manifest["buildType"], "toolchainContract": manifest["toolchainContract"], "dependencies": definition["dependencies"], "artifact": artifact, } envelope = signer.envelope(payload) if version_path.exists(): existing = signer.verify( version_path.read_bytes(), f"{component_id} version feed" ) immutable_fields = ( "channel", "productVersion", "componentId", "componentVersion", "sourceSha", "sourceTreeHash", "abiHash", "artifactIdentity", "activation", "platform", "architecture", "buildType", "toolchainContract", "dependencies", "artifact", ) if any(existing.get(field) != payload.get(field) for field in immutable_fields): fail(f"immutable version feed conflict: {version_path}") else: writes[version_path] = envelope writes[latest_path] = envelope writes[state_path] = state_bytes relative_url = relative.as_posix() catalog_components.append( { "componentId": component_id, "pluginId": definition.get("pluginId"), "kind": definition["kind"], "componentVersion": version, "activation": definition["activation"], "dependencies": definition["dependencies"], "sequence": arguments.sequence, "latestUrl": ( f"{base_url}/feeds/{arguments.channel}/" f"{relative_url}/latest.json" ), "artifactSha256": archive_sha, } ) catalog_payload = { "schemaVersion": 2, "document": "echoion-component-catalog", "channel": arguments.channel, "sequence": arguments.sequence, "generatedAt": generated_at, "expiresAt": expires_at, "productVersion": product_version, "components": catalog_components, } writes[ feed_root / "feeds" / arguments.channel / "catalog.json" ] = signer.envelope(catalog_payload) for path, content in sorted(writes.items()): atomic_write(path, content) finally: signer.close() print( f"published {len(component_ids)} {arguments.channel} component feeds " f"at sequence {arguments.sequence}" ) if __name__ == "__main__": main()