#!/usr/bin/env python3 """Merge one signed independent component release into an Echoion feed.""" from __future__ import annotations import argparse import hashlib import importlib.util from pathlib import Path import re from types import ModuleType from typing import Any, NoReturn from urllib.parse import quote 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-]+)*)?" r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" ) def fail(message: str) -> NoReturn: raise SystemExit(f"publish-component-release: {message}") def load_feed_helpers() -> ModuleType: path = Path(__file__).with_name("publish-component-feeds.py") specification = importlib.util.spec_from_file_location( "echoion_publish_component_feeds", path ) if specification is None or specification.loader is None: fail(f"cannot load shared feed helpers from {path}") module = importlib.util.module_from_spec(specification) specification.loader.exec_module(module) return module def validate_manifest( helpers: ModuleType, manifest: dict[str, Any], definition: dict[str, Any], component_id: str, ) -> None: expected = { "schemaVersion": 3, "componentId": component_id, "packageId": definition["packageId"], "kind": definition["kind"], "activation": definition["activation"], "dependencies": definition["dependencies"], } for field, value in expected.items(): if manifest.get(field) != value: fail(f"manifest {field} does not match the registry") if not SEMVER.fullmatch(str(manifest.get("componentVersion", ""))): fail("manifest componentVersion is not canonical SemVer") if not GIT_SHA.fullmatch(str(manifest.get("sourceSha", ""))): fail("manifest sourceSha is invalid") if not re.fullmatch( r"(?:git-sha1:[0-9a-f]{40}|sha256:[0-9a-f]{64})", str(manifest.get("sourceTreeHash", "")), ): fail("manifest sourceTreeHash is invalid") abi_hash = manifest.get("abiHash") if abi_hash is not None and not re.fullmatch( r"sha256:[0-9a-f]{64}", str(abi_hash) ): fail("manifest abiHash is invalid") compatibility = manifest.get("productCompatibility") if not isinstance(compatibility, str) or not compatibility: fail("manifest productCompatibility is missing") if not isinstance(manifest.get("buildDependencies"), dict): fail("manifest buildDependencies must be an object") if manifest.get("buildType") != "RelWithDebInfo": fail("manifest buildType must be RelWithDebInfo") for field in ( "artifactIdentity", "platform", "architecture", "toolchainContract", ): if not isinstance(manifest.get(field), str) or not manifest[field]: fail(f"manifest {field} is missing") if manifest["artifactIdentity"] != ( f"{manifest['packageId']}-{manifest['componentVersion']}-" f"{manifest['platform']}-{manifest['architecture']}" ): fail("manifest artifactIdentity is inconsistent") def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--registry", type=Path, default=Path("components.json")) parser.add_argument("--component", required=True) parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--archive", 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=("stable", "beta", "nightly"), 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() helpers = load_feed_helpers() if not helpers.TOKEN.fullmatch(arguments.component): fail("invalid component ID") if not helpers.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 = helpers.validate_https(arguments.base_url, "--base-url") artifact_base_url = helpers.validate_https( arguments.artifact_base_url, "--artifact-base-url" ) registry = helpers.load_object(arguments.registry, "component registry") definitions = registry.get("components") if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict): fail("unsupported component registry schema") definition = definitions.get(arguments.component) if not isinstance(definition, dict): fail(f"component is not registered: {arguments.component}") manifest_path = helpers.regular_file( arguments.manifest, "component package manifest" ) archive = helpers.regular_file(arguments.archive, "component package") manifest = helpers.load_object(manifest_path, "component package manifest") validate_manifest(helpers, manifest, definition, arguments.component) expected_archive = f"{manifest['artifactIdentity']}.tar.zst" if archive.name != expected_archive: fail(f"archive must be named {expected_archive}") version = manifest["componentVersion"] if arguments.channel == "stable" and "-" in version: fail("stable releases must not use a prerelease version") if arguments.channel == "beta" and "-" not in version: fail("beta releases must use a prerelease version") if arguments.channel == "nightly" and "-nightly." not in version: fail("nightly releases must use a -nightly.N version") generated = helpers.parse_time(arguments.generated_at) generated_at = helpers.format_time(generated) expires_at = helpers.format_time( generated + helpers.timedelta(days=arguments.valid_days) ) feed_root = arguments.feed_root.resolve() signer = helpers.Signer(arguments.private_key, arguments.key_id) writes: dict[Path, bytes] = {} try: archive_sha = helpers.digest(archive) manifest_sha = hashlib.sha256(helpers.canonical(manifest)).hexdigest() state_path = ( feed_root / "state" / "components" / f"{arguments.component}.json" ) state = ( helpers.load_object(state_path, "component state") if state_path.exists() else { "schemaVersion": 2, "componentId": arguments.component, "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"{arguments.component} {arguments.channel} sequence " "is not monotonic" ) if arguments.channel == "stable": if ( state.get("lastSourceSha") == manifest["sourceSha"] and state.get("artifactHash") not in (None, archive_sha) ): fail("changed artifact for an unchanged source SHA") state.update( { "lastSourceSha": manifest["sourceSha"], "semVer": version, "abiSchema": manifest["abiHash"], "artifactHash": archive_sha, "sequence": arguments.sequence, } ) channels[arguments.channel] = { "version": version, "artifactHash": archive_sha, "sourceSha": manifest["sourceSha"], "sequence": arguments.sequence, } relative = helpers.component_path(registry, arguments.component) version_path = ( feed_root / "feeds" / arguments.channel / relative / f"{version}.json" ) latest_path = version_path.with_name("latest.json") artifact_url = ( f"{artifact_base_url}/{quote(arguments.component, safe='')}/" f"{quote(version, safe='')}/{quote(archive.name, safe='')}" ) artifact = { "name": archive.name, "url": artifact_url, "sha256": archive_sha, "size": archive.stat().st_size, "manifestSha256": manifest_sha, "packageType": "tar.zst", } payload = { "schemaVersion": 3, "document": "echoion-component-release", "channel": arguments.channel, "sequence": arguments.sequence, "generatedAt": generated_at, "expiresAt": expires_at, "productCompatibility": manifest["productCompatibility"], "componentId": arguments.component, "pluginId": definition.get("pluginId"), "kind": definition["kind"], "componentVersion": version, "sourceSha": manifest["sourceSha"], "sourceTreeHash": manifest["sourceTreeHash"], "abiHash": manifest["abiHash"], "artifactIdentity": manifest["artifactIdentity"], "activation": definition["activation"], "platform": manifest["platform"], "architecture": manifest["architecture"], "toolchainContract": manifest["toolchainContract"], "dependencies": definition["dependencies"], "buildDependencies": manifest["buildDependencies"], "buildType": manifest["buildType"], "artifact": artifact, } envelope = signer.envelope(payload) if version_path.exists(): existing = signer.verify( version_path.read_bytes(), f"{arguments.component} version feed", ) immutable = { key: value for key, value in payload.items() if key not in {"generatedAt", "expiresAt", "sequence"} } if any(existing.get(key) != value for key, value in immutable.items()): fail(f"immutable version feed conflict: {version_path}") else: writes[version_path] = envelope writes[latest_path] = envelope writes[state_path] = helpers.canonical(state) catalog_path = ( feed_root / "feeds" / arguments.channel / "catalog.json" ) old_components: list[dict[str, Any]] = [] if catalog_path.exists(): old_catalog = signer.verify( catalog_path.read_bytes(), f"{arguments.channel} catalog" ) if ( old_catalog.get("document") != "echoion-component-catalog" or old_catalog.get("channel") != arguments.channel ): fail("existing catalog has the wrong document or channel") old_catalog_sequence = old_catalog.get("sequence", 0) if ( not isinstance(old_catalog_sequence, int) or old_catalog_sequence >= arguments.sequence ): fail("catalog sequence is not monotonic") existing_components = old_catalog.get("components") if not isinstance(existing_components, list): fail("existing catalog components must be an array") old_components = [ item for item in existing_components if isinstance(item, dict) and item.get("componentId") != arguments.component ] relative_url = relative.as_posix() old_components.append( { "componentId": arguments.component, "pluginId": definition.get("pluginId"), "kind": definition["kind"], "componentVersion": version, "productCompatibility": manifest["productCompatibility"], "activation": definition["activation"], "dependencies": definition["dependencies"], "sequence": arguments.sequence, "latestUrl": ( f"{base_url}/feeds/{arguments.channel}/" f"{relative_url}/latest.json" ), "artifactSha256": archive_sha, } ) old_components.sort(key=lambda item: str(item.get("componentId", ""))) catalog = { "schemaVersion": 3, "document": "echoion-component-catalog", "channel": arguments.channel, "sequence": arguments.sequence, "generatedAt": generated_at, "expiresAt": expires_at, "components": old_components, } writes[catalog_path] = signer.envelope(catalog) for path, content in sorted(writes.items()): helpers.atomic_write(path, content) finally: signer.close() print( f"published {arguments.component} {arguments.channel} " f"at sequence {arguments.sequence}" ) if __name__ == "__main__": main()