Release: cut over Echoion 2.0 components
Modular container CI / release-build (push) Has been cancelled
Modular container CI / release-build (push) Has been cancelled
This commit is contained in:
169 files changed
+3069
-32261
No files matched your search
@@ -1,496 +0,0 @@
|
||||
#!/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()
|
||||
Executable
+82
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if (($# < 1 || $# > 2)); then
|
||||
echo "usage: $0 COMPONENT_WORKSPACE [DEPENDENCY_WORKSPACE]" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ -z ${ECHOION_COMPONENT_SSH_KEY:-} ]]; then
|
||||
echo "ECHOION_COMPONENT_SSH_KEY is required" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
|
||||
workspace=$(realpath -m -- "$1")
|
||||
dependency_workspace=
|
||||
if (($# == 2)); then
|
||||
dependency_workspace=$(realpath -m -- "$2")
|
||||
fi
|
||||
credential_dir=$(mktemp -d)
|
||||
cleanup() {
|
||||
rm -f -- "$credential_dir/key" "$credential_dir/known_hosts"
|
||||
rmdir -- "$credential_dir"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
umask 077
|
||||
printf '%s\n' "$ECHOION_COMPONENT_SSH_KEY" >"$credential_dir/key"
|
||||
printf '%s\n' \
|
||||
'git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==' \
|
||||
>"$credential_dir/known_hosts"
|
||||
export GIT_SSH_COMMAND="ssh -i $credential_dir/key -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$credential_dir/known_hosts"
|
||||
python3 "$script_dir/sync-components.py" \
|
||||
--workspace "$workspace" \
|
||||
--update
|
||||
|
||||
if [[ -n $dependency_workspace ]]; then
|
||||
mkdir -p "$dependency_workspace"
|
||||
while IFS=$'\t' read -r dependency repository revision; do
|
||||
destination="$dependency_workspace/$dependency"
|
||||
if [[ -e $destination && ! -d $destination/.git ]]; then
|
||||
echo "dependency destination is not a Git repository: $destination" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! -d $destination/.git ]]; then
|
||||
git clone --filter=blob:none --no-checkout \
|
||||
"$repository" "$destination"
|
||||
fi
|
||||
git -C "$destination" remote set-url origin "$repository"
|
||||
git -C "$destination" fetch --prune origin main
|
||||
git -C "$destination" cat-file -e "$revision^{commit}"
|
||||
git -C "$destination" checkout --detach "$revision"
|
||||
git -C "$destination" diff --quiet
|
||||
git -C "$destination" diff --cached --quiet
|
||||
test "$(git -C "$destination" rev-parse HEAD)" = "$revision"
|
||||
done < <(
|
||||
python3 - "$script_dir/../cmake/DependencyLock.cmake" <<'PY'
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
text = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")
|
||||
repositories = {
|
||||
"VoidLibrary": (
|
||||
"ssh://gitea@git.faumaray.ru/void/voidlibrary.git",
|
||||
"ECHOION_VOID_REVISION",
|
||||
),
|
||||
"VoidTeamspeak": (
|
||||
"ssh://gitea@git.faumaray.ru/void/voidteamspeak.git",
|
||||
"ECHOION_VOID_TEAMSPEAK_REVISION",
|
||||
),
|
||||
}
|
||||
for name, (repository, variable) in repositories.items():
|
||||
match = re.search(
|
||||
rf'set\({variable}\s+"([0-9a-f]{{40}})"',
|
||||
text,
|
||||
re.MULTILINE,
|
||||
)
|
||||
if match is None:
|
||||
raise SystemExit(f"missing exact {variable} in dependency lock")
|
||||
print(name, repository, match.group(1), sep="\t")
|
||||
PY
|
||||
)
|
||||
fi
|
||||
@@ -254,7 +254,7 @@ def repository_path(owner: str, repo: str) -> str:
|
||||
|
||||
def load_artifacts(directory: Path) -> dict[str, Path]:
|
||||
try:
|
||||
entries = list(directory.iterdir())
|
||||
entries = [entry for entry in directory.rglob("*") if entry.is_file()]
|
||||
except OSError as error:
|
||||
fail(f"cannot enumerate artifact directory {directory}: {error}")
|
||||
artifacts: dict[str, Path] = {}
|
||||
|
||||
Executable
+282
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create deterministic independent Echoion component tar.zst packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
from typing import Any, NoReturn
|
||||
|
||||
|
||||
CHANNELS = {"stable", "beta", "nightly"}
|
||||
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-]+)*)?$"
|
||||
)
|
||||
|
||||
|
||||
def fail(message: str) -> NoReturn:
|
||||
raise SystemExit(f"package-components: {message}")
|
||||
|
||||
|
||||
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")
|
||||
return document
|
||||
|
||||
|
||||
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 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 component_version(stable: str, channel: str, sequence: int) -> str:
|
||||
if not SEMVER.fullmatch(stable):
|
||||
fail(f"locked component version is not stable SemVer: {stable!r}")
|
||||
if channel == "stable":
|
||||
return stable
|
||||
return f"{stable}-{channel}.{sequence}"
|
||||
|
||||
|
||||
def validate_tree(root: Path) -> list[dict[str, Any]]:
|
||||
files: list[dict[str, Any]] = []
|
||||
if root.is_symlink() or not root.is_dir():
|
||||
fail(f"component staging root is not a directory: {root}")
|
||||
for path in sorted(root.rglob("*")):
|
||||
relative = path.relative_to(root)
|
||||
pure = PurePosixPath(relative.as_posix())
|
||||
if pure.is_absolute() or ".." in pure.parts:
|
||||
fail(f"unsafe package path: {relative}")
|
||||
metadata = path.lstat()
|
||||
if stat.S_ISDIR(metadata.st_mode):
|
||||
if path.is_symlink():
|
||||
fail(f"directory symlink is forbidden: {relative}")
|
||||
continue
|
||||
if stat.S_ISLNK(metadata.st_mode):
|
||||
target = os.readlink(path)
|
||||
target_path = PurePosixPath(target)
|
||||
if not target or target_path.is_absolute() or ".." in target_path.parts:
|
||||
fail(f"unsafe package symlink: {relative} -> {target}")
|
||||
try:
|
||||
path.resolve(strict=True).relative_to(root.resolve(strict=True))
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
fail(f"package symlink escapes or is dangling: {relative}")
|
||||
files.append(
|
||||
{
|
||||
"path": relative.as_posix(),
|
||||
"type": "symlink",
|
||||
"target": target,
|
||||
}
|
||||
)
|
||||
continue
|
||||
if not stat.S_ISREG(metadata.st_mode):
|
||||
fail(f"non-regular package entry: {relative}")
|
||||
files.append(
|
||||
{
|
||||
"path": relative.as_posix(),
|
||||
"type": "file",
|
||||
"size": metadata.st_size,
|
||||
"sha256": digest(path),
|
||||
"mode": stat.S_IMODE(metadata.st_mode),
|
||||
}
|
||||
)
|
||||
if not files:
|
||||
fail(f"component staging tree is empty: {root}")
|
||||
return files
|
||||
|
||||
|
||||
def is_elf(path: Path) -> bool:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
return False
|
||||
with path.open("rb") as stream:
|
||||
return stream.read(4) == b"\x7fELF"
|
||||
|
||||
|
||||
def private_libraries(root: Path) -> list[str]:
|
||||
return sorted(
|
||||
path.relative_to(root).as_posix()
|
||||
for path in root.rglob("*")
|
||||
if path.parent.name == "lib" and is_elf(path)
|
||||
)
|
||||
|
||||
|
||||
def create_archive(source: Path, destination: Path, epoch: int) -> None:
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = destination.with_name(f".{destination.name}.tmp")
|
||||
temporary.unlink(missing_ok=True)
|
||||
tar = subprocess.Popen(
|
||||
[
|
||||
"tar",
|
||||
"--sort=name",
|
||||
"--format=gnu",
|
||||
f"--mtime=@{epoch}",
|
||||
"--owner=0",
|
||||
"--group=0",
|
||||
"--numeric-owner",
|
||||
"-C",
|
||||
os.fspath(source),
|
||||
"-cf",
|
||||
"-",
|
||||
".",
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
assert tar.stdout is not None
|
||||
compressed = subprocess.run(
|
||||
["zstd", "-19", "--threads=1", "-q", "-o", os.fspath(temporary)],
|
||||
stdin=tar.stdout,
|
||||
check=False,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
tar.stdout.close()
|
||||
tar_stderr = tar.stderr.read() if tar.stderr else b""
|
||||
tar_result = tar.wait()
|
||||
if tar_result != 0 or compressed.returncode != 0:
|
||||
temporary.unlink(missing_ok=True)
|
||||
detail = (
|
||||
tar_stderr + b"\n" + compressed.stderr
|
||||
).decode("utf-8", errors="replace").strip()
|
||||
fail(f"cannot create {destination.name}: {detail}")
|
||||
os.replace(temporary, destination)
|
||||
|
||||
|
||||
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("--staging-root", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--channel", choices=sorted(CHANNELS), default="stable")
|
||||
parser.add_argument("--sequence", type=int, required=True)
|
||||
parser.add_argument("--product-version", required=True)
|
||||
parser.add_argument(
|
||||
"--toolchain-contract",
|
||||
default="linux-x86_64-glibc-2.35-cxx26",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
if arguments.sequence < 1:
|
||||
fail("--sequence must be positive")
|
||||
product_match = SEMVER.fullmatch(arguments.product_version)
|
||||
if product_match is None:
|
||||
fail("--product-version must be canonical SemVer")
|
||||
|
||||
registry = load_object(arguments.registry, "component registry")
|
||||
lock = load_object(arguments.lock, "component lock")
|
||||
if registry.get("schemaVersion") != 1 or lock.get("schemaVersion") != 2:
|
||||
fail("unsupported component registry or lock schema")
|
||||
definitions = registry.get("components")
|
||||
locked_components = lock.get("components")
|
||||
if (
|
||||
not isinstance(definitions, dict)
|
||||
or not isinstance(locked_components, dict)
|
||||
or set(definitions) != set(locked_components)
|
||||
):
|
||||
fail("component registry and lock do not match")
|
||||
locked_product_match = SEMVER.fullmatch(str(lock.get("productVersion", "")))
|
||||
if locked_product_match is None or "-" in str(lock["productVersion"]):
|
||||
fail("locked productVersion must be stable SemVer")
|
||||
locked_tuple = tuple(int(value) for value in locked_product_match.groups()[:3])
|
||||
product_tuple = tuple(int(value) for value in product_match.groups()[:3])
|
||||
if arguments.channel == "stable":
|
||||
if arguments.product_version != lock["productVersion"]:
|
||||
fail("stable product version does not match the lock")
|
||||
elif (
|
||||
product_tuple[:2] != locked_tuple[:2]
|
||||
or product_tuple[2] not in (locked_tuple[2], locked_tuple[2] + 1)
|
||||
):
|
||||
fail("prerelease product version is not the locked or next patch line")
|
||||
staging_root = arguments.staging_root.resolve(strict=True)
|
||||
output = arguments.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
epoch_value = os.environ.get("SOURCE_DATE_EPOCH", "0")
|
||||
if not epoch_value.isdigit():
|
||||
fail("SOURCE_DATE_EPOCH must be a non-negative integer")
|
||||
epoch = int(epoch_value)
|
||||
|
||||
with tempfile.TemporaryDirectory(
|
||||
prefix=".component-packages.", dir=output
|
||||
) as temporary:
|
||||
work_root = Path(temporary)
|
||||
for component_id in sorted(definitions):
|
||||
definition = definitions[component_id]
|
||||
locked = locked_components[component_id]
|
||||
package_id = definition["packageId"]
|
||||
source = staging_root / package_id
|
||||
version = component_version(
|
||||
locked["componentVersion"],
|
||||
arguments.channel,
|
||||
arguments.sequence,
|
||||
)
|
||||
artifact_identity = (
|
||||
f"{package_id}-{version}-linux-x86_64"
|
||||
)
|
||||
if (
|
||||
arguments.channel == "stable"
|
||||
and artifact_identity != locked["artifactIdentity"]
|
||||
):
|
||||
fail(f"artifact identity mismatch for {component_id}")
|
||||
package_root = work_root / artifact_identity
|
||||
shutil.copytree(source, package_root, symlinks=True)
|
||||
files = validate_tree(package_root)
|
||||
manifest = {
|
||||
"schemaVersion": 1,
|
||||
"componentId": component_id,
|
||||
"packageId": package_id,
|
||||
"kind": definition["kind"],
|
||||
"productVersion": arguments.product_version,
|
||||
"componentVersion": version,
|
||||
"sourceSha": locked["revision"],
|
||||
"sourceTreeHash": locked["sourceTreeHash"],
|
||||
"abiHash": locked["abiHash"],
|
||||
"activation": definition["activation"],
|
||||
"dependencies": definition["dependencies"],
|
||||
"platform": "linux",
|
||||
"architecture": "x86_64",
|
||||
"toolchainContract": arguments.toolchain_contract,
|
||||
"artifactIdentity": artifact_identity,
|
||||
"privateLibraries": private_libraries(package_root),
|
||||
"files": files,
|
||||
}
|
||||
manifest_bytes = canonical(manifest)
|
||||
(package_root / "manifest.json").write_bytes(manifest_bytes)
|
||||
archive = output / f"{artifact_identity}.tar.zst"
|
||||
create_archive(package_root, archive, epoch)
|
||||
(output / f"{artifact_identity}.manifest.json").write_bytes(
|
||||
manifest_bytes
|
||||
)
|
||||
print(f"packaged {component_id}: {archive.name}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
root_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)"
|
||||
exec python3 "${root_dir}/scripts/prepare_release.py" "$@"
|
||||
Executable
+319
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve component main branches and write the canonical release lock."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
SEMVER_RE = re.compile(
|
||||
r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$"
|
||||
)
|
||||
PROJECT_RE = re.compile(
|
||||
r"\bproject\s*\(\s*Echoion\s+VERSION\s+"
|
||||
r"([0-9]+\.[0-9]+\.[0-9]+)\b",
|
||||
re.IGNORECASE | re.MULTILINE,
|
||||
)
|
||||
|
||||
|
||||
class ReleaseError(RuntimeError):
|
||||
"""Release preparation validation failed."""
|
||||
|
||||
|
||||
def command(*args: str, cwd: Path | None = None) -> str:
|
||||
try:
|
||||
return subprocess.check_output(
|
||||
args,
|
||||
cwd=cwd,
|
||||
text=True,
|
||||
stderr=subprocess.STDOUT,
|
||||
).strip()
|
||||
except (OSError, subprocess.CalledProcessError) as error:
|
||||
detail = getattr(error, "output", "") or str(error)
|
||||
raise ReleaseError(
|
||||
f"command failed: {' '.join(args)}: {detail.strip()}"
|
||||
) from error
|
||||
|
||||
|
||||
def root_product_version(cmake_text: str) -> str:
|
||||
matches = PROJECT_RE.findall(cmake_text)
|
||||
if len(matches) != 1:
|
||||
raise ReleaseError(
|
||||
"root CMakeLists.txt must contain exactly one "
|
||||
"project(Echoion VERSION x.y.z)"
|
||||
)
|
||||
version = matches[0]
|
||||
if not SEMVER_RE.fullmatch(version):
|
||||
raise ReleaseError(f"root product version is not stable SemVer: {version}")
|
||||
return version
|
||||
|
||||
|
||||
def canonical_json(value: Any) -> bytes:
|
||||
return (
|
||||
json.dumps(
|
||||
value,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
)
|
||||
+ "\n"
|
||||
).encode()
|
||||
|
||||
|
||||
def contract_hash(value: Any) -> str:
|
||||
return "sha256:" + hashlib.sha256(canonical_json(value)).hexdigest()
|
||||
|
||||
|
||||
def compatible_append(old: Any, new: Any) -> bool:
|
||||
if isinstance(old, dict) and isinstance(new, dict):
|
||||
return all(
|
||||
key in new and compatible_append(value, new[key])
|
||||
for key, value in old.items()
|
||||
)
|
||||
if isinstance(old, list) and isinstance(new, list):
|
||||
return len(new) >= len(old) and all(
|
||||
compatible_append(value, new[index])
|
||||
for index, value in enumerate(old)
|
||||
)
|
||||
return type(old) is type(new) and old == new
|
||||
|
||||
|
||||
def classify_contract(old: Any, new: Any) -> str:
|
||||
if canonical_json(old) == canonical_json(new):
|
||||
return "identical"
|
||||
if compatible_append(old, new):
|
||||
return "compatible"
|
||||
return "breaking"
|
||||
|
||||
|
||||
def bump_version(version: str, change: str) -> str:
|
||||
match = SEMVER_RE.fullmatch(version)
|
||||
if not match:
|
||||
raise ReleaseError(f"invalid prior component version: {version}")
|
||||
major, minor, patch = map(int, match.groups())
|
||||
if change == "breaking":
|
||||
return f"{major + 1}.0.0"
|
||||
if change == "compatible":
|
||||
return f"{major}.{minor + 1}.0"
|
||||
if change == "implementation":
|
||||
return f"{major}.{minor}.{patch + 1}"
|
||||
raise ReleaseError(f"unsupported version change: {change}")
|
||||
|
||||
|
||||
def read_contract(repo: Path, revision: str, relative_path: str) -> Any:
|
||||
raw = command("git", "show", f"{revision}:{relative_path}", cwd=repo)
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as error:
|
||||
raise ReleaseError(
|
||||
f"{repo.name}:{relative_path} is not valid JSON at {revision}"
|
||||
) from error
|
||||
|
||||
|
||||
def derive_component_version(
|
||||
previous: dict[str, Any] | None,
|
||||
revision: str,
|
||||
current_contract: Any | None,
|
||||
previous_contract: Any | None,
|
||||
) -> str:
|
||||
if previous is None:
|
||||
return "2.0.0"
|
||||
previous_version = previous["componentVersion"]
|
||||
if previous["revision"] == revision:
|
||||
return previous_version
|
||||
if current_contract is None:
|
||||
return bump_version(previous_version, "implementation")
|
||||
classification = classify_contract(previous_contract, current_contract)
|
||||
if classification == "identical":
|
||||
classification = "implementation"
|
||||
return bump_version(previous_version, classification)
|
||||
|
||||
|
||||
def normalize_remote(url: str) -> str:
|
||||
return url.removesuffix("/").removesuffix(".git").lower()
|
||||
|
||||
|
||||
def resolve_component(
|
||||
component_id: str,
|
||||
definition: dict[str, Any],
|
||||
previous: dict[str, Any] | None,
|
||||
workspace: Path,
|
||||
product_version: str,
|
||||
initial_modular_release: bool,
|
||||
) -> dict[str, Any]:
|
||||
repository = definition["repository"]
|
||||
url = definition["url"]
|
||||
branch = definition.get("branch", "main")
|
||||
repo = workspace / component_id
|
||||
if not (repo / ".git").is_dir():
|
||||
raise ReleaseError(
|
||||
f"component repository is missing: {repo}; "
|
||||
"run scripts/sync-components.py first"
|
||||
)
|
||||
if command("git", "status", "--porcelain", cwd=repo):
|
||||
raise ReleaseError(f"refusing dirty component repository: {repo}")
|
||||
origin = command("git", "remote", "get-url", "origin", cwd=repo)
|
||||
if normalize_remote(origin) != normalize_remote(url):
|
||||
raise ReleaseError(
|
||||
f"{component_id} origin mismatch: expected {url}, found {origin}"
|
||||
)
|
||||
|
||||
remote_line = command("git", "ls-remote", url, f"refs/heads/{branch}")
|
||||
fields = remote_line.split()
|
||||
if len(fields) != 2:
|
||||
raise ReleaseError(
|
||||
f"{component_id} has no accessible {branch} branch at {url}"
|
||||
)
|
||||
revision = fields[0]
|
||||
command("git", "fetch", "--quiet", "origin", branch, cwd=repo)
|
||||
command("git", "cat-file", "-e", f"{revision}^{{commit}}", cwd=repo)
|
||||
|
||||
head = command("git", "rev-parse", "HEAD", cwd=repo)
|
||||
if head != revision:
|
||||
merge_base = command("git", "merge-base", "HEAD", revision, cwd=repo)
|
||||
relation = "behind" if merge_base == head else "non-fast-forward"
|
||||
raise ReleaseError(
|
||||
f"{component_id} local HEAD is {relation}; "
|
||||
f"expected current {branch} {revision}, found {head}"
|
||||
)
|
||||
|
||||
tree = command("git", "rev-parse", f"{revision}^{{tree}}", cwd=repo)
|
||||
contract_path = definition.get("abiContract")
|
||||
current_contract = (
|
||||
read_contract(repo, revision, contract_path)
|
||||
if contract_path is not None
|
||||
else None
|
||||
)
|
||||
previous_contract = None
|
||||
if (
|
||||
current_contract is not None
|
||||
and previous is not None
|
||||
and previous.get("revision")
|
||||
):
|
||||
try:
|
||||
previous_contract = read_contract(
|
||||
repo, previous["revision"], contract_path
|
||||
)
|
||||
except ReleaseError:
|
||||
previous_contract = {}
|
||||
|
||||
version = (
|
||||
"2.0.0"
|
||||
if initial_modular_release
|
||||
else derive_component_version(
|
||||
previous,
|
||||
revision,
|
||||
current_contract,
|
||||
previous_contract,
|
||||
)
|
||||
)
|
||||
expected_tag = f"v{version}"
|
||||
tag_line = command("git", "ls-remote", "--tags", url, expected_tag)
|
||||
if tag_line:
|
||||
tag_revision = tag_line.split()[0]
|
||||
if tag_revision != revision:
|
||||
raise ReleaseError(
|
||||
f"{component_id} tag {expected_tag} points at "
|
||||
f"{tag_revision}, not {revision}"
|
||||
)
|
||||
|
||||
abi_hash = (
|
||||
contract_hash(current_contract) if current_contract is not None else None
|
||||
)
|
||||
package_id = definition["packageId"]
|
||||
return {
|
||||
"repository": repository,
|
||||
"revision": revision,
|
||||
"componentVersion": version,
|
||||
"abiHash": abi_hash,
|
||||
"sourceTreeHash": f"git-sha1:{tree}",
|
||||
"artifactIdentity": (
|
||||
f"{package_id}-{version}-linux-x86_64"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def prepare(root: Path, workspace: Path, check: bool) -> dict[str, Any]:
|
||||
version = root_product_version((root / "CMakeLists.txt").read_text())
|
||||
|
||||
registry_path = root / "components.json"
|
||||
lock_path = root / "components.lock.json"
|
||||
registry = json.loads(registry_path.read_text())
|
||||
previous_lock = json.loads(lock_path.read_text()) if lock_path.exists() else {}
|
||||
if registry.get("schemaVersion") != 1:
|
||||
raise ReleaseError("unsupported components.json schema")
|
||||
if previous_lock and previous_lock.get("schemaVersion") != 2:
|
||||
raise ReleaseError("unsupported components.lock.json schema")
|
||||
previous_product_version = previous_lock.get("productVersion")
|
||||
if previous_product_version is None and version != "2.0.0":
|
||||
raise ReleaseError(
|
||||
"the first modular release must use root product version 2.0.0"
|
||||
)
|
||||
initial_modular_release = (
|
||||
version == "2.0.0"
|
||||
and previous_product_version in (None, "2.0.0")
|
||||
)
|
||||
|
||||
previous_components = previous_lock.get("components", {})
|
||||
components = {
|
||||
component_id: resolve_component(
|
||||
component_id,
|
||||
definition,
|
||||
previous_components.get(component_id),
|
||||
workspace,
|
||||
version,
|
||||
initial_modular_release,
|
||||
)
|
||||
for component_id, definition in registry["components"].items()
|
||||
}
|
||||
result = {
|
||||
"schemaVersion": 2,
|
||||
"productVersion": version,
|
||||
"components": components,
|
||||
}
|
||||
rendered = json.dumps(result, indent=2, ensure_ascii=False) + "\n"
|
||||
if check:
|
||||
if not lock_path.exists() or lock_path.read_text() != rendered:
|
||||
raise ReleaseError("components.lock.json is not canonical or current")
|
||||
else:
|
||||
temporary = lock_path.with_suffix(".json.tmp")
|
||||
temporary.write_text(rendered)
|
||||
temporary.replace(lock_path)
|
||||
return result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--workspace",
|
||||
type=Path,
|
||||
help="directory containing permanent component repositories",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="validate that components.lock.json is already current",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
workspace = (args.workspace or root.parent).resolve()
|
||||
try:
|
||||
result = prepare(root, workspace, args.check)
|
||||
except ReleaseError as error:
|
||||
print(f"prepare-release: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(
|
||||
f"prepared Echoion {result['productVersion']} with "
|
||||
f"{len(result['components'])} locked components"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+572
@@ -0,0 +1,572 @@
|
||||
#!/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 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 canonical(
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"keyId": self.key_id,
|
||||
"payload": 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)
|
||||
payload = base64.urlsafe_b64decode(
|
||||
str(envelope["payload"]) + "=" * (-len(envelope["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("schemaVersion") != 2
|
||||
or envelope.get("keyId") != self.key_id
|
||||
or len(signature) != 64
|
||||
):
|
||||
fail(f"existing {label} has the wrong schema, key, or signature")
|
||||
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
|
||||
|
||||
|
||||
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",
|
||||
}
|
||||
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"],
|
||||
"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",
|
||||
"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()
|
||||
+133
-135
@@ -11,20 +11,18 @@ Options:
|
||||
--jobs N Parallel build jobs
|
||||
--skip-tests Skip CTest and frontend tests
|
||||
--no-clean Reuse the configured build directory
|
||||
--update-url URL Emit an unsigned runtime feed payload for this artifact
|
||||
--update-channel NAME
|
||||
Feed channel (default: stable)
|
||||
--update-feed-id NAME
|
||||
Feed identifier (default: echoion-runtime)
|
||||
Component package channel (default: stable)
|
||||
--update-sequence N
|
||||
Monotonic feed sequence (default: SOURCE_DATE_EPOCH)
|
||||
--update-valid-days N
|
||||
Feed lifetime in days (default: 30)
|
||||
Monotonic component sequence (default: SOURCE_DATE_EPOCH)
|
||||
--official-update-feed-url URL
|
||||
HTTPS aggregate feed embedded as the official default
|
||||
HTTPS channel catalog embedded as the official default
|
||||
--void-source DIR Use an explicit VoidLibrary source tree
|
||||
--void-teamspeak-source DIR
|
||||
Use an explicit VoidTeamspeak source tree
|
||||
--component-workspace DIR
|
||||
Directory containing the nine permanent component repos
|
||||
(default: parent of this Echoion checkout)
|
||||
--container Build with containers/release.Dockerfile (the default)
|
||||
--host Explicitly build directly on this host
|
||||
-h, --help Show this help
|
||||
@@ -70,14 +68,12 @@ jobs=
|
||||
run_tests=1
|
||||
clean_build=1
|
||||
use_container=1
|
||||
update_url=
|
||||
update_channel=stable
|
||||
update_feed_id=echoion-runtime
|
||||
update_sequence=
|
||||
update_valid_days=30
|
||||
official_update_feed_url=
|
||||
void_source=
|
||||
void_teamspeak_source=
|
||||
component_workspace=$(dirname -- "$source_dir")
|
||||
|
||||
while (($#)); do
|
||||
case $1 in
|
||||
@@ -109,31 +105,16 @@ while (($#)); do
|
||||
clean_build=0
|
||||
shift
|
||||
;;
|
||||
--update-url)
|
||||
(($# >= 2)) || die "--update-url requires a value"
|
||||
update_url=$2
|
||||
shift 2
|
||||
;;
|
||||
--update-channel)
|
||||
(($# >= 2)) || die "--update-channel requires a value"
|
||||
update_channel=$2
|
||||
shift 2
|
||||
;;
|
||||
--update-feed-id)
|
||||
(($# >= 2)) || die "--update-feed-id requires a value"
|
||||
update_feed_id=$2
|
||||
shift 2
|
||||
;;
|
||||
--update-sequence)
|
||||
(($# >= 2)) || die "--update-sequence requires a value"
|
||||
update_sequence=$2
|
||||
shift 2
|
||||
;;
|
||||
--update-valid-days)
|
||||
(($# >= 2)) || die "--update-valid-days requires a value"
|
||||
update_valid_days=$2
|
||||
shift 2
|
||||
;;
|
||||
--official-update-feed-url)
|
||||
(($# >= 2)) || die "--official-update-feed-url requires a value"
|
||||
official_update_feed_url=$2
|
||||
@@ -149,6 +130,11 @@ while (($#)); do
|
||||
void_teamspeak_source=$2
|
||||
shift 2
|
||||
;;
|
||||
--component-workspace)
|
||||
(($# >= 2)) || die "--component-workspace requires a value"
|
||||
component_workspace=$2
|
||||
shift 2
|
||||
;;
|
||||
--container)
|
||||
use_container=1
|
||||
shift
|
||||
@@ -176,18 +162,15 @@ if [[ -n $jobs && ! $jobs =~ ^[1-9][0-9]*$ ]]; then
|
||||
fi
|
||||
[[ $update_channel =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$ ]] ||
|
||||
die "--update-channel contains unsupported characters"
|
||||
[[ $update_feed_id =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$ ]] ||
|
||||
die "--update-feed-id contains unsupported characters"
|
||||
[[ -z $update_sequence || $update_sequence =~ ^[0-9]+$ ]] ||
|
||||
die "--update-sequence must be a non-negative integer"
|
||||
[[ $update_valid_days =~ ^[1-9][0-9]*$ && $update_valid_days -le 365 ]] ||
|
||||
die "--update-valid-days must be between 1 and 365"
|
||||
[[ -z $official_update_feed_url ||
|
||||
$official_update_feed_url == https://* ]] ||
|
||||
die "--official-update-feed-url must use HTTPS"
|
||||
|
||||
build_dir=$(realpath -m -- "$build_dir")
|
||||
dist_dir=$(realpath -m -- "$dist_dir")
|
||||
component_workspace=$(realpath -e -- "$component_workspace")
|
||||
if [[ -n $void_source ]]; then
|
||||
void_source=$(realpath -e -- "$void_source")
|
||||
[[ -d $void_source && -f $void_source/CMakeLists.txt ]] ||
|
||||
@@ -198,6 +181,22 @@ if [[ -n $void_teamspeak_source ]]; then
|
||||
[[ -d $void_teamspeak_source && -f $void_teamspeak_source/CMakeLists.txt ]] ||
|
||||
die "--void-teamspeak-source must name a VoidTeamspeak source directory"
|
||||
fi
|
||||
component_ids=(
|
||||
EchoionApi
|
||||
EchoionCore
|
||||
EchoionDesktop
|
||||
EchoionHost
|
||||
EchoionPluginUrlShortenerExternal
|
||||
EchoionPluginUrlShortenerInternal
|
||||
EchoionStandalone
|
||||
EchoionUpdater
|
||||
EchoionWeb
|
||||
)
|
||||
for component_id in "${component_ids[@]}"; do
|
||||
[[ -f $component_workspace/$component_id/CMakeLists.txt &&
|
||||
-d $component_workspace/$component_id/.git ]] ||
|
||||
die "missing permanent component repository: $component_workspace/$component_id"
|
||||
done
|
||||
|
||||
container_path() {
|
||||
local path=$1
|
||||
@@ -238,6 +237,15 @@ if ((use_container)); then
|
||||
--env HOME=/tmp/echoion-release-home
|
||||
--env npm_config_cache=/tmp/echoion-npm-cache
|
||||
)
|
||||
for component_id in "${component_ids[@]}"; do
|
||||
docker_component_source=$(
|
||||
docker_daemon_path "$component_workspace/$component_id"
|
||||
)
|
||||
container_args+=(
|
||||
--volume
|
||||
"$docker_component_source:/workspace-components/$component_id"
|
||||
)
|
||||
done
|
||||
container_args+=("${proxy_run_args[@]}")
|
||||
if [[ -n $void_source ]]; then
|
||||
docker_void_source=$(docker_daemon_path "$void_source")
|
||||
@@ -259,6 +267,7 @@ if ((use_container)); then
|
||||
--version "$version"
|
||||
--build-dir "$container_build_dir"
|
||||
--dist-dir "$container_dist_dir"
|
||||
--component-workspace /workspace-components
|
||||
)
|
||||
[[ -n $jobs ]] && release_args+=(--jobs "$jobs")
|
||||
((run_tests)) || release_args+=(--skip-tests)
|
||||
@@ -267,16 +276,9 @@ if ((use_container)); then
|
||||
release_args+=(--void-source /workspace-deps/VoidLibrary)
|
||||
[[ -z $void_teamspeak_source ]] ||
|
||||
release_args+=(--void-teamspeak-source /workspace-deps/VoidTeamspeak)
|
||||
if [[ -n $update_url ]]; then
|
||||
release_args+=(
|
||||
--update-url "$update_url"
|
||||
--update-channel "$update_channel"
|
||||
--update-feed-id "$update_feed_id"
|
||||
--update-valid-days "$update_valid_days"
|
||||
)
|
||||
[[ -z $update_sequence ]] ||
|
||||
release_args+=(--update-sequence "$update_sequence")
|
||||
fi
|
||||
release_args+=(--update-channel "$update_channel")
|
||||
[[ -z $update_sequence ]] ||
|
||||
release_args+=(--update-sequence "$update_sequence")
|
||||
[[ -z $official_update_feed_url ]] ||
|
||||
release_args+=(
|
||||
--official-update-feed-url "$official_update_feed_url"
|
||||
@@ -300,7 +302,7 @@ case "$(uname -s)/$(uname -m)" in
|
||||
esac
|
||||
|
||||
required_commands=(
|
||||
cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum openssl
|
||||
cmake file ninja npm python3 patchelf readelf tar zstd gzip sha256sum openssl
|
||||
dpkg-query ldconfig
|
||||
)
|
||||
for command_name in "${required_commands[@]}"; do
|
||||
@@ -340,10 +342,18 @@ configure_args=(
|
||||
-B "$build_dir"
|
||||
-DBUILD_SHARED_LIBS=ON
|
||||
-DECHOION_STATIC_LINK=OFF
|
||||
-DECHOION_RELEASE_BUILD=ON
|
||||
-DECHOION_REPRODUCIBLE_BUILD=ON
|
||||
"-DECHOION_RELEASE_VERSION=$version"
|
||||
"-DECHOION_RUNTIME_VERSION=$version"
|
||||
"-DECHOION_TOOLCHAIN_ABI=linux-x86_64-glibc-2.35-cxx26"
|
||||
"-DECHOION_COMPONENT_WORKSPACE=$component_workspace"
|
||||
)
|
||||
for component_id in "${component_ids[@]}"; do
|
||||
configure_args+=(
|
||||
"-DCPM_${component_id}_SOURCE=$component_workspace/$component_id"
|
||||
)
|
||||
done
|
||||
official_update_keys="$source_dir/.gitea/release-keys/official-update-keys.json"
|
||||
[[ -f $official_update_keys ]] ||
|
||||
die "official update trust store is missing: $official_update_keys"
|
||||
@@ -360,8 +370,9 @@ configure_args+=(
|
||||
configure_args+=("-DCPM_Void_SOURCE=$void_source")
|
||||
[[ -z $void_teamspeak_source ]] ||
|
||||
configure_args+=("-DCPM_VoidTeamspeak_SOURCE=$void_teamspeak_source")
|
||||
npm --prefix "$source_dir/EchoionWeb/frontend" ci --no-audit --no-fund
|
||||
cmake -E rm -rf "$source_dir/EchoionWeb/frontend/web-dist"
|
||||
web_frontend="$component_workspace/EchoionWeb/frontend"
|
||||
npm --prefix "$web_frontend" ci --no-audit --no-fund
|
||||
cmake -E rm -rf "$web_frontend/web-dist"
|
||||
(
|
||||
cd "$source_dir"
|
||||
cmake "${configure_args[@]}"
|
||||
@@ -372,8 +383,8 @@ cmake "${build_args[@]}"
|
||||
|
||||
if ((run_tests)); then
|
||||
ctest --test-dir "$build_dir" --build-config Release --output-on-failure
|
||||
npm --prefix "$source_dir/EchoionWeb/frontend" test
|
||||
npm --prefix "$source_dir/EchoionWeb/frontend" run i18n:check
|
||||
npm --prefix "$web_frontend" test
|
||||
npm --prefix "$web_frontend" run i18n:check
|
||||
fi
|
||||
|
||||
stage="$build_dir/runtime-stage"
|
||||
@@ -454,11 +465,15 @@ collect_licenses() {
|
||||
local destination=$1
|
||||
local candidate relative package_name license_name digest target package source_path soname
|
||||
local -a license_roots=(
|
||||
"$source_dir/EchoionApi"
|
||||
"$source_dir/EchoionCore"
|
||||
"$source_dir/EchoionHost"
|
||||
"$source_dir/EchoionStandalone"
|
||||
"$source_dir/EchoionWeb"
|
||||
"$component_workspace/EchoionApi"
|
||||
"$component_workspace/EchoionCore"
|
||||
"$component_workspace/EchoionHost"
|
||||
"$component_workspace/EchoionStandalone"
|
||||
"$component_workspace/EchoionWeb"
|
||||
"$component_workspace/EchoionUpdater"
|
||||
"$component_workspace/EchoionDesktop"
|
||||
"$component_workspace/EchoionPluginUrlShortenerInternal"
|
||||
"$component_workspace/EchoionPluginUrlShortenerExternal"
|
||||
"$build_dir/_deps"
|
||||
)
|
||||
if [[ -n ${GCC_ROOT:-} && -d $GCC_ROOT/share/licenses ]]; then
|
||||
@@ -531,7 +546,7 @@ collect_licenses() {
|
||||
|
||||
collect_licenses "$stage/share/echoion/licenses"
|
||||
python3 "$source_dir/scripts/collect-frontend-licenses.py" \
|
||||
--node-modules "$source_dir/EchoionWeb/frontend/node_modules" \
|
||||
--node-modules "$web_frontend/node_modules" \
|
||||
--output "$stage/share/echoion/licenses/frontend"
|
||||
|
||||
python3 "$source_dir/scripts/generate-release-manifest.py" \
|
||||
@@ -545,26 +560,66 @@ install -m 0755 "$source_dir/packaging/install.sh" "$stage/install.sh"
|
||||
install -m 0755 "$source_dir/packaging/uninstall.sh" "$stage/uninstall.sh"
|
||||
|
||||
mkdir -p "$dist_dir"
|
||||
component_stage_root="$build_dir/component-staging"
|
||||
safe_remove_tree "$component_stage_root"
|
||||
mkdir -p "$component_stage_root"
|
||||
while IFS=$'\t' read -r component_id package_id; do
|
||||
component_root="$component_stage_root/$package_id"
|
||||
cmake --install "$build_dir" \
|
||||
--config Release \
|
||||
--component "Package${component_id}" \
|
||||
--prefix "$component_root"
|
||||
|
||||
component_executables=()
|
||||
component_libraries=()
|
||||
while IFS= read -r -d '' component_elf; do
|
||||
case $(file --brief --mime-type "$component_elf") in
|
||||
application/x-executable|application/x-pie-executable|application/x-sharedlib) ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
case ${component_elf#"$component_root"/} in
|
||||
bin/*) component_executables+=("$component_elf") ;;
|
||||
*) component_libraries+=("$component_elf") ;;
|
||||
esac
|
||||
done < <(
|
||||
find "$component_root" -type f -print0 | LC_ALL=C sort -z
|
||||
)
|
||||
if ((${#component_executables[@]} || ${#component_libraries[@]})); then
|
||||
component_executable_list=$(
|
||||
IFS=';'
|
||||
echo "${component_executables[*]}"
|
||||
)
|
||||
component_library_list=$(
|
||||
IFS=';'
|
||||
echo "${component_libraries[*]}"
|
||||
)
|
||||
cmake \
|
||||
"-DBUNDLE_ROOT=$component_root" \
|
||||
"-DBUNDLE_EXECUTABLES=$component_executable_list" \
|
||||
"-DBUNDLE_LIBRARIES=$component_library_list" \
|
||||
"-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \
|
||||
"-DBUNDLE_SEED_FILES=$compiler_runtimes" \
|
||||
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
|
||||
-P "$source_dir/cmake/BundleComponentDependencies.cmake"
|
||||
fi
|
||||
done < <(
|
||||
python3 -c \
|
||||
'import json,sys; data=json.load(open(sys.argv[1], encoding="utf-8"))["components"]; [print(name, data[name]["packageId"], sep="\t") for name in sorted(data)]' \
|
||||
"$source_dir/components.json"
|
||||
)
|
||||
|
||||
artifact_base="echoion-${version}-linux-x86_64"
|
||||
archive="$dist_dir/$artifact_base.tar.zst"
|
||||
installer="$dist_dir/$artifact_base.run"
|
||||
external_manifest="$dist_dir/$artifact_base.manifest.json"
|
||||
external_report="$dist_dir/$artifact_base.dependencies.txt"
|
||||
feed_payload="$dist_dir/$artifact_base.update-payload.json"
|
||||
core_artifact="$dist_dir/echoion-core-${version}-linux-x86_64.so"
|
||||
core_feed_payload="$dist_dir/echoion-core-${version}-linux-x86_64.update-payload.json"
|
||||
internal_plugin_artifact="$dist_dir/url-shortener-internal-${version}-linux-x86_64.so"
|
||||
internal_plugin_feed_payload="$dist_dir/url-shortener-internal-${version}-linux-x86_64.update-payload.json"
|
||||
external_plugin_artifact="$dist_dir/url-shortener-external-${version}-linux-x86_64.so"
|
||||
external_plugin_feed_payload="$dist_dir/url-shortener-external-${version}-linux-x86_64.update-payload.json"
|
||||
component_dist="$dist_dir/components"
|
||||
rm -f -- \
|
||||
"$archive" "$archive.tmp" \
|
||||
"$installer" "$installer.tmp" \
|
||||
"$external_manifest" "$external_report" "$feed_payload" \
|
||||
"$core_artifact" "$core_feed_payload" \
|
||||
"$internal_plugin_artifact" "$internal_plugin_feed_payload" \
|
||||
"$external_plugin_artifact" "$external_plugin_feed_payload" \
|
||||
"$external_manifest" "$external_report" \
|
||||
"$dist_dir/SHA256SUMS"
|
||||
cmake -E rm -rf "$component_dist"
|
||||
|
||||
bash "$source_dir/scripts/package-release-payload.sh" \
|
||||
"$stage" "$artifact_base" "$SOURCE_DATE_EPOCH" \
|
||||
@@ -572,73 +627,24 @@ bash "$source_dir/scripts/package-release-payload.sh" \
|
||||
|
||||
install -m 0644 "$stage/manifest.json" "$external_manifest"
|
||||
install -m 0644 "$dependency_report" "$external_report"
|
||||
install -m 0644 "$stage/lib/Echoion.ts" "$core_artifact"
|
||||
install -m 0644 \
|
||||
"$stage/share/echoion/bootstrap-plugins/url-shortener-internal/$version/url-shortener-internal.so" \
|
||||
"$internal_plugin_artifact"
|
||||
install -m 0644 \
|
||||
"$stage/share/echoion/bootstrap-plugins/url-shortener-external/$version/url-shortener-external.so" \
|
||||
"$external_plugin_artifact"
|
||||
if [[ -n $update_url ]]; then
|
||||
feed_args=(
|
||||
--artifact "$archive"
|
||||
--manifest "$external_manifest"
|
||||
--version "$version"
|
||||
--url "$update_url"
|
||||
--channel "$update_channel"
|
||||
--feed-id "$update_feed_id"
|
||||
--valid-days "$update_valid_days"
|
||||
--output-payload "$feed_payload"
|
||||
)
|
||||
[[ -z $update_sequence ]] ||
|
||||
feed_args+=(--sequence "$update_sequence")
|
||||
python3 "$source_dir/scripts/generate-update-feed.py" "${feed_args[@]}"
|
||||
artifact_url_root=${update_url%/*}
|
||||
component_feed_args=(
|
||||
--version "$version"
|
||||
--channel "$update_channel"
|
||||
--feed-id "$update_feed_id"
|
||||
--valid-days "$update_valid_days"
|
||||
)
|
||||
[[ -z $update_sequence ]] ||
|
||||
component_feed_args+=(--sequence "$update_sequence")
|
||||
python3 "$source_dir/scripts/generate-update-feed.py" \
|
||||
--artifact "$core_artifact" \
|
||||
--component core \
|
||||
--url "$artifact_url_root/$(basename "$core_artifact")" \
|
||||
--output-payload "$core_feed_payload" \
|
||||
"${component_feed_args[@]}"
|
||||
python3 "$source_dir/scripts/generate-update-feed.py" \
|
||||
--artifact "$internal_plugin_artifact" \
|
||||
--component plugin \
|
||||
--artifact-id url-shortener-internal \
|
||||
--url "$artifact_url_root/$(basename "$internal_plugin_artifact")" \
|
||||
--output-payload "$internal_plugin_feed_payload" \
|
||||
"${component_feed_args[@]}"
|
||||
python3 "$source_dir/scripts/generate-update-feed.py" \
|
||||
--artifact "$external_plugin_artifact" \
|
||||
--component plugin \
|
||||
--artifact-id url-shortener-external \
|
||||
--url "$artifact_url_root/$(basename "$external_plugin_artifact")" \
|
||||
--output-payload "$external_plugin_feed_payload" \
|
||||
"${component_feed_args[@]}"
|
||||
component_sequence=${update_sequence:-$SOURCE_DATE_EPOCH}
|
||||
if [[ $component_sequence == 0 ]]; then
|
||||
component_sequence=1
|
||||
fi
|
||||
python3 "$source_dir/scripts/package-components.py" \
|
||||
--registry "$source_dir/components.json" \
|
||||
--lock "$source_dir/components.lock.json" \
|
||||
--staging-root "$component_stage_root" \
|
||||
--output "$component_dist" \
|
||||
--channel "$update_channel" \
|
||||
--sequence "$component_sequence" \
|
||||
--product-version "$version" \
|
||||
--toolchain-contract linux-x86_64-glibc-2.35-cxx26
|
||||
(
|
||||
cd "$dist_dir"
|
||||
checksum_files=(
|
||||
"$(basename "$archive")" \
|
||||
"$(basename "$installer")" \
|
||||
"$(basename "$external_manifest")" \
|
||||
"$(basename "$external_report")" \
|
||||
"$(basename "$core_artifact")" \
|
||||
"$(basename "$internal_plugin_artifact")" \
|
||||
"$(basename "$external_plugin_artifact")"
|
||||
)
|
||||
[[ -z $update_url ]] || checksum_files+=(
|
||||
"$(basename "$feed_payload")"
|
||||
"$(basename "$core_feed_payload")"
|
||||
"$(basename "$internal_plugin_feed_payload")"
|
||||
"$(basename "$external_plugin_feed_payload")"
|
||||
mapfile -t checksum_files < <(
|
||||
find . -type f ! -name SHA256SUMS -printf '%P\n' |
|
||||
LC_ALL=C sort
|
||||
)
|
||||
sha256sum "${checksum_files[@]}" >SHA256SUMS
|
||||
)
|
||||
@@ -648,13 +654,5 @@ echo " $archive"
|
||||
echo " $installer"
|
||||
echo " $external_manifest"
|
||||
echo " $external_report"
|
||||
echo " $core_artifact"
|
||||
echo " $internal_plugin_artifact"
|
||||
echo " $external_plugin_artifact"
|
||||
if [[ -n $update_url ]]; then
|
||||
echo " $feed_payload"
|
||||
echo " $core_feed_payload"
|
||||
echo " $internal_plugin_feed_payload"
|
||||
echo " $external_plugin_feed_payload"
|
||||
fi
|
||||
echo " $component_dist"
|
||||
echo " $dist_dir/SHA256SUMS"
|
||||
+31
-29
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Clone the independently versioned Echoion component repositories."""
|
||||
"""Create or synchronize permanent Echoion component working copies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,60 +19,62 @@ def output(*args: str, cwd: Path) -> str:
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--workspace",
|
||||
type=Path,
|
||||
help="component checkout directory (default: parent of Echoion root)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--update",
|
||||
action="store_true",
|
||||
help="fetch and check out locked revisions in existing clean repositories",
|
||||
help="fetch and check out exact revisions from components.lock.json",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--record",
|
||||
action="store_true",
|
||||
help="record the current clean component HEADs in components.lock.json",
|
||||
help="prepare and record a complete canonical release lock",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.update and args.record:
|
||||
parser.error("--update and --record are mutually exclusive")
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
lock_path = root / "components.lock.json"
|
||||
lock = json.loads(lock_path.read_text())
|
||||
if lock.get("schemaVersion") != 1:
|
||||
workspace = (args.workspace or root.parent).resolve()
|
||||
registry = json.loads((root / "components.json").read_text())
|
||||
lock = json.loads((root / "components.lock.json").read_text())
|
||||
if registry.get("schemaVersion") != 1:
|
||||
raise SystemExit("unsupported components.json schema")
|
||||
if lock.get("schemaVersion") != 2:
|
||||
raise SystemExit("unsupported components.lock.json schema")
|
||||
|
||||
if args.record:
|
||||
for name, component in lock["components"].items():
|
||||
destination = root / name
|
||||
if not (destination / ".git").exists():
|
||||
raise SystemExit(f"component repository is missing: {destination}")
|
||||
if output("git", "status", "--porcelain", cwd=destination):
|
||||
raise SystemExit(
|
||||
f"refusing to record dirty repository: {destination}"
|
||||
)
|
||||
component["revision"] = output(
|
||||
"git", "rev-parse", "HEAD", cwd=destination
|
||||
)
|
||||
temporary = lock_path.with_suffix(".json.tmp")
|
||||
temporary.write_text(json.dumps(lock, indent=2) + "\n")
|
||||
temporary.replace(lock_path)
|
||||
run(
|
||||
str(root / "scripts" / "prepare-release.sh"),
|
||||
"--workspace",
|
||||
str(workspace),
|
||||
cwd=root,
|
||||
)
|
||||
return 0
|
||||
|
||||
for name, component in lock["components"].items():
|
||||
destination = root / name
|
||||
revision = component["revision"]
|
||||
for name, component in registry["components"].items():
|
||||
destination = workspace / name
|
||||
revision = (
|
||||
lock["components"][name]["revision"]
|
||||
if args.update
|
||||
else component.get("branch", "main")
|
||||
)
|
||||
if not destination.exists():
|
||||
run(
|
||||
"git",
|
||||
"clone",
|
||||
"--no-checkout",
|
||||
"--branch",
|
||||
component.get("branch", "main"),
|
||||
component["url"],
|
||||
str(destination),
|
||||
)
|
||||
run("git", "fetch", "--depth=1", "origin", revision, cwd=destination)
|
||||
run("git", "checkout", "--detach", "FETCH_HEAD", cwd=destination)
|
||||
continue
|
||||
|
||||
if not (destination / ".git").exists():
|
||||
elif not (destination / ".git").exists():
|
||||
raise SystemExit(f"{destination} exists but is not a Git repository")
|
||||
|
||||
if not args.update:
|
||||
continue
|
||||
if output("git", "status", "--porcelain", cwd=destination):
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [[ $# != 1 ]]; then
|
||||
echo "usage: $0 SOURCE_ROOT" >&2
|
||||
if [[ $# != 2 ]]; then
|
||||
echo "usage: $0 SOURCE_ROOT COMPONENT_WORKSPACE" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
source_root=$(realpath -e -- "$1")
|
||||
component_workspace=$(realpath -e -- "$2")
|
||||
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-packaging.XXXXXX")
|
||||
trap 'rm -rf -- "$temporary"' EXIT
|
||||
|
||||
@@ -54,9 +55,10 @@ if PATH="$pythonless_path" command -v python3 >/dev/null; then
|
||||
fi
|
||||
PATH="$pythonless_path" "$source_root/scripts/release.sh" \
|
||||
--version 1.2.3-rc.1 \
|
||||
--build-dir "$source_root/build-pythonless-container-probe" \
|
||||
--dist-dir "$source_root/dist-pythonless-container-probe" \
|
||||
--skip-tests
|
||||
--build-dir "$source_root/build-pythonless-container-probe" \
|
||||
--dist-dir "$source_root/dist-pythonless-container-probe" \
|
||||
--component-workspace "$component_workspace" \
|
||||
--skip-tests
|
||||
|
||||
bundle="$temporary/bundle"
|
||||
mkdir -p \
|
||||
|
||||
@@ -1,416 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline regression tests for scripts/aggregate_update_feed.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SOURCE_ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = SOURCE_ROOT / "scripts" / "aggregate_update_feed.py"
|
||||
|
||||
|
||||
def release(version: str, channel: str = "nightly") -> dict:
|
||||
return {
|
||||
"component": "runtime",
|
||||
"artifactId": "",
|
||||
"channel": channel,
|
||||
"version": version,
|
||||
"cohort": "linux-glibc-2.35",
|
||||
"platform": "linux",
|
||||
"arch": "x86_64",
|
||||
"url": f"https://updates.example.invalid/echoion-{version}.tar.zst",
|
||||
"size": 123,
|
||||
"sha256": "ab" * 32,
|
||||
"packageType": "tar.zst",
|
||||
"compatibility": {"versionContracts": {}, "exactContracts": {}},
|
||||
"releaseManifestSha256": "cd" * 32,
|
||||
}
|
||||
|
||||
|
||||
def payload(path: Path, releases: list[dict], sequence: int) -> None:
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"feedId": "echoion-runtime",
|
||||
"sequence": sequence,
|
||||
"generatedAt": "2026-07-22T00:00:00Z",
|
||||
"expiresAt": "2026-08-01T00:00:00Z",
|
||||
"releases": releases,
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
class AggregateUpdateFeedTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temporary.name)
|
||||
self.private_key = self.root / "private.pem"
|
||||
self.public_key = self.root / "public.pem"
|
||||
subprocess.run(
|
||||
["openssl", "genpkey", "-algorithm", "ED25519", "-out", self.private_key],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
self.private_key.chmod(0o600)
|
||||
subprocess.run(
|
||||
[
|
||||
"openssl",
|
||||
"pkey",
|
||||
"-in",
|
||||
self.private_key,
|
||||
"-pubout",
|
||||
"-out",
|
||||
self.public_key,
|
||||
],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temporary.cleanup()
|
||||
|
||||
def run_script(
|
||||
self,
|
||||
new_payload: Path,
|
||||
output_payload: Path,
|
||||
output_envelope: Path,
|
||||
*extra: str,
|
||||
check: bool = True,
|
||||
) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
[
|
||||
os.fspath(SCRIPT),
|
||||
"--new-payload",
|
||||
os.fspath(new_payload),
|
||||
"--public-key",
|
||||
os.fspath(self.public_key),
|
||||
"--private-key",
|
||||
os.fspath(self.private_key),
|
||||
"--generated-at",
|
||||
"2026-07-22T12:00:00Z",
|
||||
"--output-payload",
|
||||
os.fspath(output_payload),
|
||||
"--output-envelope",
|
||||
os.fspath(output_envelope),
|
||||
*extra,
|
||||
],
|
||||
check=check,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def test_merge_signs_and_retains_fourteen_nightly_versions(self) -> None:
|
||||
first = self.root / "first.json"
|
||||
first_output = self.root / "first-output.json"
|
||||
first_envelope = self.root / "first-envelope.json"
|
||||
payload(
|
||||
first,
|
||||
[release(f"0.0.0-nightly.202607{day:02d}.1") for day in range(16, 0, -1)],
|
||||
100,
|
||||
)
|
||||
self.run_script(first, first_output, first_envelope)
|
||||
first_document = json.loads(first_output.read_text(encoding="utf-8"))
|
||||
self.assertEqual(len(first_document["releases"]), 14)
|
||||
|
||||
second = self.root / "second.json"
|
||||
second_output = self.root / "second-output.json"
|
||||
second_envelope = self.root / "second-envelope.json"
|
||||
payload(second, [release("1.2.3", "stable")], 101)
|
||||
self.run_script(
|
||||
second,
|
||||
second_output,
|
||||
second_envelope,
|
||||
"--existing-envelope",
|
||||
os.fspath(first_envelope),
|
||||
)
|
||||
document = json.loads(second_output.read_text(encoding="utf-8"))
|
||||
expected_sequence = int(
|
||||
datetime(2026, 7, 22, 12, tzinfo=timezone.utc).timestamp()
|
||||
) + 1
|
||||
self.assertEqual(document["sequence"], expected_sequence)
|
||||
self.assertEqual(document["expiresAt"], "2026-09-05T12:00:00Z")
|
||||
self.assertEqual(len(document["releases"]), 15)
|
||||
self.assertEqual(document["releases"][0]["channel"], "stable")
|
||||
|
||||
envelope = json.loads(second_envelope.read_text(encoding="utf-8"))
|
||||
decoded = base64.urlsafe_b64decode(
|
||||
envelope["payload"] + "=" * (-len(envelope["payload"]) % 4)
|
||||
)
|
||||
self.assertEqual(decoded, second_output.read_bytes())
|
||||
|
||||
third_output = self.root / "third-output.json"
|
||||
third_envelope = self.root / "third-envelope.json"
|
||||
self.run_script(
|
||||
second,
|
||||
third_output,
|
||||
third_envelope,
|
||||
"--existing-envelope",
|
||||
os.fspath(second_envelope),
|
||||
)
|
||||
self.assertEqual(third_output.read_bytes(), second_output.read_bytes())
|
||||
self.assertEqual(third_envelope.read_bytes(), second_envelope.read_bytes())
|
||||
|
||||
changed = json.loads(second.read_text(encoding="utf-8"))
|
||||
changed["releases"][0]["sha256"] = "ef" * 32
|
||||
second.write_text(json.dumps(changed), encoding="utf-8")
|
||||
collision = self.run_script(
|
||||
second,
|
||||
self.root / "collision-output.json",
|
||||
self.root / "collision-envelope.json",
|
||||
"--existing-envelope",
|
||||
os.fspath(second_envelope),
|
||||
check=False,
|
||||
)
|
||||
self.assertNotEqual(collision.returncode, 0)
|
||||
self.assertIn("immutable release identity", collision.stderr)
|
||||
|
||||
def test_multiple_component_payloads_are_signed_together(self) -> None:
|
||||
runtime_payload = self.root / "runtime.json"
|
||||
core_payload = self.root / "core.json"
|
||||
internal_plugin_payload = self.root / "internal-plugin.json"
|
||||
external_plugin_payload = self.root / "external-plugin.json"
|
||||
runtime_release = release("1.2.3", "stable")
|
||||
core_release = {
|
||||
**release("1.2.3", "stable"),
|
||||
"component": "core",
|
||||
"url": "https://updates.example.invalid/echoion-core-1.2.3.so",
|
||||
"packageType": "shared-library",
|
||||
}
|
||||
core_release.pop("releaseManifestSha256")
|
||||
internal_plugin_release = {
|
||||
**core_release,
|
||||
"component": "plugin",
|
||||
"artifactId": "url-shortener-internal",
|
||||
"url": (
|
||||
"https://updates.example.invalid/"
|
||||
"url-shortener-internal-1.2.3.so"
|
||||
),
|
||||
}
|
||||
external_plugin_release = {
|
||||
**core_release,
|
||||
"component": "plugin",
|
||||
"artifactId": "url-shortener-external",
|
||||
"url": (
|
||||
"https://updates.example.invalid/"
|
||||
"url-shortener-external-1.2.3.so"
|
||||
),
|
||||
}
|
||||
payload(runtime_payload, [runtime_release], 100)
|
||||
payload(core_payload, [core_release], 100)
|
||||
payload(internal_plugin_payload, [internal_plugin_release], 100)
|
||||
payload(external_plugin_payload, [external_plugin_release], 100)
|
||||
|
||||
output = self.root / "components-output.json"
|
||||
self.run_script(
|
||||
runtime_payload,
|
||||
output,
|
||||
self.root / "components-envelope.json",
|
||||
"--new-payload",
|
||||
os.fspath(core_payload),
|
||||
"--new-payload",
|
||||
os.fspath(internal_plugin_payload),
|
||||
"--new-payload",
|
||||
os.fspath(external_plugin_payload),
|
||||
)
|
||||
releases = json.loads(output.read_text(encoding="utf-8"))["releases"]
|
||||
self.assertEqual(
|
||||
{
|
||||
(item["component"], item["artifactId"], item["version"])
|
||||
for item in releases
|
||||
},
|
||||
{
|
||||
("runtime", "", "1.2.3"),
|
||||
("core", "", "1.2.3"),
|
||||
("plugin", "url-shortener-internal", "1.2.3"),
|
||||
("plugin", "url-shortener-external", "1.2.3"),
|
||||
},
|
||||
)
|
||||
|
||||
def test_tampered_existing_envelope_is_rejected(self) -> None:
|
||||
first = self.root / "first.json"
|
||||
first_output = self.root / "first-output.json"
|
||||
first_envelope = self.root / "first-envelope.json"
|
||||
payload(first, [release("1.2.3", "stable")], 100)
|
||||
self.run_script(first, first_output, first_envelope)
|
||||
envelope = json.loads(first_envelope.read_text(encoding="utf-8"))
|
||||
envelope["payload"] = envelope["payload"][:-1] + (
|
||||
"A" if envelope["payload"][-1] != "A" else "B"
|
||||
)
|
||||
first_envelope.write_text(json.dumps(envelope), encoding="utf-8")
|
||||
|
||||
second = self.root / "second.json"
|
||||
payload(second, [release("1.2.4", "stable")], 101)
|
||||
failed = self.run_script(
|
||||
second,
|
||||
self.root / "second-output.json",
|
||||
self.root / "second-envelope.json",
|
||||
"--existing-envelope",
|
||||
os.fspath(first_envelope),
|
||||
check=False,
|
||||
)
|
||||
self.assertNotEqual(failed.returncode, 0)
|
||||
self.assertIn("verify the existing feed", failed.stderr)
|
||||
|
||||
def test_private_key_must_match_the_published_public_key(self) -> None:
|
||||
new_payload = self.root / "new.json"
|
||||
payload(new_payload, [release("1.2.3", "stable")], 100)
|
||||
wrong_private_key = self.root / "wrong-private.pem"
|
||||
subprocess.run(
|
||||
[
|
||||
"openssl",
|
||||
"genpkey",
|
||||
"-algorithm",
|
||||
"ED25519",
|
||||
"-out",
|
||||
wrong_private_key,
|
||||
],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
wrong_private_key.chmod(0o600)
|
||||
|
||||
completed = subprocess.run(
|
||||
[
|
||||
os.fspath(SCRIPT),
|
||||
"--new-payload",
|
||||
os.fspath(new_payload),
|
||||
"--public-key",
|
||||
os.fspath(self.public_key),
|
||||
"--private-key",
|
||||
os.fspath(wrong_private_key),
|
||||
"--generated-at",
|
||||
"2026-07-22T12:00:00Z",
|
||||
"--output-payload",
|
||||
os.fspath(self.root / "output.json"),
|
||||
"--output-envelope",
|
||||
os.fspath(self.root / "envelope.json"),
|
||||
],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
|
||||
self.assertNotEqual(completed.returncode, 0)
|
||||
self.assertIn("verify the newly signed feed", completed.stderr)
|
||||
|
||||
def test_key_rotation_accepts_only_an_explicitly_trusted_old_key(self) -> None:
|
||||
old_payload = self.root / "old.json"
|
||||
old_output = self.root / "old-output.json"
|
||||
old_envelope = self.root / "old-envelope.json"
|
||||
payload(old_payload, [release("1.2.3", "stable")], 100)
|
||||
self.run_script(
|
||||
old_payload,
|
||||
old_output,
|
||||
old_envelope,
|
||||
"--key-id",
|
||||
"old-key",
|
||||
)
|
||||
|
||||
new_private_key = self.root / "new-private.pem"
|
||||
new_public_key = self.root / "new-public.pem"
|
||||
subprocess.run(
|
||||
[
|
||||
"openssl",
|
||||
"genpkey",
|
||||
"-algorithm",
|
||||
"ED25519",
|
||||
"-out",
|
||||
new_private_key,
|
||||
],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
new_private_key.chmod(0o600)
|
||||
subprocess.run(
|
||||
[
|
||||
"openssl",
|
||||
"pkey",
|
||||
"-in",
|
||||
new_private_key,
|
||||
"-pubout",
|
||||
"-out",
|
||||
new_public_key,
|
||||
],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
new_payload = self.root / "new.json"
|
||||
payload(new_payload, [release("1.2.4", "stable")], 101)
|
||||
common = [
|
||||
os.fspath(SCRIPT),
|
||||
"--new-payload",
|
||||
os.fspath(new_payload),
|
||||
"--public-key",
|
||||
os.fspath(new_public_key),
|
||||
"--private-key",
|
||||
os.fspath(new_private_key),
|
||||
"--key-id",
|
||||
"new-key",
|
||||
"--generated-at",
|
||||
"2026-07-22T12:00:00Z",
|
||||
"--existing-envelope",
|
||||
os.fspath(old_envelope),
|
||||
]
|
||||
|
||||
rejected = subprocess.run(
|
||||
[
|
||||
*common,
|
||||
"--output-payload",
|
||||
os.fspath(self.root / "rejected-output.json"),
|
||||
"--output-envelope",
|
||||
os.fspath(self.root / "rejected-envelope.json"),
|
||||
],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
self.assertNotEqual(rejected.returncode, 0)
|
||||
self.assertIn("untrusted key id: old-key", rejected.stderr)
|
||||
|
||||
rotated_output = self.root / "rotated-output.json"
|
||||
rotated_envelope = self.root / "rotated-envelope.json"
|
||||
accepted = subprocess.run(
|
||||
[
|
||||
*common,
|
||||
"--trusted-existing-key",
|
||||
f"old-key={self.public_key}",
|
||||
"--output-payload",
|
||||
os.fspath(rotated_output),
|
||||
"--output-envelope",
|
||||
os.fspath(rotated_envelope),
|
||||
],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(accepted.returncode, 0, accepted.stderr)
|
||||
envelope = json.loads(rotated_envelope.read_text(encoding="utf-8"))
|
||||
self.assertEqual(envelope["keyId"], "new-key")
|
||||
releases = json.loads(rotated_output.read_text(encoding="utf-8"))[
|
||||
"releases"
|
||||
]
|
||||
self.assertEqual([item["version"] for item in releases], ["1.2.4", "1.2.3"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for deterministic independent component packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "scripts" / "package-components.py"
|
||||
|
||||
|
||||
class PackageComponentsTests(unittest.TestCase):
|
||||
def test_packages_every_locked_component(self) -> None:
|
||||
with tempfile.TemporaryDirectory(
|
||||
prefix="echoion-package-components."
|
||||
) as directory:
|
||||
root = Path(directory)
|
||||
staging = root / "staging"
|
||||
output = root / "dist"
|
||||
(staging / "echoion-api/include").mkdir(parents=True)
|
||||
(staging / "echoion-api/include/api.hpp").write_text("api")
|
||||
registry = {
|
||||
"schemaVersion": 1,
|
||||
"components": {
|
||||
"EchoionApi": {
|
||||
"repository": "Void/EchoionApi",
|
||||
"kind": "sdk",
|
||||
"packageId": "echoion-api",
|
||||
"activation": "restart-required",
|
||||
"dependencies": {},
|
||||
}
|
||||
},
|
||||
}
|
||||
lock = {
|
||||
"schemaVersion": 2,
|
||||
"productVersion": "2.0.0",
|
||||
"components": {
|
||||
"EchoionApi": {
|
||||
"repository": "Void/EchoionApi",
|
||||
"revision": "1" * 40,
|
||||
"componentVersion": "2.0.0",
|
||||
"abiHash": "sha256:" + "2" * 64,
|
||||
"sourceTreeHash": "git-sha1:" + "3" * 40,
|
||||
"artifactIdentity": (
|
||||
"echoion-api-2.0.0-linux-x86_64"
|
||||
),
|
||||
}
|
||||
},
|
||||
}
|
||||
registry_path = root / "components.json"
|
||||
lock_path = root / "components.lock.json"
|
||||
registry_path.write_text(json.dumps(registry))
|
||||
lock_path.write_text(json.dumps(lock))
|
||||
environment = os.environ.copy()
|
||||
environment["SOURCE_DATE_EPOCH"] = "100"
|
||||
result = subprocess.run(
|
||||
[
|
||||
str(SCRIPT),
|
||||
"--registry",
|
||||
str(registry_path),
|
||||
"--lock",
|
||||
str(lock_path),
|
||||
"--staging-root",
|
||||
str(staging),
|
||||
"--output",
|
||||
str(output),
|
||||
"--channel",
|
||||
"stable",
|
||||
"--sequence",
|
||||
"100",
|
||||
"--product-version",
|
||||
"2.0.0",
|
||||
],
|
||||
check=False,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env=environment,
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
manifest_path = (
|
||||
output
|
||||
/ "echoion-api-2.0.0-linux-x86_64.manifest.json"
|
||||
)
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
self.assertEqual(manifest["componentId"], "EchoionApi")
|
||||
self.assertTrue(
|
||||
(
|
||||
output / "echoion-api-2.0.0-linux-x86_64.tar.zst"
|
||||
).is_file()
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "prepare_release.py"
|
||||
SPEC = importlib.util.spec_from_file_location("prepare_release", SCRIPT)
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class PrepareReleaseTests(unittest.TestCase):
|
||||
def test_root_version_is_the_only_product_version(self) -> None:
|
||||
self.assertEqual(
|
||||
MODULE.root_product_version(
|
||||
"cmake_minimum_required(VERSION 4.0)\n"
|
||||
"project(Echoion VERSION 2.0.0 LANGUAGES CXX)\n"
|
||||
),
|
||||
"2.0.0",
|
||||
)
|
||||
|
||||
def test_duplicate_root_version_is_rejected(self) -> None:
|
||||
with self.assertRaises(MODULE.ReleaseError):
|
||||
MODULE.root_product_version(
|
||||
"project(Echoion VERSION 2.0.0)\n"
|
||||
"project(Echoion VERSION 2.0.1)\n"
|
||||
)
|
||||
|
||||
def test_contract_classification(self) -> None:
|
||||
original = {"descriptor": {"fields": ["id", "version"]}}
|
||||
self.assertEqual(
|
||||
MODULE.classify_contract(original, original), "identical"
|
||||
)
|
||||
self.assertEqual(
|
||||
MODULE.classify_contract(
|
||||
original,
|
||||
{"descriptor": {"fields": ["id", "version", "health"]}},
|
||||
),
|
||||
"compatible",
|
||||
)
|
||||
self.assertEqual(
|
||||
MODULE.classify_contract(
|
||||
original,
|
||||
{"descriptor": {"fields": ["version", "id"]}},
|
||||
),
|
||||
"breaking",
|
||||
)
|
||||
|
||||
def test_component_version_derivation(self) -> None:
|
||||
previous = {
|
||||
"revision": "a" * 40,
|
||||
"componentVersion": "2.3.4",
|
||||
}
|
||||
self.assertEqual(
|
||||
MODULE.derive_component_version(
|
||||
previous, "a" * 40, None, None
|
||||
),
|
||||
"2.3.4",
|
||||
)
|
||||
self.assertEqual(
|
||||
MODULE.derive_component_version(
|
||||
previous, "b" * 40, None, None
|
||||
),
|
||||
"2.3.5",
|
||||
)
|
||||
self.assertEqual(
|
||||
MODULE.derive_component_version(
|
||||
previous,
|
||||
"b" * 40,
|
||||
{"fields": ["a", "b"]},
|
||||
{"fields": ["a"]},
|
||||
),
|
||||
"2.4.0",
|
||||
)
|
||||
self.assertEqual(
|
||||
MODULE.derive_component_version(
|
||||
previous,
|
||||
"b" * 40,
|
||||
{"fields": ["b"]},
|
||||
{"fields": ["a"]},
|
||||
),
|
||||
"3.0.0",
|
||||
)
|
||||
|
||||
def test_contract_hash_is_canonical(self) -> None:
|
||||
self.assertEqual(
|
||||
MODULE.contract_hash({"b": 2, "a": 1}),
|
||||
MODULE.contract_hash({"a": 1, "b": 2}),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for signed channel-separated component feed publication."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "scripts" / "publish-component-feeds.py"
|
||||
|
||||
|
||||
class ComponentFeedTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary = tempfile.TemporaryDirectory(
|
||||
prefix="echoion-component-feed-test."
|
||||
)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.artifacts = self.root / "artifacts"
|
||||
self.feeds = self.root / "feed"
|
||||
self.artifacts.mkdir()
|
||||
self.key = self.root / "feed-key.pem"
|
||||
subprocess.run(
|
||||
[
|
||||
"openssl",
|
||||
"genpkey",
|
||||
"-algorithm",
|
||||
"ED25519",
|
||||
"-out",
|
||||
str(self.key),
|
||||
],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
self.key.chmod(0o600)
|
||||
components = {
|
||||
"EchoionApi": {
|
||||
"repository": "Void/EchoionApi",
|
||||
"packageId": "echoion-api",
|
||||
"kind": "sdk",
|
||||
"activation": "restart-required",
|
||||
"dependencies": {},
|
||||
},
|
||||
"EchoionPluginExample": {
|
||||
"repository": "Void/EchoionPluginExample",
|
||||
"packageId": "echoion-plugin-example",
|
||||
"pluginId": "example",
|
||||
"kind": "plugin",
|
||||
"activation": "reloadable",
|
||||
"dependencies": {"EchoionApi": ">=2.0.0 <3.0.0"},
|
||||
},
|
||||
}
|
||||
self.registry = {"schemaVersion": 1, "components": components}
|
||||
locked = {}
|
||||
for index, component_id in enumerate(components, start=1):
|
||||
locked[component_id] = {
|
||||
"repository": components[component_id]["repository"],
|
||||
"revision": f"{index:040x}",
|
||||
"componentVersion": "2.0.0",
|
||||
"abiHash": f"sha256:{index:064x}",
|
||||
"sourceTreeHash": f"git-sha1:{index + 10:040x}",
|
||||
"artifactIdentity": (
|
||||
f"{components[component_id]['packageId']}-"
|
||||
"2.0.0-linux-x86_64"
|
||||
),
|
||||
}
|
||||
self.lock = {
|
||||
"schemaVersion": 2,
|
||||
"productVersion": "2.0.0",
|
||||
"components": locked,
|
||||
}
|
||||
self.registry_path = self.root / "components.json"
|
||||
self.lock_path = self.root / "components.lock.json"
|
||||
self.registry_path.write_text(json.dumps(self.registry))
|
||||
self.lock_path.write_text(json.dumps(self.lock))
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temporary.cleanup()
|
||||
|
||||
def write_packages(self, channel: str, sequence: int) -> None:
|
||||
for component_id, definition in self.registry["components"].items():
|
||||
version = "2.0.0"
|
||||
if channel != "stable":
|
||||
version += f"-{channel}.{sequence}"
|
||||
stem = (
|
||||
f"{definition['packageId']}-{version}-linux-x86_64"
|
||||
)
|
||||
archive = self.artifacts / f"{stem}.tar.zst"
|
||||
archive.write_bytes(f"{component_id}:{channel}:{sequence}".encode())
|
||||
locked = self.lock["components"][component_id]
|
||||
manifest = {
|
||||
"schemaVersion": 1,
|
||||
"componentId": component_id,
|
||||
"packageId": definition["packageId"],
|
||||
"kind": definition["kind"],
|
||||
"productVersion": "2.0.0",
|
||||
"componentVersion": version,
|
||||
"sourceSha": locked["revision"],
|
||||
"sourceTreeHash": locked["sourceTreeHash"],
|
||||
"abiHash": locked["abiHash"],
|
||||
"artifactIdentity": stem,
|
||||
"activation": definition["activation"],
|
||||
"dependencies": definition["dependencies"],
|
||||
"platform": "linux",
|
||||
"architecture": "x86_64",
|
||||
"toolchainContract": "linux-x86_64-glibc-2.35-cxx26",
|
||||
}
|
||||
(self.artifacts / f"{stem}.manifest.json").write_text(
|
||||
json.dumps(manifest)
|
||||
)
|
||||
|
||||
def publish(
|
||||
self, channel: str, sequence: int, *, expect_success: bool = True
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
result = subprocess.run(
|
||||
[
|
||||
str(SCRIPT),
|
||||
"--registry",
|
||||
str(self.registry_path),
|
||||
"--lock",
|
||||
str(self.lock_path),
|
||||
"--artifacts",
|
||||
str(self.artifacts),
|
||||
"--feed-root",
|
||||
str(self.feeds),
|
||||
"--base-url",
|
||||
"https://updates.example.test/echoion",
|
||||
"--artifact-base-url",
|
||||
"https://updates.example.test/releases/v2.0.0",
|
||||
"--channel",
|
||||
channel,
|
||||
"--sequence",
|
||||
str(sequence),
|
||||
"--generated-at",
|
||||
"2026-07-28T12:00:00Z",
|
||||
"--key-id",
|
||||
"test-key",
|
||||
"--private-key",
|
||||
str(self.key),
|
||||
],
|
||||
check=False,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if expect_success and result.returncode != 0:
|
||||
self.fail(result.stderr)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def payload(path: Path) -> dict[str, object]:
|
||||
envelope = json.loads(path.read_text())
|
||||
encoded = envelope["payload"]
|
||||
decoded = base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))
|
||||
return json.loads(decoded)
|
||||
|
||||
def test_stable_layout_and_catalog(self) -> None:
|
||||
self.write_packages("stable", 100)
|
||||
self.publish("stable", 100)
|
||||
catalog = self.payload(self.feeds / "feeds/stable/catalog.json")
|
||||
self.assertEqual(len(catalog["components"]), 2)
|
||||
self.assertTrue(
|
||||
(self.feeds / "feeds/stable/echoion-api/2.0.0.json").is_file()
|
||||
)
|
||||
self.assertTrue(
|
||||
(
|
||||
self.feeds
|
||||
/ "feeds/stable/plugins/example/2.0.0.json"
|
||||
).is_file()
|
||||
)
|
||||
state = json.loads(
|
||||
(
|
||||
self.feeds
|
||||
/ "state/components/EchoionPluginExample.json"
|
||||
).read_text()
|
||||
)
|
||||
self.assertEqual(state["semVer"], "2.0.0")
|
||||
self.assertEqual(state["sequence"], 100)
|
||||
release = self.payload(
|
||||
self.feeds / "feeds/stable/echoion-api/2.0.0.json"
|
||||
)
|
||||
self.assertEqual(release["artifactIdentity"], "echoion-api-2.0.0-linux-x86_64")
|
||||
self.assertEqual(release["platform"], "linux")
|
||||
self.assertEqual(release["architecture"], "x86_64")
|
||||
self.assertEqual(
|
||||
release["toolchainContract"],
|
||||
"linux-x86_64-glibc-2.35-cxx26",
|
||||
)
|
||||
|
||||
def test_rejects_replay_and_immutable_artifact_change(self) -> None:
|
||||
self.write_packages("stable", 100)
|
||||
self.publish("stable", 100)
|
||||
replay = self.publish("stable", 100, expect_success=False)
|
||||
self.assertNotEqual(replay.returncode, 0)
|
||||
for archive in self.artifacts.glob("*.tar.zst"):
|
||||
archive.write_bytes(archive.read_bytes() + b"changed")
|
||||
conflict = self.publish("stable", 101, expect_success=False)
|
||||
self.assertNotEqual(conflict.returncode, 0)
|
||||
self.assertIn("unchanged source SHA", conflict.stderr)
|
||||
|
||||
def test_beta_does_not_advance_stable_state(self) -> None:
|
||||
self.write_packages("stable", 100)
|
||||
self.publish("stable", 100)
|
||||
for path in self.artifacts.iterdir():
|
||||
path.unlink()
|
||||
self.write_packages("beta", 200)
|
||||
self.publish("beta", 200)
|
||||
state = json.loads(
|
||||
(
|
||||
self.feeds / "state/components/EchoionApi.json"
|
||||
).read_text()
|
||||
)
|
||||
self.assertEqual(state["semVer"], "2.0.0")
|
||||
self.assertEqual(state["sequence"], 100)
|
||||
self.assertEqual(state["channels"]["beta"]["version"], "2.0.0-beta.200")
|
||||
beta_release = self.payload(
|
||||
self.feeds
|
||||
/ "feeds/beta/echoion-api/2.0.0-beta.200.json"
|
||||
)
|
||||
self.assertEqual(
|
||||
beta_release["artifactIdentity"],
|
||||
"echoion-api-2.0.0-beta.200-linux-x86_64",
|
||||
)
|
||||
self.assertTrue(
|
||||
(
|
||||
self.feeds
|
||||
/ "feeds/beta/echoion-api/2.0.0-beta.200.json"
|
||||
).is_file()
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user