Add independent component release architecture
Modular container CI / release-build (push) Failing after 12s

This commit is contained in:
faumaray committed 2026-07-29 22:40:35 +03:00
1 parent 458dde05a6
commit 2a533a27f8
18 files changed
+2110 -216

No files matched your search

+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Create one deterministic, product-independent Echoion component package."""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
from pathlib import Path
import re
import shutil
import tempfile
from types import ModuleType
from typing import Any, NoReturn
GIT_SHA = re.compile(r"^[0-9a-f]{40}$")
HASH = re.compile(r"^(?:sha256:[0-9a-f]{64}|git-sha1:[0-9a-f]{40})$")
SEMVER = re.compile(
r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
)
TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$")
def fail(message: str) -> NoReturn:
raise SystemExit(f"package-component: {message}")
def load_packaging_helpers() -> ModuleType:
path = Path(__file__).with_name("package-components.py")
specification = importlib.util.spec_from_file_location(
"echoion_package_components", path
)
if specification is None or specification.loader is None:
fail(f"cannot load shared packaging helpers from {path}")
module = importlib.util.module_from_spec(specification)
specification.loader.exec_module(module)
return module
def load_json_object(path: Path, label: str) -> dict[str, Any]:
try:
value = 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(value, dict):
fail(f"{label} must be a JSON object")
return value
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--registry", type=Path, default=Path("components.json"))
parser.add_argument("--component", required=True)
parser.add_argument("--package-root", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--component-version", required=True)
parser.add_argument(
"--product-compatibility", default=">=2.0.0 <3.0.0"
)
parser.add_argument("--source-sha", required=True)
parser.add_argument("--source-tree-hash", required=True)
parser.add_argument("--abi-hash")
parser.add_argument("--build-dependencies", type=Path)
parser.add_argument("--platform", default="linux")
parser.add_argument("--architecture", default="x86_64")
parser.add_argument(
"--toolchain-contract",
default="linux-x86_64-glibc-2.35-cxx26",
)
arguments = parser.parse_args()
if not TOKEN.fullmatch(arguments.component):
fail("invalid component ID")
if not SEMVER.fullmatch(arguments.component_version):
fail("--component-version must be canonical SemVer")
if (
not arguments.product_compatibility
or len(arguments.product_compatibility) > 256
or any(
character in arguments.product_compatibility
for character in "\r\n\0"
)
):
fail("--product-compatibility is invalid")
if not GIT_SHA.fullmatch(arguments.source_sha):
fail("--source-sha must be a full lowercase Git SHA")
if not HASH.fullmatch(arguments.source_tree_hash):
fail("--source-tree-hash must be a supported content hash")
if arguments.abi_hash is not None and not re.fullmatch(
r"sha256:[0-9a-f]{64}", arguments.abi_hash
):
fail("--abi-hash must be a SHA-256 hash")
for label, value in (
("--platform", arguments.platform),
("--architecture", arguments.architecture),
("--toolchain-contract", arguments.toolchain_contract),
):
if not TOKEN.fullmatch(value):
fail(f"{label} is invalid")
registry = load_json_object(arguments.registry, "component registry")
definitions = registry.get("components")
if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict):
fail("unsupported component registry schema")
definition = definitions.get(arguments.component)
if not isinstance(definition, dict):
fail(f"component is not registered: {arguments.component}")
package_id = definition.get("packageId")
if not isinstance(package_id, str) or not TOKEN.fullmatch(package_id):
fail("registered packageId is invalid")
build_dependencies: dict[str, Any] = {}
if arguments.build_dependencies is not None:
build_dependencies = load_json_object(
arguments.build_dependencies, "build dependency provenance"
)
package_root = arguments.package_root.resolve(strict=True)
if package_root.is_symlink() or not package_root.is_dir():
fail("--package-root must be a real directory")
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")
helpers = load_packaging_helpers()
artifact_identity = (
f"{package_id}-{arguments.component_version}-"
f"{arguments.platform}-{arguments.architecture}"
)
with tempfile.TemporaryDirectory(
prefix=".component-package.", dir=output
) as temporary:
staged = Path(temporary) / artifact_identity
shutil.copytree(package_root, staged, symlinks=True)
files = helpers.validate_tree(staged)
manifest = {
"schemaVersion": 3,
"componentId": arguments.component,
"packageId": package_id,
"kind": definition["kind"],
"productCompatibility": arguments.product_compatibility,
"componentVersion": arguments.component_version,
"sourceSha": arguments.source_sha,
"sourceTreeHash": arguments.source_tree_hash,
"abiHash": arguments.abi_hash,
"activation": definition["activation"],
"dependencies": definition["dependencies"],
"buildDependencies": build_dependencies,
"platform": arguments.platform,
"architecture": arguments.architecture,
"toolchainContract": arguments.toolchain_contract,
"artifactIdentity": artifact_identity,
"privateLibraries": helpers.private_libraries(staged),
"files": files,
}
manifest_bytes = helpers.canonical(manifest)
(staged / "manifest.json").write_bytes(manifest_bytes)
archive = output / f"{artifact_identity}.tar.zst"
helpers.create_archive(staged, archive, int(epoch_value))
manifest_path = output / f"{artifact_identity}.manifest.json"
manifest_path.write_bytes(manifest_bytes)
print(f"packaged {arguments.component}: {archive.name}")
if __name__ == "__main__":
main()
+258
View File
@@ -0,0 +1,258 @@
#!/usr/bin/env python3
"""Validate and derive one component's independent release identity."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
import subprocess
import sys
from typing import Any, NoReturn
SEMVER = re.compile(
r"^(?P<major>0|[1-9][0-9]*)\."
r"(?P<minor>0|[1-9][0-9]*)\."
r"(?P<patch>0|[1-9][0-9]*)$"
)
RELEASE_VERSION = 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"prepare-component-release: {message}")
def canonical(value: Any) -> bytes:
return (
json.dumps(
value,
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:
value = 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(value, dict):
fail(f"{label} must be a JSON object")
return value
def git(repository: Path, *arguments: str) -> str:
try:
return subprocess.check_output(
["git", "-C", str(repository), *arguments],
text=True,
stderr=subprocess.STDOUT,
).strip()
except (OSError, subprocess.CalledProcessError) as error:
detail = getattr(error, "output", "") or str(error)
fail(f"git {' '.join(arguments)} failed: {detail.strip()}")
def read_contract(repository: Path, revision: str, relative: str) -> Any:
raw = git(repository, "show", f"{revision}:{relative}")
try:
value = json.loads(raw)
except json.JSONDecodeError as error:
fail(f"{relative} at {revision} is invalid JSON: {error}")
if not isinstance(value, dict) or value.get("schemaVersion") != 1:
fail(f"{relative} at {revision} has an unsupported ABI schema")
return value
def compatible_append(old: Any, new: Any) -> bool:
if type(old) is not type(new):
return False
if isinstance(old, dict):
return all(
key in new and compatible_append(value, new[key])
for key, value in old.items()
)
if isinstance(old, list):
return len(new) >= len(old) and all(
compatible_append(value, new[index])
for index, value in enumerate(old)
)
return old == new
def change_classification(old: Any, new: Any) -> str:
if canonical(old) == canonical(new):
return "patch"
return "minor" if compatible_append(old, new) else "major"
def bump(version: str, change: str) -> str:
match = SEMVER.fullmatch(version)
if match is None:
fail(f"previous stable version is invalid: {version!r}")
major = int(match.group("major"))
minor = int(match.group("minor"))
patch = int(match.group("patch"))
if change == "patch":
return f"{major}.{minor}.{patch + 1}"
if change == "minor":
return f"{major}.{minor + 1}.0"
if change == "major":
return f"{major + 1}.0.0"
raise AssertionError(change)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--registry", type=Path, required=True)
parser.add_argument("--configuration", type=Path, required=True)
parser.add_argument("--repository", type=Path, required=True)
parser.add_argument("--feed-root", type=Path, required=True)
parser.add_argument(
"--channel", choices=("stable", "beta", "nightly"), required=True
)
parser.add_argument("--requested-version")
parser.add_argument("--nightly-sequence")
parser.add_argument("--output", type=Path)
arguments = parser.parse_args()
registry = load_object(arguments.registry, "component registry")
configuration = load_object(
arguments.configuration, "component release configuration"
)
definitions = registry.get("components")
if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict):
fail("unsupported component registry schema")
if configuration.get("schemaVersion") != 1:
fail("unsupported component release configuration schema")
component_id = configuration.get("componentId")
definition = definitions.get(component_id)
if not isinstance(component_id, str) or not isinstance(definition, dict):
fail("configured component is not present in the registry")
compatibility = configuration.get("productCompatibility")
if not isinstance(compatibility, str) or not compatibility:
fail("productCompatibility is required")
if not isinstance(configuration.get("cmakeOptions"), dict):
fail("cmakeOptions must be an object")
repository = arguments.repository.resolve(strict=True)
if git(repository, "status", "--porcelain"):
fail("component repository must be clean")
source_sha = git(repository, "rev-parse", "HEAD")
source_tree = git(repository, "rev-parse", "HEAD^{tree}")
state_path = (
arguments.feed_root
/ "state"
/ "components"
/ f"{component_id}.json"
)
state = (
load_object(state_path, "component state")
if state_path.exists()
else {}
)
channels = state.get("channels", {})
if not isinstance(channels, dict):
fail("component state channels must be an object")
channel_state = channels.get(arguments.channel, {})
if not isinstance(channel_state, dict):
fail("component channel state must be an object")
if channel_state.get("sourceSha") == source_sha:
if arguments.channel == "nightly":
print("component source is already published in nightly")
return 3
fail(f"component source is already published in {arguments.channel}")
previous_version = state.get("semVer")
previous_sha = state.get("lastSourceSha")
contract_path = definition.get("abiContract")
abi_hash = None
if contract_path is not None:
if not isinstance(contract_path, str) or not contract_path:
fail("registered ABI contract path is invalid")
current_contract = read_contract(repository, source_sha, contract_path)
abi_hash = "sha256:" + hashlib.sha256(
canonical(current_contract)
).hexdigest()
else:
current_contract = None
if previous_version is None:
expected_stable = "2.0.0"
change = "initial"
else:
if not isinstance(previous_sha, str) or not re.fullmatch(
r"[0-9a-f]{40}", previous_sha
):
fail("stable component state has no valid source SHA")
if previous_sha == source_sha:
fail("unchanged source cannot produce another release")
if current_contract is None:
change = "patch"
else:
previous_contract = read_contract(
repository, previous_sha, contract_path
)
change = change_classification(
previous_contract, current_contract
)
expected_stable = bump(str(previous_version), change)
if arguments.channel == "nightly":
if not arguments.nightly_sequence or not re.fullmatch(
r"[0-9]+", arguments.nightly_sequence
):
fail("--nightly-sequence must be a positive integer")
version = f"{expected_stable}-nightly.{arguments.nightly_sequence}"
else:
requested = arguments.requested_version
if not isinstance(requested, str) or not RELEASE_VERSION.fullmatch(
requested
):
fail("--requested-version must be canonical SemVer")
requested_base = requested.split("-", 1)[0]
if requested_base != expected_stable:
fail(
f"{change} change requires version {expected_stable}; "
f"received {requested}"
)
if arguments.channel == "stable" and "-" in requested:
fail("stable release version must not have a prerelease suffix")
if arguments.channel == "beta" and "-" not in requested:
fail("beta release version must have a prerelease suffix")
version = requested
result = {
"schemaVersion": 1,
"componentId": component_id,
"channel": arguments.channel,
"componentVersion": version,
"productCompatibility": compatibility,
"sourceSha": source_sha,
"sourceTreeHash": f"git-sha1:{source_tree}",
"abiHash": abi_hash,
"change": change,
}
encoded = canonical(result)
if arguments.output is None:
sys.stdout.buffer.write(encoded)
else:
temporary = arguments.output.with_name(arguments.output.name + ".tmp")
temporary.write_bytes(encoded)
temporary.replace(arguments.output)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+25
View File
@@ -213,6 +213,31 @@ class Signer:
return document
class PublicKeyVerifier:
verify = Signer.verify
def __init__(self, public_key: Path, key_id: str) -> None:
self.public_key = regular_file(public_key, "public key")
self.key_id = key_id
self.temporary = tempfile.TemporaryDirectory(
prefix="echoion-component-feed-verify."
)
self.directory = Path(self.temporary.name)
run_openssl(
[
"pkey",
"-pubin",
"-in",
os.fspath(self.public_key),
"-noout",
],
"validate the feed public key",
)
def close(self) -> None:
self.temporary.cleanup()
def validate_https(value: str, label: str) -> str:
parsed = urlsplit(value)
if (
+338
View File
@@ -0,0 +1,338 @@
#!/usr/bin/env python3
"""Merge one signed independent component release into an Echoion feed."""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
from pathlib import Path
import re
from types import ModuleType
from typing import Any, NoReturn
from urllib.parse import quote
GIT_SHA = re.compile(r"^[0-9a-f]{40}$")
SEMVER = re.compile(
r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
)
def fail(message: str) -> NoReturn:
raise SystemExit(f"publish-component-release: {message}")
def load_feed_helpers() -> ModuleType:
path = Path(__file__).with_name("publish-component-feeds.py")
specification = importlib.util.spec_from_file_location(
"echoion_publish_component_feeds", path
)
if specification is None or specification.loader is None:
fail(f"cannot load shared feed helpers from {path}")
module = importlib.util.module_from_spec(specification)
specification.loader.exec_module(module)
return module
def validate_manifest(
helpers: ModuleType,
manifest: dict[str, Any],
definition: dict[str, Any],
component_id: str,
) -> None:
expected = {
"schemaVersion": 3,
"componentId": component_id,
"packageId": definition["packageId"],
"kind": definition["kind"],
"activation": definition["activation"],
"dependencies": definition["dependencies"],
}
for field, value in expected.items():
if manifest.get(field) != value:
fail(f"manifest {field} does not match the registry")
if not SEMVER.fullmatch(str(manifest.get("componentVersion", ""))):
fail("manifest componentVersion is not canonical SemVer")
if not GIT_SHA.fullmatch(str(manifest.get("sourceSha", ""))):
fail("manifest sourceSha is invalid")
if not re.fullmatch(
r"(?:git-sha1:[0-9a-f]{40}|sha256:[0-9a-f]{64})",
str(manifest.get("sourceTreeHash", "")),
):
fail("manifest sourceTreeHash is invalid")
abi_hash = manifest.get("abiHash")
if abi_hash is not None and not re.fullmatch(
r"sha256:[0-9a-f]{64}", str(abi_hash)
):
fail("manifest abiHash is invalid")
compatibility = manifest.get("productCompatibility")
if not isinstance(compatibility, str) or not compatibility:
fail("manifest productCompatibility is missing")
if not isinstance(manifest.get("buildDependencies"), dict):
fail("manifest buildDependencies must be an object")
for field in (
"artifactIdentity",
"platform",
"architecture",
"toolchainContract",
):
if not isinstance(manifest.get(field), str) or not manifest[field]:
fail(f"manifest {field} is missing")
if manifest["artifactIdentity"] != (
f"{manifest['packageId']}-{manifest['componentVersion']}-"
f"{manifest['platform']}-{manifest['architecture']}"
):
fail("manifest artifactIdentity is inconsistent")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--registry", type=Path, default=Path("components.json"))
parser.add_argument("--component", required=True)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--archive", type=Path, required=True)
parser.add_argument("--feed-root", type=Path, required=True)
parser.add_argument("--base-url", required=True)
parser.add_argument("--artifact-base-url", required=True)
parser.add_argument(
"--channel", choices=("stable", "beta", "nightly"), required=True
)
parser.add_argument("--sequence", type=int, required=True)
parser.add_argument("--generated-at")
parser.add_argument("--valid-days", type=int, default=45)
parser.add_argument("--key-id", required=True)
parser.add_argument("--private-key", type=Path, required=True)
arguments = parser.parse_args()
helpers = load_feed_helpers()
if not helpers.TOKEN.fullmatch(arguments.component):
fail("invalid component ID")
if not helpers.TOKEN.fullmatch(arguments.key_id):
fail("invalid key ID")
if arguments.sequence < 1 or arguments.sequence > (1 << 63) - 1:
fail("--sequence must be between 1 and 2^63-1")
if arguments.valid_days < 1 or arguments.valid_days > 365:
fail("--valid-days must be between 1 and 365")
base_url = helpers.validate_https(arguments.base_url, "--base-url")
artifact_base_url = helpers.validate_https(
arguments.artifact_base_url, "--artifact-base-url"
)
registry = helpers.load_object(arguments.registry, "component registry")
definitions = registry.get("components")
if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict):
fail("unsupported component registry schema")
definition = definitions.get(arguments.component)
if not isinstance(definition, dict):
fail(f"component is not registered: {arguments.component}")
manifest_path = helpers.regular_file(
arguments.manifest, "component package manifest"
)
archive = helpers.regular_file(arguments.archive, "component package")
manifest = helpers.load_object(manifest_path, "component package manifest")
validate_manifest(helpers, manifest, definition, arguments.component)
expected_archive = f"{manifest['artifactIdentity']}.tar.zst"
if archive.name != expected_archive:
fail(f"archive must be named {expected_archive}")
version = manifest["componentVersion"]
if arguments.channel == "stable" and "-" in version:
fail("stable releases must not use a prerelease version")
if arguments.channel == "beta" and "-" not in version:
fail("beta releases must use a prerelease version")
if arguments.channel == "nightly" and "-nightly." not in version:
fail("nightly releases must use a -nightly.N version")
generated = helpers.parse_time(arguments.generated_at)
generated_at = helpers.format_time(generated)
expires_at = helpers.format_time(
generated + helpers.timedelta(days=arguments.valid_days)
)
feed_root = arguments.feed_root.resolve()
signer = helpers.Signer(arguments.private_key, arguments.key_id)
writes: dict[Path, bytes] = {}
try:
archive_sha = helpers.digest(archive)
manifest_sha = hashlib.sha256(helpers.canonical(manifest)).hexdigest()
state_path = (
feed_root
/ "state"
/ "components"
/ f"{arguments.component}.json"
)
state = (
helpers.load_object(state_path, "component state")
if state_path.exists()
else {
"schemaVersion": 2,
"componentId": arguments.component,
"channels": {},
}
)
channels = state.setdefault("channels", {})
old_channel = channels.get(arguments.channel, {})
old_sequence = old_channel.get("sequence", 0)
if not isinstance(old_sequence, int) or old_sequence >= arguments.sequence:
fail(
f"{arguments.component} {arguments.channel} sequence "
"is not monotonic"
)
if arguments.channel == "stable":
if (
state.get("lastSourceSha") == manifest["sourceSha"]
and state.get("artifactHash") not in (None, archive_sha)
):
fail("changed artifact for an unchanged source SHA")
state.update(
{
"lastSourceSha": manifest["sourceSha"],
"semVer": version,
"abiSchema": manifest["abiHash"],
"artifactHash": archive_sha,
"sequence": arguments.sequence,
}
)
channels[arguments.channel] = {
"version": version,
"artifactHash": archive_sha,
"sourceSha": manifest["sourceSha"],
"sequence": arguments.sequence,
}
relative = helpers.component_path(registry, arguments.component)
version_path = (
feed_root
/ "feeds"
/ arguments.channel
/ relative
/ f"{version}.json"
)
latest_path = version_path.with_name("latest.json")
artifact_url = (
f"{artifact_base_url}/{quote(arguments.component, safe='')}/"
f"{quote(version, safe='')}/{quote(archive.name, safe='')}"
)
artifact = {
"name": archive.name,
"url": artifact_url,
"sha256": archive_sha,
"size": archive.stat().st_size,
"manifestSha256": manifest_sha,
"packageType": "tar.zst",
}
payload = {
"schemaVersion": 3,
"document": "echoion-component-release",
"channel": arguments.channel,
"sequence": arguments.sequence,
"generatedAt": generated_at,
"expiresAt": expires_at,
"productCompatibility": manifest["productCompatibility"],
"componentId": arguments.component,
"pluginId": definition.get("pluginId"),
"kind": definition["kind"],
"componentVersion": version,
"sourceSha": manifest["sourceSha"],
"sourceTreeHash": manifest["sourceTreeHash"],
"abiHash": manifest["abiHash"],
"artifactIdentity": manifest["artifactIdentity"],
"activation": definition["activation"],
"platform": manifest["platform"],
"architecture": manifest["architecture"],
"toolchainContract": manifest["toolchainContract"],
"dependencies": definition["dependencies"],
"buildDependencies": manifest["buildDependencies"],
"artifact": artifact,
}
envelope = signer.envelope(payload)
if version_path.exists():
existing = signer.verify(
version_path.read_bytes(),
f"{arguments.component} version feed",
)
immutable = {
key: value
for key, value in payload.items()
if key not in {"generatedAt", "expiresAt", "sequence"}
}
if any(existing.get(key) != value for key, value in immutable.items()):
fail(f"immutable version feed conflict: {version_path}")
else:
writes[version_path] = envelope
writes[latest_path] = envelope
writes[state_path] = helpers.canonical(state)
catalog_path = (
feed_root / "feeds" / arguments.channel / "catalog.json"
)
old_components: list[dict[str, Any]] = []
if catalog_path.exists():
old_catalog = signer.verify(
catalog_path.read_bytes(), f"{arguments.channel} catalog"
)
if (
old_catalog.get("document") != "echoion-component-catalog"
or old_catalog.get("channel") != arguments.channel
):
fail("existing catalog has the wrong document or channel")
old_catalog_sequence = old_catalog.get("sequence", 0)
if (
not isinstance(old_catalog_sequence, int)
or old_catalog_sequence >= arguments.sequence
):
fail("catalog sequence is not monotonic")
existing_components = old_catalog.get("components")
if not isinstance(existing_components, list):
fail("existing catalog components must be an array")
old_components = [
item
for item in existing_components
if isinstance(item, dict)
and item.get("componentId") != arguments.component
]
relative_url = relative.as_posix()
old_components.append(
{
"componentId": arguments.component,
"pluginId": definition.get("pluginId"),
"kind": definition["kind"],
"componentVersion": version,
"productCompatibility": manifest["productCompatibility"],
"activation": definition["activation"],
"dependencies": definition["dependencies"],
"sequence": arguments.sequence,
"latestUrl": (
f"{base_url}/feeds/{arguments.channel}/"
f"{relative_url}/latest.json"
),
"artifactSha256": archive_sha,
}
)
old_components.sort(key=lambda item: str(item.get("componentId", "")))
catalog = {
"schemaVersion": 3,
"document": "echoion-component-catalog",
"channel": arguments.channel,
"sequence": arguments.sequence,
"generatedAt": generated_at,
"expiresAt": expires_at,
"components": old_components,
}
writes[catalog_path] = signer.envelope(catalog)
for path, content in sorted(writes.items()):
helpers.atomic_write(path, content)
finally:
signer.close()
print(
f"published {arguments.component} {arguments.channel} "
f"at sequence {arguments.sequence}"
)
if __name__ == "__main__":
main()
+349
View File
@@ -0,0 +1,349 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "usage: $0 COMPONENT_RELEASE_JSON" >&2
exit 2
}
(($# == 1)) || usage
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
root=$(cd -- "$script_dir/.." && pwd -P)
source_root=$(pwd -P)
configuration=$(realpath -- "$1")
required_commands=(
aws
cmake
cmp
ctest
find
git
jq
ninja
openssl
python3
realpath
ssh
zstd
)
for command_name in "${required_commands[@]}"; do
command -v "$command_name" >/dev/null ||
{
echo "release-component: missing command: $command_name" >&2
exit 2
}
done
required_environment=(
ECHOION_COMPONENT_SSH_KEY
ECHOION_DISTRIBUTION_BASE_URL
ECHOION_FEED_BASE_URL
ECHOION_FEED_COMMIT_SIGNING_KEY
ECHOION_FEED_PRIVATE_KEY
ECHOION_FEED_REPOSITORY
ECHOION_FEED_SIGNING_KEY_ID
ECHOION_OBJECT_STORAGE_BUCKET
ECHOION_RELEASE_TAG_ALLOWED_SIGNERS
GITEA_API_URL
GITEA_RELEASE_TOKEN
GITEA_REPOSITORY
)
for variable in "${required_environment[@]}"; do
if [[ -z ${!variable:-} ]]; then
echo "release-component: $variable is required" >&2
exit 2
fi
done
component_id=$(jq -er '
if .schemaVersion == 1 and
(.componentId | type == "string" and length > 0) and
(.productCompatibility | type == "string" and length > 0) and
(.cmakeOptions | type == "object")
then .componentId
else error("invalid component release configuration")
end
' "$configuration")
if [[ ! $component_id =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$ ]]; then
echo "release-component: invalid component ID" >&2
exit 2
fi
repository_name=${GITEA_REPOSITORY#*/}
if [[ $GITEA_REPOSITORY != */* || -z $repository_name ]]; then
echo "release-component: GITEA_REPOSITORY must be owner/name" >&2
exit 2
fi
work_root=${RUNNER_TEMP:-"$source_root/.component-release"}
work_root=$(realpath -m -- "$work_root/echoion-$component_id")
components="$work_root/components"
dependencies="$work_root/dependencies"
build="$work_root/build"
install_root="$work_root/install"
dist="$work_root/dist"
feed_state="$work_root/feed-state"
secrets_dir="$work_root/secrets"
mkdir -p "$work_root"
rm -rf -- "$components" "$dependencies" "$build" "$install_root" "$dist" \
"$feed_state" "$secrets_dir"
mkdir -p "$secrets_dir"
chmod 0700 "$secrets_dir"
cleanup() {
rm -rf -- "$secrets_dir"
}
trap cleanup EXIT
umask 077
ssh_key="$secrets_dir/release-ssh"
known_hosts="$secrets_dir/known-hosts"
feed_key="$secrets_dir/feed-ed25519.pem"
commit_key="$secrets_dir/feed-commit-key"
allowed_signers="$secrets_dir/tag-allowed-signers"
printf '%s\n' "$ECHOION_COMPONENT_SSH_KEY" >"$ssh_key"
printf '%s\n' "$ECHOION_FEED_PRIVATE_KEY" >"$feed_key"
printf '%s\n' "$ECHOION_FEED_COMMIT_SIGNING_KEY" >"$commit_key"
printf '%s\n' "$ECHOION_RELEASE_TAG_ALLOWED_SIGNERS" >"$allowed_signers"
printf '%s\n' \
'git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==' \
>"$known_hosts"
chmod 0600 "$ssh_key" "$known_hosts" "$feed_key" "$commit_key" \
"$allowed_signers"
openssl pkey -in "$feed_key" -noout
export GIT_SSH_COMMAND="ssh -i $ssh_key -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$known_hosts"
git clone --filter=blob:none --branch release-feed --single-branch \
"$ECHOION_FEED_REPOSITORY" "$feed_state"
event=${GITEA_EVENT_NAME:-push}
sequence=$(python3 -c 'import time; print(time.time_ns() // 1_000_000)')
if [[ $event == schedule ]]; then
channel=nightly
release_tag="nightly-$(date -u +%Y%m%d)-${GITEA_RUN_NUMBER:-$sequence}"
requested_arguments=(--nightly-sequence "$sequence")
else
release_tag=${GITEA_REF_NAME:-}
if [[ -z $release_tag || $release_tag != v* ]]; then
echo "release-component: a v* tag is required" >&2
exit 2
fi
version_from_tag=${release_tag#v}
if [[ $version_from_tag == *-* ]]; then
channel=beta
else
channel=stable
fi
requested_arguments=(--requested-version "$version_from_tag")
"$script_dir/verify-gitea-release-tag.sh" \
--tag "$release_tag" \
--event-sha "${GITEA_SHA:-$(git rev-parse HEAD)}" \
--allowed-signers "$allowed_signers" \
--notes-output "$work_root/release-notes.md" >/dev/null
fi
metadata="$work_root/release-metadata.json"
set +e
python3 "$script_dir/prepare-component-release.py" \
--registry "$root/components.json" \
--configuration "$configuration" \
--repository "$source_root" \
--feed-root "$feed_state" \
--channel "$channel" \
"${requested_arguments[@]}" \
--output "$metadata"
prepare_status=$?
set -e
if ((prepare_status == 3)) && [[ $channel == nightly ]]; then
echo "release-component: $component_id has no unpublished nightly source"
exit 0
fi
((prepare_status == 0)) || exit "$prepare_status"
component_version=$(jq -er .componentVersion "$metadata")
source_sha=$(jq -er .sourceSha "$metadata")
source_tree_hash=$(jq -er .sourceTreeHash "$metadata")
product_compatibility=$(jq -er .productCompatibility "$metadata")
abi_hash=$(jq -r '.abiHash // empty' "$metadata")
product_version=$(python3 - "$root/CMakeLists.txt" <<'PY'
import pathlib
import re
import sys
source = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")
match = re.search(
r"(?m)^project\(Echoion[ \t]+VERSION[ \t]+"
r"([0-9]+\.[0-9]+\.[0-9]+)[ \t]+LANGUAGES[ \t]+CXX\)$",
source,
)
if match is None:
raise SystemExit("release-component: cannot read Echoion product version")
print(match.group(1))
PY
)
ECHOION_COMPONENT_SSH_KEY=$ECHOION_COMPONENT_SSH_KEY \
"$script_dir/ci-checkout-components.sh" "$components" "$dependencies"
build_dependencies="$work_root/build-dependencies.json"
python3 - "$root/components.json" "$root/components.lock.json" \
"$component_id" "$build_dependencies" <<'PY'
import json
import pathlib
import sys
registry = json.loads(pathlib.Path(sys.argv[1]).read_text())
lock = json.loads(pathlib.Path(sys.argv[2]).read_text())
component = registry["components"][sys.argv[3]]
result = {}
for dependency in component["dependencies"]:
value = lock["components"][dependency]
result[dependency] = {
"componentVersion": value["componentVersion"],
"revision": value["revision"],
"abiHash": value["abiHash"],
}
pathlib.Path(sys.argv[4]).write_text(
json.dumps(result, sort_keys=True, separators=(",", ":")) + "\n"
)
PY
cmake_arguments=(
-S "$source_root"
-B "$build"
-G Ninja
-DCMAKE_BUILD_TYPE=Release
-DCMAKE_INSTALL_PREFIX="$install_root"
-DECHOION_COMPONENT_VERSION="$component_version"
-DECHOION_PRODUCT_VERSION="$product_version"
-DCPM_Void_SOURCE="$dependencies/VoidLibrary"
-DCPM_VoidTeamspeak_SOURCE="$dependencies/VoidTeamspeak"
)
while IFS= read -r dependency; do
cmake_arguments+=("-DCPM_${dependency}_SOURCE=$components/$dependency")
done < <(jq -r --arg id "$component_id" '
.components[$id].dependencies | keys[]
' "$root/components.json")
while IFS=$'\t' read -r option value; do
cmake_arguments+=("-D${option}=${value}")
done < <(jq -r '.cmakeOptions | to_entries[] | [.key, .value] | @tsv' \
"$configuration")
cmake "${cmake_arguments[@]}"
cmake --build "$build" --parallel
ctest --test-dir "$build" --output-on-failure
cmake --install "$build"
package_arguments=(
--registry "$root/components.json"
--component "$component_id"
--package-root "$install_root"
--output "$dist"
--component-version "$component_version"
--product-compatibility "$product_compatibility"
--source-sha "$source_sha"
--source-tree-hash "$source_tree_hash"
--build-dependencies "$build_dependencies"
)
if [[ -n $abi_hash ]]; then
package_arguments+=(--abi-hash "$abi_hash")
fi
SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD) \
python3 "$script_dir/package-component.py" "${package_arguments[@]}"
manifest=$(find "$dist" -maxdepth 1 -type f -name '*.manifest.json' -print)
archive=$(find "$dist" -maxdepth 1 -type f -name '*.tar.zst' -print)
[[ -f $manifest && -f $archive ]] ||
{
echo "release-component: packaging did not produce one release" >&2
exit 1
}
object_key="${ECHOION_OBJECT_STORAGE_PREFIX:-components}/$component_id/$component_version/$(basename "$archive")"
aws_arguments=()
if [[ -n ${ECHOION_OBJECT_STORAGE_ENDPOINT:-} ]]; then
aws_arguments+=(--endpoint-url "$ECHOION_OBJECT_STORAGE_ENDPOINT")
fi
set +e
aws "${aws_arguments[@]}" s3api put-object \
--bucket "$ECHOION_OBJECT_STORAGE_BUCKET" \
--key "$object_key" \
--body "$archive" \
--if-none-match '*' >/dev/null
upload_status=$?
set -e
if ((upload_status != 0)); then
existing="$work_root/existing-archive"
aws "${aws_arguments[@]}" s3api get-object \
--bucket "$ECHOION_OBJECT_STORAGE_BUCKET" \
--key "$object_key" "$existing" >/dev/null
cmp -- "$archive" "$existing" ||
{
echo "release-component: immutable object conflict: $object_key" >&2
exit 1
}
fi
verified="$work_root/verified-archive"
aws "${aws_arguments[@]}" s3api get-object \
--bucket "$ECHOION_OBJECT_STORAGE_BUCKET" \
--key "$object_key" "$verified" >/dev/null
cmp -- "$archive" "$verified"
if [[ $channel == nightly ]]; then
printf 'Automated %s nightly from %s.\n' "$component_id" "$source_sha" \
>"$work_root/release-notes.md"
fi
owner=${GITEA_REPOSITORY%%/*}
prerelease=()
if [[ $channel != stable ]]; then
prerelease+=(--prerelease)
fi
missing_tag=()
if [[ $channel == nightly ]]; then
missing_tag+=(--allow-missing-draft-tag)
fi
python3 "$script_dir/gitea_release.py" \
--api-url "$GITEA_API_URL" \
publish \
--owner "$owner" \
--repo "$repository_name" \
--tag "$release_tag" \
--target "$source_sha" \
--name "$component_id $component_version" \
--body-file "$work_root/release-notes.md" \
--artifacts "$dist" \
"${prerelease[@]}" \
"${missing_tag[@]}"
python3 "$script_dir/publish-component-release.py" \
--registry "$root/components.json" \
--component "$component_id" \
--manifest "$manifest" \
--archive "$archive" \
--feed-root "$feed_state" \
--base-url "$ECHOION_FEED_BASE_URL" \
--artifact-base-url "$ECHOION_DISTRIBUTION_BASE_URL" \
--channel "$channel" \
--sequence "$sequence" \
--valid-days 45 \
--key-id "$ECHOION_FEED_SIGNING_KEY_ID" \
--private-key "$feed_key"
git -C "$feed_state" config user.name 'Echoion Component Release Bot'
git -C "$feed_state" config user.email 'release-bot@echoion.invalid'
git -C "$feed_state" config gpg.format ssh
git -C "$feed_state" config user.signingkey "$commit_key"
git -C "$feed_state" config commit.gpgsign true
git -C "$feed_state" add feeds state
if ! git -C "$feed_state" diff --cached --quiet; then
git -C "$feed_state" commit -S -m \
"Feed: $component_id $channel $component_version"
git -C "$feed_state" cat-file commit HEAD | grep -q '^gpgsig '
git -C "$feed_state" push origin HEAD:release-feed
fi
git -C "$root" diff --exit-code -- components.lock.json
echo "release-component: published $component_id $component_version"
+69 -56
View File
@@ -10,6 +10,9 @@ Options:
--dist-dir DIR Release output directory (default: dist)
--jobs N Parallel build jobs
--skip-tests Skip CTest and frontend tests
--skip-component-packages
Build only the Echoion product artifacts; component
packages are published by their own repositories
--no-clean Reuse the configured build directory
--update-channel NAME
Component package channel (default: stable)
@@ -67,6 +70,7 @@ dist_dir="$source_dir/dist"
jobs=
run_tests=1
clean_build=1
package_components=1
use_container=1
update_channel=stable
update_sequence=
@@ -101,6 +105,10 @@ while (($#)); do
run_tests=0
shift
;;
--skip-component-packages)
package_components=0
shift
;;
--no-clean)
clean_build=0
shift
@@ -271,6 +279,7 @@ if ((use_container)); then
)
[[ -n $jobs ]] && release_args+=(--jobs "$jobs")
((run_tests)) || release_args+=(--skip-tests)
((package_components)) || release_args+=(--skip-component-packages)
((clean_build)) || release_args+=(--no-clean)
[[ -z $void_source ]] ||
release_args+=(--void-source /workspace-deps/VoidLibrary)
@@ -561,52 +570,54 @@ 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"
if ((package_components)); then
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
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 < <(
find "$component_root" -type f -print0 | LC_ALL=C sort -z
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"
)
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"
)
fi
artifact_base="echoion-${version}-linux-x86_64"
archive="$dist_dir/$artifact_base.tar.zst"
@@ -627,19 +638,21 @@ bash "$source_dir/scripts/package-release-payload.sh" \
install -m 0644 "$stage/manifest.json" "$external_manifest"
install -m 0644 "$dependency_report" "$external_report"
component_sequence=${update_sequence:-$SOURCE_DATE_EPOCH}
if [[ $component_sequence == 0 ]]; then
component_sequence=1
if ((package_components)); then
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
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"
mapfile -t checksum_files < <(
@@ -654,5 +667,5 @@ echo " $archive"
echo " $installer"
echo " $external_manifest"
echo " $external_report"
echo " $component_dist"
((package_components)) && echo " $component_dist"
echo " $dist_dir/SHA256SUMS"
+284
View File
@@ -0,0 +1,284 @@
#!/usr/bin/env python3
"""Offline tests for product-independent component release transactions."""
from __future__ import annotations
import base64
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PACKAGE = ROOT / "scripts" / "package-component.py"
PUBLISH = ROOT / "scripts" / "publish-component-release.py"
VERIFY = ROOT / "scripts" / "verify-locked-component-feeds.py"
class IndependentComponentReleaseTests(unittest.TestCase):
def setUp(self) -> None:
self.temporary = tempfile.TemporaryDirectory(
prefix="echoion-independent-component."
)
self.root = Path(self.temporary.name)
self.registry = self.root / "components.json"
self.output = self.root / "dist"
self.feed = self.root / "feed"
self.key = self.root / "key.pem"
self.public_key = self.root / "public.pem"
self.registry.write_text(
json.dumps(
{
"schemaVersion": 1,
"components": {
"EchoionApi": {
"repository": "Void/EchoionApi",
"packageId": "echoion-api",
"kind": "sdk",
"activation": "restart-required",
"dependencies": {},
},
"EchoionWeb": {
"repository": "Void/EchoionWeb",
"packageId": "echoion-web",
"kind": "runtime-module",
"activation": "restart-required",
"dependencies": {
"EchoionApi": ">=2.0.0 <3.0.0"
},
},
},
}
)
)
subprocess.run(
[
"openssl",
"genpkey",
"-algorithm",
"ED25519",
"-out",
str(self.key),
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
self.key.chmod(0o600)
subprocess.run(
[
"openssl",
"pkey",
"-in",
str(self.key),
"-pubout",
"-out",
str(self.public_key),
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def tearDown(self) -> None:
self.temporary.cleanup()
def package(self, component: str, package_id: str, version: str) -> tuple[Path, Path]:
package_root = self.root / f"stage-{component}"
package_root.mkdir()
(package_root / "payload.txt").write_text(component)
environment = os.environ.copy()
environment["SOURCE_DATE_EPOCH"] = "100"
result = subprocess.run(
[
str(PACKAGE),
"--registry",
str(self.registry),
"--component",
component,
"--package-root",
str(package_root),
"--output",
str(self.output),
"--component-version",
version,
"--source-sha",
("1" if component == "EchoionApi" else "2") * 40,
"--source-tree-hash",
"git-sha1:" + ("3" if component == "EchoionApi" else "4") * 40,
"--abi-hash",
"sha256:" + ("5" if component == "EchoionApi" else "6") * 64,
],
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=environment,
)
self.assertEqual(result.returncode, 0, result.stderr)
stem = f"{package_id}-{version}-linux-x86_64"
return (
self.output / f"{stem}.manifest.json",
self.output / f"{stem}.tar.zst",
)
def publish(
self,
component: str,
manifest: Path,
archive: Path,
sequence: int,
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[
str(PUBLISH),
"--registry",
str(self.registry),
"--component",
component,
"--manifest",
str(manifest),
"--archive",
str(archive),
"--feed-root",
str(self.feed),
"--base-url",
"https://updates.example.test/echoion",
"--artifact-base-url",
"https://downloads.example.test/components",
"--channel",
"stable",
"--sequence",
str(sequence),
"--generated-at",
"2026-07-29T12:00:00Z",
"--key-id",
"test-key",
"--private-key",
str(self.key),
],
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
@staticmethod
def payload(path: Path) -> dict[str, object]:
envelope = json.loads(path.read_text())
encoded = envelope["payload"]
raw = base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))
return json.loads(raw)
def test_single_component_publication_merges_catalog(self) -> None:
api_manifest, api_archive = self.package(
"EchoionApi", "echoion-api", "2.1.0"
)
api_result = self.publish(
"EchoionApi", api_manifest, api_archive, 100
)
self.assertEqual(api_result.returncode, 0, api_result.stderr)
web_manifest, web_archive = self.package(
"EchoionWeb", "echoion-web", "2.0.1"
)
web_result = self.publish(
"EchoionWeb", web_manifest, web_archive, 101
)
self.assertEqual(web_result.returncode, 0, web_result.stderr)
catalog = self.payload(self.feed / "feeds/stable/catalog.json")
self.assertEqual(
[item["componentId"] for item in catalog["components"]],
["EchoionApi", "EchoionWeb"],
)
api = self.payload(
self.feed / "feeds/stable/echoion-api/2.1.0.json"
)
self.assertNotIn("productVersion", api)
for private_field in (
"repository",
"repositoryUrl",
"cloneUrl",
"giteaReleaseUrl",
):
self.assertNotIn(private_field, api)
self.assertEqual(api["productCompatibility"], ">=2.0.0 <3.0.0")
self.assertEqual(
api["artifact"]["url"],
"https://downloads.example.test/components/"
"EchoionApi/2.1.0/echoion-api-2.1.0-linux-x86_64.tar.zst",
)
def test_rejects_replay_without_mutating_lock(self) -> None:
manifest, archive = self.package(
"EchoionApi", "echoion-api", "2.0.1"
)
first = self.publish("EchoionApi", manifest, archive, 200)
self.assertEqual(first.returncode, 0, first.stderr)
replay = self.publish("EchoionApi", manifest, archive, 200)
self.assertNotEqual(replay.returncode, 0)
self.assertIn("sequence is not monotonic", replay.stderr)
def test_product_lock_verifies_against_independent_feeds(self) -> None:
manifests: dict[str, Path] = {}
for sequence, component, package_id, version in (
(300, "EchoionApi", "echoion-api", "2.1.0"),
(301, "EchoionWeb", "echoion-web", "2.0.1"),
):
manifest, archive = self.package(
component, package_id, version
)
result = self.publish(component, manifest, archive, sequence)
self.assertEqual(result.returncode, 0, result.stderr)
manifests[component] = manifest
locked: dict[str, object] = {}
for component, manifest_path in manifests.items():
manifest = json.loads(manifest_path.read_text())
locked[component] = {
"componentVersion": manifest["componentVersion"],
"revision": manifest["sourceSha"],
"sourceTreeHash": manifest["sourceTreeHash"],
"abiHash": manifest["abiHash"],
"artifactIdentity": manifest["artifactIdentity"],
}
lock = self.root / "components.lock.json"
lock.write_text(
json.dumps(
{
"schemaVersion": 2,
"productVersion": "2.0.0",
"components": locked,
}
)
)
result = subprocess.run(
[
str(VERIFY),
"--registry",
str(self.registry),
"--lock",
str(lock),
"--feed-root",
str(self.feed),
"--channel",
"stable",
"--key-id",
"test-key",
"--public-key",
str(self.public_key),
],
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("verified 2 locked components", result.stdout)
if __name__ == "__main__":
unittest.main()
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Tests for independent component version derivation."""
from __future__ import annotations
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "scripts" / "prepare-component-release.py"
class PrepareComponentReleaseTests(unittest.TestCase):
def setUp(self) -> None:
self.temporary = tempfile.TemporaryDirectory(
prefix="echoion-prepare-component."
)
self.root = Path(self.temporary.name)
self.repo = self.root / "repo"
self.feed = self.root / "feed"
self.repo.mkdir()
subprocess.run(
["git", "init", "-b", "main"],
cwd=self.repo,
check=True,
stdout=subprocess.DEVNULL,
)
subprocess.run(
["git", "config", "user.email", "test@example.invalid"],
cwd=self.repo,
check=True,
)
subprocess.run(
["git", "config", "user.name", "Test"],
cwd=self.repo,
check=True,
)
(self.repo / "abi").mkdir()
self.contract = self.repo / "abi/module.json"
self.contract.write_text(
json.dumps({"schemaVersion": 1, "functions": ["create"]})
)
self.commit("initial")
self.initial_sha = self.git("rev-parse", "HEAD")
self.registry = self.root / "components.json"
self.registry.write_text(
json.dumps(
{
"schemaVersion": 1,
"components": {
"EchoionExample": {
"repository": "Void/EchoionExample",
"packageId": "echoion-example",
"kind": "runtime-module",
"activation": "restart-required",
"dependencies": {},
"abiContract": "abi/module.json",
}
},
}
)
)
self.configuration = self.root / "component.release.json"
self.configuration.write_text(
json.dumps(
{
"schemaVersion": 1,
"componentId": "EchoionExample",
"productCompatibility": ">=2.0.0 <3.0.0",
"cmakeOptions": {},
}
)
)
def tearDown(self) -> None:
self.temporary.cleanup()
def git(self, *arguments: str) -> str:
return subprocess.check_output(
["git", *arguments], cwd=self.repo, text=True
).strip()
def commit(self, message: str) -> None:
subprocess.run(["git", "add", "."], cwd=self.repo, check=True)
subprocess.run(
["git", "commit", "-m", message],
cwd=self.repo,
check=True,
stdout=subprocess.DEVNULL,
)
def state(self, version: str) -> None:
path = self.feed / "state/components/EchoionExample.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(
{
"schemaVersion": 2,
"componentId": "EchoionExample",
"lastSourceSha": self.initial_sha,
"semVer": version,
"channels": {},
}
)
)
def run_prepare(
self, version: str
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[
str(SCRIPT),
"--registry",
str(self.registry),
"--configuration",
str(self.configuration),
"--repository",
str(self.repo),
"--feed-root",
str(self.feed),
"--channel",
"stable",
"--requested-version",
version,
],
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
def test_initial_component_starts_at_2_0_0(self) -> None:
result = self.run_prepare("2.0.0")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout)["change"], "initial")
def test_append_only_contract_change_requires_minor(self) -> None:
self.state("2.0.0")
self.contract.write_text(
json.dumps(
{"schemaVersion": 1, "functions": ["create", "destroy"]}
)
)
self.commit("append")
rejected = self.run_prepare("2.0.1")
self.assertNotEqual(rejected.returncode, 0)
accepted = self.run_prepare("2.1.0")
self.assertEqual(accepted.returncode, 0, accepted.stderr)
self.assertEqual(json.loads(accepted.stdout)["change"], "minor")
def test_reordered_contract_requires_major(self) -> None:
self.state("2.2.0")
self.contract.write_text(
json.dumps({"schemaVersion": 1, "functions": ["destroy", "create"]})
)
self.commit("breaking")
accepted = self.run_prepare("3.0.0")
self.assertEqual(accepted.returncode, 0, accepted.stderr)
self.assertEqual(json.loads(accepted.stdout)["change"], "major")
if __name__ == "__main__":
unittest.main()
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
"""Verify that a product lock is fully represented by signed component feeds."""
from __future__ import annotations
import argparse
import importlib.util
from pathlib import Path
import re
from types import ModuleType
from typing import Any, NoReturn
def fail(message: str) -> NoReturn:
raise SystemExit(f"verify-locked-component-feeds: {message}")
def load_helpers() -> ModuleType:
path = Path(__file__).with_name("publish-component-feeds.py")
specification = importlib.util.spec_from_file_location(
"echoion_verify_component_feeds", path
)
if specification is None or specification.loader is None:
fail(f"cannot load shared feed helpers from {path}")
module = importlib.util.module_from_spec(specification)
specification.loader.exec_module(module)
return module
def 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("--feed-root", type=Path, required=True)
parser.add_argument(
"--channel", choices=("stable", "beta", "nightly"), default="stable"
)
parser.add_argument("--key-id", required=True)
parser.add_argument("--public-key", type=Path, required=True)
arguments = parser.parse_args()
helpers = load_helpers()
registry = helpers.load_object(arguments.registry, "component registry")
lock = helpers.load_object(arguments.lock, "component lock")
definitions = registry.get("components")
locked = lock.get("components")
if (
registry.get("schemaVersion") != 1
or lock.get("schemaVersion") != 2
or not isinstance(definitions, dict)
or not isinstance(locked, dict)
or set(definitions) != set(locked)
):
fail("unsupported or inconsistent component metadata")
feed_root = arguments.feed_root.resolve(strict=True)
verifier = helpers.PublicKeyVerifier(
arguments.public_key, arguments.key_id
)
try:
catalog_path = (
feed_root / "feeds" / arguments.channel / "catalog.json"
)
catalog = verifier.verify(
catalog_path.read_bytes(), f"{arguments.channel} catalog"
)
if (
catalog.get("schemaVersion") != 3
or catalog.get("document") != "echoion-component-catalog"
or catalog.get("channel") != arguments.channel
):
fail("catalog is not an independent component catalog")
entries = catalog.get("components")
if not isinstance(entries, list):
fail("catalog components must be an array")
catalog_by_id: dict[str, dict[str, Any]] = {}
for entry in entries:
if not isinstance(entry, dict):
fail("catalog component entry must be an object")
component_id = entry.get("componentId")
if (
not isinstance(component_id, str)
or component_id in catalog_by_id
):
fail("catalog contains an invalid or duplicate component ID")
catalog_by_id[component_id] = entry
for component_id in sorted(definitions):
definition = definitions[component_id]
expected = locked[component_id]
entry = catalog_by_id.get(component_id)
if entry is None:
fail(f"catalog is missing locked component {component_id}")
if entry.get("componentVersion") != expected["componentVersion"]:
fail(f"catalog version mismatch for {component_id}")
relative = helpers.component_path(registry, component_id)
release_path = (
feed_root
/ "feeds"
/ arguments.channel
/ relative
/ f"{expected['componentVersion']}.json"
)
release = verifier.verify(
release_path.read_bytes(), f"{component_id} release"
)
required = {
"schemaVersion": 3,
"document": "echoion-component-release",
"channel": arguments.channel,
"componentId": component_id,
"componentVersion": expected["componentVersion"],
"sourceSha": expected["revision"],
"sourceTreeHash": expected["sourceTreeHash"],
"abiHash": expected["abiHash"],
"artifactIdentity": expected["artifactIdentity"],
"activation": definition["activation"],
"dependencies": definition["dependencies"],
}
for field, value in required.items():
if release.get(field) != value:
fail(f"{component_id} release {field} does not match lock")
artifact = release.get("artifact")
if (
not isinstance(artifact, dict)
or not re.fullmatch(
r"[0-9a-f]{64}", str(artifact.get("sha256", ""))
)
or not str(artifact.get("url", "")).startswith("https://")
):
fail(f"{component_id} release artifact is invalid")
except OSError as error:
fail(f"cannot read component feed: {error}")
finally:
verifier.close()
print(
f"verified {len(definitions)} locked components in "
f"{arguments.channel}"
)
if __name__ == "__main__":
main()