Files
Echoion/scripts/aggregate_update_feed.py
T
faumaray f78004e822
Container CI / release-build (push) Successful in 16m22s
Nightly release / publish-nightly (push) Successful in 16m6s
Release: use independent component repositories
2026-07-28 21:24:30 +03:00

497 lines
18 KiB
Python
Executable File

#!/usr/bin/env python3
"""Merge, validate, and Ed25519-sign Echoion's aggregate release feed."""
from __future__ import annotations
import argparse
import base64
import binascii
from datetime import datetime, timedelta, timezone
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 urlsplit
SAFE_TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$")
SHA256 = re.compile(r"^[0-9a-f]{64}$")
TIMESTAMP = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$")
SEMVER = re.compile(
r"^(0|[1-9][0-9]*)\."
r"(0|[1-9][0-9]*)\."
r"(0|[1-9][0-9]*)"
r"(?:-((?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)"
r"(?:\.(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?"
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
)
MAX_FEED_BYTES = 8 * 1024 * 1024
CHANNELS = {"stable", "beta", "nightly"}
def fail(message: str) -> NoReturn:
raise SystemExit(f"aggregate-update-feed: {message}")
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")
if metadata.st_size > MAX_FEED_BYTES:
fail(f"{label} is too large")
return path.resolve(strict=True)
def parse_timestamp(value: str, label: str) -> datetime:
if not isinstance(value, str) or not TIMESTAMP.fullmatch(value):
fail(f"{label} must use UTC YYYY-MM-DDTHH:MM:SSZ format")
try:
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=timezone.utc
)
except ValueError as error:
fail(f"invalid {label}: {error}")
def format_timestamp(value: datetime) -> str:
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def urlsafe_decode(value: Any, label: str) -> bytes:
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", value):
fail(f"{label} is not unpadded base64url")
try:
return base64.b64decode(
value + "=" * (-len(value) % 4), altchars=b"-_", validate=True
)
except (ValueError, binascii.Error) as error:
fail(f"cannot decode {label}: {error}")
def urlsafe_encode(value: bytes) -> str:
return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")
def load_json_bytes(value: bytes, label: str) -> dict[str, Any]:
try:
document = json.loads(value)
except (UnicodeDecodeError, json.JSONDecodeError) as error:
fail(f"cannot parse {label}: {error}")
if not isinstance(document, dict):
fail(f"{label} must be a JSON object")
return document
def run_openssl(command: list[str], action: str) -> None:
try:
completed = subprocess.run(
command,
check=False,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFoundError:
fail("openssl is required to sign and verify update feeds")
if completed.returncode != 0:
detail = completed.stderr.decode("utf-8", errors="replace").strip()
fail(f"OpenSSL could not {action}: {detail}")
def verify_signature(
payload: bytes,
signature: bytes,
public_key: Path,
action: str,
) -> None:
if len(signature) != 64:
fail("feed signature is not an Ed25519 signature")
with tempfile.TemporaryDirectory(prefix="echoion-feed-verify.") as directory:
payload_path = Path(directory, "payload.json")
signature_path = Path(directory, "signature.bin")
payload_path.write_bytes(payload)
signature_path.write_bytes(signature)
run_openssl(
[
"openssl",
"pkeyutl",
"-verify",
"-rawin",
"-pubin",
"-inkey",
os.fspath(public_key),
"-in",
os.fspath(payload_path),
"-sigfile",
os.fspath(signature_path),
],
action,
)
def verify_envelope(
path: Path,
trusted_keys: dict[str, Path],
) -> tuple[dict[str, Any], bytes, bytes]:
envelope_bytes = path.read_bytes()
envelope = load_json_bytes(envelope_bytes, "existing feed envelope")
if envelope.get("schemaVersion") != 1:
fail("existing feed envelope has the wrong schema")
key_id = envelope.get("keyId")
if not isinstance(key_id, str) or not SAFE_TOKEN.fullmatch(key_id):
fail("existing feed envelope has an invalid key id")
public_key = trusted_keys.get(key_id)
if public_key is None:
fail(f"existing feed envelope uses an untrusted key id: {key_id}")
payload = urlsafe_decode(envelope.get("payload"), "existing feed payload")
signature = urlsafe_decode(envelope.get("signature"), "existing feed signature")
verify_signature(payload, signature, public_key, "verify the existing feed")
return load_json_bytes(payload, "existing feed payload"), payload, envelope_bytes
def sign_payload(payload: bytes, private_key: Path) -> bytes:
with tempfile.TemporaryDirectory(prefix="echoion-feed-sign.") as directory:
payload_path = Path(directory, "payload.json")
signature_path = Path(directory, "signature.bin")
payload_path.write_bytes(payload)
run_openssl(
[
"openssl",
"pkeyutl",
"-sign",
"-rawin",
"-inkey",
os.fspath(private_key),
"-in",
os.fspath(payload_path),
"-out",
os.fspath(signature_path),
],
"sign the aggregate feed",
)
signature = signature_path.read_bytes()
if len(signature) != 64:
fail("OpenSSL returned an invalid Ed25519 signature")
return signature
def validate_release(release: Any) -> dict[str, Any]:
if not isinstance(release, dict):
fail("feed releases must be JSON objects")
for field in ("component", "channel", "cohort", "platform", "arch"):
if not isinstance(release.get(field), str) or not SAFE_TOKEN.fullmatch(
release[field]
):
fail(f"release has an invalid {field}")
version = release.get("version")
if not isinstance(version, str) or not SEMVER.fullmatch(version):
fail("release has an invalid Semantic Versioning version")
artifact_id = release.get("artifactId")
if not isinstance(artifact_id, str) or (
artifact_id and not SAFE_TOKEN.fullmatch(artifact_id)
):
fail("release has an invalid artifactId")
if release["channel"] not in CHANNELS:
fail(f"unsupported release channel: {release['channel']!r}")
url = release.get("url")
parsed_url = urlsplit(url) if isinstance(url, str) else None
if (
parsed_url is None
or parsed_url.scheme != "https"
or not parsed_url.hostname
or parsed_url.username
or parsed_url.password
or parsed_url.fragment
):
fail("release artifact URLs must be credential-free HTTPS URLs")
if not isinstance(release.get("size"), int) or release["size"] < 0:
fail("release has an invalid artifact size")
if not isinstance(release.get("sha256"), str) or not SHA256.fullmatch(
release["sha256"]
):
fail("release has an invalid sha256")
package_type = release.get("packageType")
if not isinstance(package_type, str) or not SAFE_TOKEN.fullmatch(package_type):
fail("release has an invalid packageType")
if not isinstance(release.get("compatibility"), dict):
fail("release has no compatibility object")
manifest_hash = release.get("releaseManifestSha256")
if manifest_hash is not None and (
not isinstance(manifest_hash, str) or not SHA256.fullmatch(manifest_hash)
):
fail("release has an invalid releaseManifestSha256")
return release
def validate_payload(document: dict[str, Any], label: str) -> list[dict[str, Any]]:
if document.get("schemaVersion") != 1:
fail(f"{label} has an unsupported schema")
feed_id = document.get("feedId")
if not isinstance(feed_id, str) or not SAFE_TOKEN.fullmatch(feed_id):
fail(f"{label} has an invalid feed id")
sequence = document.get("sequence")
if not isinstance(sequence, int) or sequence < 0 or sequence > (1 << 64) - 1:
fail(f"{label} has an invalid sequence")
generated = parse_timestamp(document.get("generatedAt"), f"{label} generatedAt")
expires = parse_timestamp(document.get("expiresAt"), f"{label} expiresAt")
if expires <= generated:
fail(f"{label} expiry does not follow its generated timestamp")
releases = document.get("releases")
if not isinstance(releases, list) or not releases:
fail(f"{label} must contain at least one release")
return [validate_release(release) for release in releases]
def release_identity(release: dict[str, Any]) -> tuple[str, ...]:
return tuple(
str(release.get(field, ""))
for field in (
"component",
"artifactId",
"channel",
"version",
"cohort",
"platform",
"arch",
)
)
def merge_releases(
new: list[dict[str, Any]],
existing: list[dict[str, Any]],
nightly_retention: int,
) -> list[dict[str, Any]]:
merged: list[dict[str, Any]] = []
identities: dict[tuple[str, ...], dict[str, Any]] = {}
for release in [*new, *existing]:
identity = release_identity(release)
if identity in identities:
previous = identities[identity]
if previous != release:
fail(
"an immutable release identity has different metadata: "
+ "/".join(identity)
)
continue
identities[identity] = release
merged.append(release)
nightly_versions: list[str] = []
for release in merged:
if release["channel"] == "nightly" and release["version"] not in nightly_versions:
nightly_versions.append(release["version"])
retained_versions = set(nightly_versions[:nightly_retention])
return [
release
for release in merged
if release["channel"] != "nightly" or release["version"] in retained_versions
]
def atomic_write(path: Path, content: bytes, mode: int = 0o644) -> 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, mode)
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(
"--new-payload", type=Path, action="append", required=True
)
parser.add_argument("--existing-envelope", type=Path)
parser.add_argument("--public-key", type=Path, required=True)
parser.add_argument("--private-key", type=Path, required=True)
parser.add_argument("--key-id", default="echoion-release-2026-07")
parser.add_argument(
"--trusted-existing-key",
action="append",
default=[],
metavar="KEY_ID=PUBLIC_KEY",
help="additional key allowed only for verifying an existing envelope",
)
parser.add_argument("--valid-days", type=int, default=45)
parser.add_argument("--nightly-retention", type=int, default=14)
parser.add_argument("--generated-at")
parser.add_argument("--sequence", type=int)
parser.add_argument("--output-payload", type=Path, required=True)
parser.add_argument("--output-envelope", type=Path, required=True)
arguments = parser.parse_args()
if not SAFE_TOKEN.fullmatch(arguments.key_id):
fail("the signing key id is invalid")
if arguments.valid_days < 1 or arguments.valid_days > 365:
fail("--valid-days must be between 1 and 365")
if arguments.nightly_retention < 1:
fail("--nightly-retention must be positive")
new_payload_paths = [
regular_file(path, "new payload") for path in arguments.new_payload
]
public_key = regular_file(arguments.public_key, "Ed25519 public key")
private_key = regular_file(
arguments.private_key, "Ed25519 private key", private=True
)
trusted_existing_keys = {arguments.key_id: public_key}
for value in arguments.trusted_existing_key:
key_id, separator, path_value = value.partition("=")
if (
not separator
or not SAFE_TOKEN.fullmatch(key_id)
or not path_value
):
fail(f"invalid --trusted-existing-key value: {value!r}")
key_path = regular_file(
Path(path_value),
f"trusted existing Ed25519 public key {key_id}",
)
previous = trusted_existing_keys.get(key_id)
if previous is not None and previous != key_path:
fail(f"conflicting public keys for key id: {key_id}")
trusted_existing_keys[key_id] = key_path
new_documents = [
load_json_bytes(path.read_bytes(), "new feed payload")
for path in new_payload_paths
]
new_document = new_documents[0]
new_releases: list[dict[str, Any]] = []
for document in new_documents:
releases = validate_payload(document, "new feed payload")
if document["feedId"] != new_document["feedId"]:
fail("new feed identifiers differ")
new_releases.extend(releases)
existing_document: dict[str, Any] | None = None
existing_payload_bytes = b""
existing_envelope_bytes = b""
existing_releases: list[dict[str, Any]] = []
if arguments.existing_envelope:
existing_path = regular_file(arguments.existing_envelope, "existing envelope")
(
existing_document,
existing_payload_bytes,
existing_envelope_bytes,
) = verify_envelope(existing_path, trusted_existing_keys)
existing_releases = validate_payload(existing_document, "existing feed payload")
if existing_document["feedId"] != new_document["feedId"]:
fail("existing and new feed identifiers differ")
output_payload = arguments.output_payload.resolve()
output_envelope = arguments.output_envelope.resolve()
inputs = {
*new_payload_paths,
private_key,
*trusted_existing_keys.values(),
}
if arguments.existing_envelope:
inputs.add(arguments.existing_envelope.resolve())
if output_payload in inputs or output_envelope in inputs or output_payload == output_envelope:
fail("an output path would overwrite an input or the other output")
if existing_document is not None:
existing_by_identity = {
release_identity(release): release for release in existing_releases
}
already_present = all(
existing_by_identity.get(release_identity(release)) == release
for release in new_releases
)
retained_existing = merge_releases(
[], existing_releases, arguments.nightly_retention
)
if already_present and retained_existing == existing_releases:
atomic_write(output_payload, existing_payload_bytes)
atomic_write(output_envelope, existing_envelope_bytes)
print("aggregate feed already contains this immutable release")
return
generated = (
parse_timestamp(arguments.generated_at, "generated timestamp")
if arguments.generated_at
else datetime.now(timezone.utc).replace(microsecond=0)
)
generated = max(
generated,
max(
parse_timestamp(document["generatedAt"], "new feed generatedAt")
for document in new_documents
),
)
if existing_document is not None:
generated = max(
generated,
parse_timestamp(
existing_document["generatedAt"], "existing feed generatedAt"
),
)
minimum_sequence = max(
int(document["sequence"]) for document in new_documents
)
if existing_document is not None:
minimum_sequence = max(minimum_sequence, int(existing_document["sequence"]) + 1)
sequence = arguments.sequence
if sequence is None:
sequence = max(int(generated.timestamp()), minimum_sequence)
if sequence < minimum_sequence or sequence > (1 << 64) - 1:
fail("aggregate feed sequence is not monotonic or exceeds uint64")
releases = merge_releases(
new_releases, existing_releases, arguments.nightly_retention
)
payload_document = {
"schemaVersion": 1,
"feedId": new_document["feedId"],
"sequence": sequence,
"generatedAt": format_timestamp(generated),
"expiresAt": format_timestamp(generated + timedelta(days=arguments.valid_days)),
"releases": releases,
}
payload = (
json.dumps(payload_document, ensure_ascii=False, indent=2).encode("utf-8")
+ b"\n"
)
signature = sign_payload(payload, private_key)
verify_signature(payload, signature, public_key, "verify the newly signed feed")
envelope = {
"schemaVersion": 1,
"keyId": arguments.key_id,
"payload": urlsafe_encode(payload),
"signature": urlsafe_encode(signature),
}
atomic_write(output_payload, payload)
atomic_write(
output_envelope,
json.dumps(envelope, ensure_ascii=False, indent=2).encode("utf-8") + b"\n",
)
print(
f"signed {len(releases)} releases at sequence {sequence}; "
f"nightlies retained={arguments.nightly_retention}"
)
if __name__ == "__main__":
main()