Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-25 23:44:48 +03:00
1 parent 639362fbf5
commit bdd69f0aad
101 files changed
+22691 -531

No files matched your search

+478
View File
@@ -0,0 +1,478 @@
#!/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, 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_path = regular_file(arguments.new_payload, "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_document = load_json_bytes(new_payload_path.read_bytes(), "new feed payload")
new_releases = validate_payload(new_document, "new feed payload")
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_path,
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,
parse_timestamp(new_document["generatedAt"], "new feed generatedAt"),
)
if existing_document is not None:
generated = max(
generated,
parse_timestamp(
existing_document["generatedAt"], "existing feed generatedAt"
),
)
minimum_sequence = int(new_document["sequence"])
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()
+16 -2
View File
@@ -113,22 +113,36 @@ def write_manifest(root: Path, version: str, output: Path) -> None:
str(entry["path"]) for entry in entries if entry["type"] == "file"
}
executable = "bin/echoiond"
updater = "bin/echoion-updater"
core = "lib/Echoion.ts"
web_index = "share/echoion/web/index.html"
required_support = (
"share/echoion/config.example.json",
"share/echoion/tools/validate-release-manifest.py",
"service/echoion.service.in",
"service/echoion-updater.service.in",
"service/echoion-updater.timer.in",
)
for description, required in (
("executable", executable),
("updater", updater),
("Core library", core),
("web dashboard entry point", web_index),
):
if required not in regular_files:
raise ValueError(f"manifest {description} is missing: {required}")
if not os.access(root / executable, os.X_OK):
raise ValueError(f"manifest executable is not executable: {executable}")
for required in required_support:
if required not in regular_files:
raise ValueError(f"manifest installer support file is missing: {required}")
for required in (executable, updater):
if not os.access(root / required, os.X_OK):
raise ValueError(f"manifest executable is not executable: {required}")
manifest = {
"schemaVersion": 2,
"version": version,
"executable": executable,
"updater": updater,
"core": core,
"files": entries,
}
+321
View File
@@ -0,0 +1,321 @@
#!/usr/bin/env python3
"""Generate an Echoion component feed payload and optional signature envelope."""
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 NoReturn
SAFE_TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$")
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-]+)*)?$"
)
def fail(message: str) -> NoReturn:
raise SystemExit(f"generate-update-feed: {message}")
def regular_file(path: Path, description: str) -> Path:
try:
metadata = path.lstat()
except OSError as error:
fail(f"cannot inspect {description} {path}: {error}")
if not stat.S_ISREG(metadata.st_mode) or path.is_symlink():
fail(f"{description} is not a regular file: {path}")
return path.resolve(strict=True)
def digest(path: Path) -> str:
result = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
result.update(chunk)
return result.hexdigest()
def timestamp(value: str, label: str) -> datetime:
if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", 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 parse_contract(values: list[str], label: str) -> dict[str, str]:
result: dict[str, str] = {}
for value in values:
name, separator, contract = value.partition("=")
if (
not separator
or not SAFE_TOKEN.fullmatch(name)
or not contract
or any(character in contract for character in "\r\n\0")
or name in result
):
fail(f"invalid or duplicate {label}: {value!r}")
result[name] = contract
return dict(sorted(result.items()))
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)
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
finally:
if descriptor >= 0:
os.close(descriptor)
temporary.unlink(missing_ok=True)
def urlsafe(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def sign_payload(payload: Path, private_key: Path) -> bytes:
with tempfile.NamedTemporaryFile(prefix="echoion-feed-signature.") as signature:
command = [
"openssl",
"pkeyutl",
"-sign",
"-rawin",
"-inkey",
os.fspath(private_key),
"-in",
os.fspath(payload),
"-out",
signature.name,
]
try:
completed = subprocess.run(
command,
check=False,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFoundError:
fail("openssl is required to sign an update feed")
if completed.returncode != 0:
detail = completed.stderr.decode("utf-8", errors="replace").strip()
fail(f"OpenSSL could not sign the feed: {detail}")
value = Path(signature.name).read_bytes()
if len(value) != 64:
fail(f"OpenSSL returned an invalid Ed25519 signature size: {len(value)}")
return value
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--artifact", type=Path, required=True)
parser.add_argument("--manifest", type=Path)
parser.add_argument("--component", default="runtime")
parser.add_argument("--artifact-id", default="")
parser.add_argument("--package-type")
parser.add_argument("--version", required=True)
parser.add_argument("--url", required=True)
parser.add_argument("--channel", default="stable")
parser.add_argument("--feed-id", default="echoion-runtime")
parser.add_argument("--sequence", type=int)
parser.add_argument("--generated-at")
parser.add_argument("--expires-at")
parser.add_argument("--valid-days", type=int, default=30)
parser.add_argument("--cohort", default="linux-glibc-2.35")
parser.add_argument("--platform", default="linux")
parser.add_argument("--architecture", default="x86_64")
parser.add_argument("--version-contract", action="append", default=[])
parser.add_argument("--exact-contract", action="append", default=[])
parser.add_argument("--output-payload", type=Path, required=True)
parser.add_argument("--output-envelope", type=Path)
parser.add_argument("--key-id")
parser.add_argument("--private-key", type=Path)
arguments = parser.parse_args()
for label, value in (
("feed id", arguments.feed_id),
("component", arguments.component),
("channel", arguments.channel),
("cohort", arguments.cohort),
("platform", arguments.platform),
("architecture", arguments.architecture),
):
if not SAFE_TOKEN.fullmatch(value):
fail(f"invalid {label}: {value!r}")
if arguments.artifact_id and not SAFE_TOKEN.fullmatch(arguments.artifact_id):
fail(f"invalid artifact id: {arguments.artifact_id!r}")
package_type = arguments.package_type or (
"tar.zst"
if arguments.component in {"runtime", "executable"}
else "shared-library"
)
if not SAFE_TOKEN.fullmatch(package_type):
fail(f"invalid package type: {package_type!r}")
if arguments.component in {"plugin", "plugins"} and not arguments.artifact_id:
fail("plugin feeds require --artifact-id")
if not SEMVER.fullmatch(arguments.version):
fail(f"version is not strict SemVer: {arguments.version!r}")
if not arguments.url or any(
character in arguments.url for character in "\r\n\0"
):
fail("artifact URL is empty or contains a control character")
if arguments.valid_days < 1 or arguments.valid_days > 365:
fail("--valid-days must be between 1 and 365")
artifact = regular_file(arguments.artifact, f"{arguments.component} artifact")
manifest_path = (
regular_file(arguments.manifest, "release manifest")
if arguments.manifest
else None
)
if arguments.component in {"runtime", "executable"}:
if manifest_path is None:
fail("runtime feeds require --manifest")
try:
with manifest_path.open(encoding="utf-8") as stream:
manifest = json.load(stream)
except (OSError, json.JSONDecodeError) as error:
fail(f"cannot parse release manifest: {error}")
if (
not isinstance(manifest, dict)
or manifest.get("schemaVersion") != 2
or manifest.get("version") != arguments.version
):
fail("release manifest schema/version does not match the feed")
source_epoch = os.environ.get("SOURCE_DATE_EPOCH")
if arguments.generated_at:
generated = timestamp(arguments.generated_at, "generated timestamp")
elif source_epoch is not None and source_epoch.isdigit():
generated = datetime.fromtimestamp(int(source_epoch), timezone.utc)
else:
generated = datetime.now(timezone.utc).replace(microsecond=0)
expires = (
timestamp(arguments.expires_at, "expiry timestamp")
if arguments.expires_at
else generated + timedelta(days=arguments.valid_days)
)
if expires <= generated:
fail("feed expiry must be after its generated timestamp")
sequence = arguments.sequence
if sequence is None:
sequence = int(generated.timestamp())
if sequence < 0 or sequence > (1 << 64) - 1:
fail("feed sequence is outside the uint64 range")
release = {
"component": arguments.component,
"artifactId": arguments.artifact_id,
"channel": arguments.channel,
"version": arguments.version,
"cohort": arguments.cohort,
"platform": arguments.platform,
"arch": arguments.architecture,
"url": arguments.url,
"size": artifact.stat().st_size,
"sha256": digest(artifact),
"packageType": package_type,
"compatibility": {
"versionContracts": parse_contract(
arguments.version_contract, "version contract"
),
"exactContracts": parse_contract(
arguments.exact_contract, "exact contract"
),
},
}
if manifest_path is not None:
release["releaseManifestSha256"] = digest(manifest_path)
payload_document = {
"schemaVersion": 1,
"feedId": arguments.feed_id,
"sequence": sequence,
"generatedAt": format_timestamp(generated),
"expiresAt": format_timestamp(expires),
"releases": [release],
}
payload = (
json.dumps(payload_document, ensure_ascii=False, indent=2).encode("utf-8")
+ b"\n"
)
output_payload = arguments.output_payload.resolve()
forbidden = {artifact}
if manifest_path is not None:
forbidden.add(manifest_path)
if arguments.private_key:
private_key = regular_file(arguments.private_key, "Ed25519 private key")
if private_key.stat().st_mode & 0o077:
fail("Ed25519 private key must not be accessible by group or others")
forbidden.add(private_key)
else:
private_key = None
if output_payload in forbidden:
fail("output payload would overwrite an input file")
atomic_write(output_payload, payload)
signing_requested = any(
value is not None
for value in (arguments.output_envelope, arguments.key_id, private_key)
)
if not signing_requested:
return
if not arguments.output_envelope or not arguments.key_id or not private_key:
fail("--output-envelope, --key-id, and --private-key are required together")
if not SAFE_TOKEN.fullmatch(arguments.key_id):
fail(f"invalid signing key id: {arguments.key_id!r}")
output_envelope = arguments.output_envelope.resolve()
if output_envelope in forbidden or output_envelope == output_payload:
fail("output envelope would overwrite an input or payload file")
signature = sign_payload(output_payload, private_key)
envelope = {
"schemaVersion": 1,
"keyId": arguments.key_id,
"payload": urlsafe(payload),
"signature": urlsafe(signature),
}
atomic_write(
output_envelope,
json.dumps(envelope, ensure_ascii=False, indent=2).encode("utf-8") + b"\n",
)
if __name__ == "__main__":
main()
+632
View File
@@ -0,0 +1,632 @@
#!/usr/bin/env python3
"""Publish verified, idempotent Gitea releases and prune old nightlies."""
from __future__ import annotations
import argparse
import hashlib
import http.client
import json
import mimetypes
import os
from pathlib import Path
import re
import secrets
import stat
import sys
from typing import Any, NoReturn
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode, urljoin, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
MAX_JSON_BYTES = 8 * 1024 * 1024
UPLOAD_CHUNK_BYTES = 1024 * 1024
SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,255}$")
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *_args: Any, **_kwargs: Any) -> None:
return None
def fail(message: str) -> NoReturn:
raise SystemExit(f"gitea-release: {message}")
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(UPLOAD_CHUNK_BYTES), b""):
digest.update(chunk)
return digest.hexdigest()
def validate_regular_file(path: Path) -> Path:
try:
metadata = path.lstat()
except OSError as error:
fail(f"cannot inspect artifact {path}: {error}")
if not stat.S_ISREG(metadata.st_mode) or path.is_symlink():
fail(f"artifact is not a regular file: {path}")
if not SAFE_NAME.fullmatch(path.name):
fail(f"artifact has an unsafe filename: {path}")
return path.resolve(strict=True)
class GiteaApi:
def __init__(
self,
base_url: str,
token: str,
*,
allow_http: bool = False,
timeout_seconds: int = 120,
) -> None:
self.base_url = base_url.rstrip("/") + "/"
parsed = urlsplit(self.base_url)
loopback = parsed.hostname in {"127.0.0.1", "::1", "localhost"}
if parsed.scheme != "https" and not (
allow_http and parsed.scheme == "http" and loopback
):
fail("the Gitea API URL must use HTTPS")
if (
not parsed.hostname
or parsed.username
or parsed.password
or parsed.query
or parsed.fragment
):
fail("the Gitea API URL is malformed or contains credentials")
if not token or any(character in token for character in "\r\n\0"):
fail("the release token is empty or contains a control character")
self._parsed = parsed
self._token = token
self._timeout_seconds = timeout_seconds
self._opener = build_opener(NoRedirect)
def url(self, path: str) -> str:
return urljoin(self.base_url, path.lstrip("/"))
@property
def headers(self) -> dict[str, str]:
return {
"Accept": "application/json",
"Authorization": f"token {self._token}",
"User-Agent": "echoion-gitea-release/1",
}
def request_json(
self,
method: str,
path: str,
document: dict[str, Any] | None = None,
*,
allowed_statuses: tuple[int, ...] = (200,),
) -> tuple[int, Any | None]:
body = None
headers = self.headers
if document is not None:
body = json.dumps(document, separators=(",", ":")).encode("utf-8")
headers = {**headers, "Content-Type": "application/json"}
request = Request(self.url(path), data=body, headers=headers, method=method)
try:
with self._opener.open(request, timeout=self._timeout_seconds) as response:
status = response.status
content = response.read(MAX_JSON_BYTES + 1)
except HTTPError as error:
status = error.code
content = error.read(64 * 1024)
except (OSError, URLError) as error:
fail(f"{method} {path} failed: {error}")
if status not in allowed_statuses:
detail = content.decode("utf-8", errors="replace").strip()
fail(f"{method} {path} returned HTTP {status}: {detail[:1000]}")
if len(content) > MAX_JSON_BYTES:
fail(f"{method} {path} returned an oversized JSON response")
if not content:
return status, None
try:
return status, json.loads(content)
except json.JSONDecodeError as error:
fail(f"{method} {path} returned invalid JSON: {error}")
def upload_asset(self, release_id: int, artifact: Path) -> dict[str, Any]:
boundary = f"echoion-{secrets.token_hex(24)}"
mime_type = mimetypes.guess_type(artifact.name)[0] or "application/octet-stream"
prefix = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="attachment"; '
f'filename="{artifact.name}"\r\n'
f"Content-Type: {mime_type}\r\n\r\n"
).encode("utf-8")
suffix = f"\r\n--{boundary}--\r\n".encode("ascii")
content_length = len(prefix) + artifact.stat().st_size + len(suffix)
query = urlencode({"name": artifact.name})
relative = (
f"repos/{quote_owner(self.owner)}/{quote_owner(self.repo)}/releases/"
f"{release_id}/assets?{query}"
)
target = urlsplit(self.url(relative))
connection_type = (
http.client.HTTPSConnection
if target.scheme == "https"
else http.client.HTTPConnection
)
connection = connection_type(
target.hostname,
target.port,
timeout=self._timeout_seconds,
)
try:
request_target = target.path + (f"?{target.query}" if target.query else "")
connection.putrequest("POST", request_target)
for name, value in self.headers.items():
connection.putheader(name, value)
connection.putheader("Content-Type", f"multipart/form-data; boundary={boundary}")
connection.putheader("Content-Length", str(content_length))
connection.endheaders()
connection.send(prefix)
with artifact.open("rb") as stream:
for chunk in iter(lambda: stream.read(UPLOAD_CHUNK_BYTES), b""):
connection.send(chunk)
connection.send(suffix)
response = connection.getresponse()
content = response.read(MAX_JSON_BYTES + 1)
status = response.status
except OSError as error:
fail(f"uploading {artifact.name} failed: {error}")
finally:
connection.close()
if status != 201:
detail = content.decode("utf-8", errors="replace").strip()
fail(f"uploading {artifact.name} returned HTTP {status}: {detail[:1000]}")
if len(content) > MAX_JSON_BYTES:
fail(f"uploading {artifact.name} returned oversized JSON")
try:
result = json.loads(content)
except json.JSONDecodeError as error:
fail(f"uploading {artifact.name} returned invalid JSON: {error}")
if not isinstance(result, dict):
fail(f"uploading {artifact.name} returned an invalid asset")
return result
def bind_repository(self, owner: str, repo: str) -> None:
self.owner = owner
self.repo = repo
def remote_sha256(self, download_url: str) -> tuple[int, str]:
target = urljoin(self.base_url, download_url)
parsed = urlsplit(target)
base = self._parsed
parsed_port = parsed.port or (443 if parsed.scheme == "https" else 80)
base_port = base.port or (443 if base.scheme == "https" else 80)
if (
parsed.scheme != base.scheme
or parsed.hostname != base.hostname
or parsed_port != base_port
or parsed.username
or parsed.password
or parsed.fragment
):
fail(f"Gitea returned an untrusted asset URL: {download_url!r}")
request = Request(target, headers=self.headers, method="GET")
result = hashlib.sha256()
size = 0
try:
with self._opener.open(request, timeout=self._timeout_seconds) as response:
if response.status != 200:
fail(f"downloading an asset returned HTTP {response.status}")
while chunk := response.read(UPLOAD_CHUNK_BYTES):
size += len(chunk)
result.update(chunk)
except (HTTPError, OSError, URLError) as error:
fail(f"downloading an asset for verification failed: {error}")
return size, result.hexdigest()
def quote_owner(value: str) -> str:
if not SAFE_NAME.fullmatch(value):
fail(f"invalid repository name: {value!r}")
return quote(value, safe="")
def repository_path(owner: str, repo: str) -> str:
return f"repos/{quote_owner(owner)}/{quote_owner(repo)}"
def load_artifacts(directory: Path) -> dict[str, Path]:
try:
entries = list(directory.iterdir())
except OSError as error:
fail(f"cannot enumerate artifact directory {directory}: {error}")
artifacts: dict[str, Path] = {}
for entry in sorted(entries, key=lambda value: value.name):
path = validate_regular_file(entry)
if path.name in artifacts:
fail(f"duplicate artifact filename: {path.name}")
artifacts[path.name] = path
if not artifacts:
fail("the artifact directory is empty")
return artifacts
def release_body(arguments: argparse.Namespace) -> str:
if arguments.body_file is None:
body = arguments.body
if "\0" in body or len(body.encode("utf-8")) > 1024 * 1024:
fail("the release body is invalid or too large")
return body
path = validate_regular_file(arguments.body_file)
if path.stat().st_size > 1024 * 1024:
fail("the release body file is too large")
try:
body = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as error:
fail(f"cannot read release body file {path}: {error}")
if "\0" in body:
fail("the release body contains a NUL byte")
return body
def release_assets(release: dict[str, Any]) -> list[dict[str, Any]]:
assets = release.get("assets", [])
if not isinstance(assets, list) or not all(isinstance(asset, dict) for asset in assets):
fail("Gitea returned an invalid release asset list")
return assets
def verify_assets(
api: GiteaApi,
release: dict[str, Any],
artifacts: dict[str, Path],
) -> None:
remote: dict[str, dict[str, Any]] = {}
for asset in release_assets(release):
name = asset.get("name")
if not isinstance(name, str) or not name or name in remote:
fail("Gitea returned missing or duplicate release asset names")
remote[name] = asset
if set(remote) != set(artifacts):
missing = sorted(set(artifacts) - set(remote))
extra = sorted(set(remote) - set(artifacts))
fail(f"release asset set mismatch (missing={missing}, extra={extra})")
for name, path in artifacts.items():
asset = remote[name]
download_url = asset.get("browser_download_url")
if not isinstance(download_url, str) or not download_url:
fail(f"Gitea returned no download URL for {name}")
expected_size = path.stat().st_size
if asset.get("size") != expected_size:
fail(f"Gitea metadata size mismatch for {name}")
actual_size, actual_hash = api.remote_sha256(download_url)
if actual_size != expected_size or actual_hash != sha256(path):
fail(f"download verification failed for {name}")
def verify_release_metadata(
release: dict[str, Any],
*,
tag: str,
name: str,
body: str,
prerelease: bool,
) -> None:
expected = {
"tag_name": tag,
"name": name,
"body": body,
"prerelease": prerelease,
}
mismatched = [field for field, value in expected.items() if release.get(field) != value]
if mismatched:
fail(f"release metadata mismatch: {', '.join(mismatched)}")
def verify_tag_target(
api: GiteaApi, base: str, tag: str, expected_commit: str
) -> None:
_, document = api.request_json(
"GET", f"{base}/tags/{quote(tag, safe='')}", allowed_statuses=(200,)
)
if (
not isinstance(document, dict)
or not isinstance(document.get("commit"), dict)
or document["commit"].get("sha") != expected_commit
):
fail("the release tag does not target the requested commit")
def publish(arguments: argparse.Namespace, api: GiteaApi) -> None:
owner = arguments.owner
repo = arguments.repo
api.bind_repository(owner, repo)
base = repository_path(owner, repo)
artifacts = load_artifacts(arguments.artifacts)
body = release_body(arguments)
tag = arguments.tag
if not SAFE_NAME.fullmatch(tag):
fail("the release tag is invalid")
if not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", arguments.target):
fail("the release target must be a full commit object id")
if (
not arguments.name
or len(arguments.name) > 255
or any(character in arguments.name for character in "\r\n\0")
):
fail("the release name is invalid")
tag_path = quote(tag, safe="")
status, release = api.request_json(
"GET",
f"{base}/releases/tags/{tag_path}",
allowed_statuses=(200, 404),
)
if status == 404:
_, release = api.request_json(
"POST",
f"{base}/releases",
{
"tag_name": tag,
"target_commitish": arguments.target,
"name": arguments.name,
"body": body,
"draft": True,
"prerelease": arguments.prerelease,
},
allowed_statuses=(201,),
)
if not isinstance(release, dict) or not isinstance(release.get("id"), int):
fail("Gitea returned an invalid release")
if release.get("tag_name") != tag:
fail("Gitea returned a release for the wrong tag")
verify_tag_target(api, base, tag, arguments.target)
release_id = release["id"]
if not release.get("draft", False):
verify_release_metadata(
release,
tag=tag,
name=arguments.name,
body=body,
prerelease=arguments.prerelease,
)
verify_assets(api, release, artifacts)
print(f"release {tag} is already published and verified")
return
api.request_json(
"PATCH",
f"{base}/releases/{release_id}",
{
"name": arguments.name,
"body": body,
"draft": True,
"prerelease": arguments.prerelease,
"target_commitish": arguments.target,
},
allowed_statuses=(200,),
)
for asset in release_assets(release):
asset_id = asset.get("id")
if not isinstance(asset_id, int):
fail("Gitea returned an invalid release asset id")
api.request_json(
"DELETE",
f"{base}/releases/{release_id}/assets/{asset_id}",
allowed_statuses=(204, 404),
)
for artifact in artifacts.values():
api.upload_asset(release_id, artifact)
_, release = api.request_json(
"GET", f"{base}/releases/{release_id}", allowed_statuses=(200,)
)
if not isinstance(release, dict):
fail("Gitea returned an invalid release after upload")
verify_release_metadata(
release,
tag=tag,
name=arguments.name,
body=body,
prerelease=arguments.prerelease,
)
verify_assets(api, release, artifacts)
_, release = api.request_json(
"PATCH",
f"{base}/releases/{release_id}",
{
"name": arguments.name,
"body": body,
"draft": False,
"prerelease": arguments.prerelease,
"target_commitish": arguments.target,
},
allowed_statuses=(200,),
)
if not isinstance(release, dict) or release.get("draft", True):
fail("Gitea did not publish the verified draft")
verify_release_metadata(
release,
tag=tag,
name=arguments.name,
body=body,
prerelease=arguments.prerelease,
)
verify_tag_target(api, base, tag, arguments.target)
print(f"published and verified release {tag} with {len(artifacts)} assets")
def prune_nightlies(arguments: argparse.Namespace, api: GiteaApi) -> None:
base = repository_path(arguments.owner, arguments.repo)
releases: list[dict[str, Any]] = []
page = 1
while True:
query = urlencode({"limit": 50, "page": page})
_, batch = api.request_json(
"GET", f"{base}/releases?{query}", allowed_statuses=(200,)
)
if not isinstance(batch, list) or not all(
isinstance(release, dict) for release in batch
):
fail("Gitea returned an invalid release page")
releases.extend(batch)
if len(batch) < 50:
break
page += 1
if page > 1000:
fail("Gitea release pagination exceeded the safety limit")
nightlies = [
release
for release in releases
if release.get("prerelease") is True
and isinstance(release.get("tag_name"), str)
and release["tag_name"].startswith(arguments.tag_prefix)
]
nightlies.sort(
key=lambda release: (
str(release.get("published_at") or release.get("created_at") or ""),
int(release.get("id", -1)),
),
reverse=True,
)
release_ids: set[int] = set()
for release in nightlies:
release_id = release.get("id")
if not isinstance(release_id, int) or release_id in release_ids:
fail("Gitea returned a missing or duplicate nightly release id")
release_ids.add(release_id)
protected = [
release
for release in nightlies
if release["tag_name"] == arguments.protect_tag
]
if len(protected) > 1:
fail("Gitea returned duplicate releases for the protected nightly tag")
ordered_to_keep = [
*protected,
*[
release
for release in nightlies
if not protected or release["id"] != protected[0]["id"]
],
]
retained_ids = {
release["id"] for release in ordered_to_keep[: arguments.keep]
}
deleted = 0
for release in nightlies:
tag = release["tag_name"]
release_id = release["id"]
if release_id in retained_ids:
continue
api.request_json(
"DELETE",
f"{base}/tags/{quote(tag, safe='')}",
allowed_statuses=(204, 404),
)
api.request_json(
"DELETE",
f"{base}/releases/{release_id}",
allowed_statuses=(204, 404),
)
deleted += 1
print(f"kept {len(retained_ids)} nightly releases and deleted {deleted}")
def verify_tag_protection(arguments: argparse.Namespace, api: GiteaApi) -> None:
base = repository_path(arguments.owner, arguments.repo)
_, protections = api.request_json(
"GET", f"{base}/tag_protections", allowed_statuses=(200,)
)
if not isinstance(protections, list) or not all(
isinstance(protection, dict) for protection in protections
):
fail("Gitea returned an invalid tag-protection list")
matches = [
protection
for protection in protections
if protection.get("name_pattern") == arguments.required_pattern
]
if not matches:
fail(f"required protected tag pattern is missing: {arguments.required_pattern}")
if len(matches) != 1:
fail(
"required protected tag pattern is ambiguous: "
f"{arguments.required_pattern}"
)
protection = matches[0]
users = protection.get("whitelist_usernames")
teams = protection.get("whitelist_teams")
if (
not isinstance(users, list)
or not all(isinstance(value, str) and value for value in users)
or not isinstance(teams, list)
or not all(isinstance(value, str) and value for value in teams)
):
fail("Gitea returned an invalid protected-tag allowlist")
if not users and not teams:
fail("the required protected tag pattern has an empty allowlist")
print(
f"verified protected tag pattern {arguments.required_pattern} "
f"(users={len(users)}, teams={len(teams)})"
)
def parser() -> argparse.ArgumentParser:
result = argparse.ArgumentParser(description=__doc__)
result.add_argument("--api-url", required=True)
result.add_argument("--token-env", default="GITEA_RELEASE_TOKEN")
result.add_argument("--allow-http", action="store_true", help=argparse.SUPPRESS)
subparsers = result.add_subparsers(dest="command", required=True)
publish_parser = subparsers.add_parser("publish")
publish_parser.add_argument("--owner", required=True)
publish_parser.add_argument("--repo", required=True)
publish_parser.add_argument("--tag", required=True)
publish_parser.add_argument("--target", required=True)
publish_parser.add_argument("--name", required=True)
body_group = publish_parser.add_mutually_exclusive_group()
body_group.add_argument("--body", default="")
body_group.add_argument("--body-file", type=Path)
publish_parser.add_argument("--artifacts", type=Path, required=True)
publish_parser.add_argument("--prerelease", action="store_true")
prune_parser = subparsers.add_parser("prune-nightlies")
prune_parser.add_argument("--owner", required=True)
prune_parser.add_argument("--repo", required=True)
prune_parser.add_argument("--tag-prefix", default="nightly-")
prune_parser.add_argument("--keep", type=int, default=14)
prune_parser.add_argument("--protect-tag", default="")
protection_parser = subparsers.add_parser("verify-tag-protection")
protection_parser.add_argument("--owner", required=True)
protection_parser.add_argument("--repo", required=True)
protection_parser.add_argument("--required-pattern", default="v*")
return result
def main() -> None:
arguments = parser().parse_args()
if arguments.command == "prune-nightlies" and arguments.keep < 1:
fail("--keep must be positive")
if arguments.command == "prune-nightlies":
if not SAFE_NAME.fullmatch(arguments.tag_prefix):
fail("--tag-prefix must be a non-empty safe tag prefix")
if (
arguments.protect_tag
and not arguments.protect_tag.startswith(arguments.tag_prefix)
):
fail("--protect-tag must start with --tag-prefix")
token = os.environ.get(arguments.token_env, "")
api = GiteaApi(arguments.api_url, token, allow_http=arguments.allow_http)
if arguments.command == "publish":
publish(arguments, api)
elif arguments.command == "prune-nightlies":
prune_nightlies(arguments, api)
else:
verify_tag_protection(arguments, api)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)
+22 -5
View File
@@ -25,7 +25,8 @@ work_dir=$(realpath -m -- "$6")
echo "stage is missing executable installer helpers" >&2
exit 2
}
[[ -f $stage/manifest.json && -x $stage/bin/echoiond && -f $stage/lib/Echoion.ts ]] || {
[[ -f $stage/manifest.json && -x $stage/bin/echoiond &&
-x $stage/bin/echoion-updater && -f $stage/lib/Echoion.ts ]] || {
echo "stage is missing required Echoion payload files" >&2
exit 2
}
@@ -55,6 +56,7 @@ tar -C "$stage" "${tar_options[@]}" \
--transform="s,^\\./,$artifact_base/," \
-cf - . |
zstd -T1 -19 --no-progress -o "$archive_tmp"
chmod 0644 "$archive_tmp"
mv -f -- "$archive_tmp" "$archive"
tar -C "$stage" "${tar_options[@]}" -cf - . | gzip -n -9 >"$gzip_payload"
@@ -65,13 +67,29 @@ set -eu
self=$0
case $self in
/*) ;;
*) self=$(pwd)/$self ;;
*/*)
self_directory=$(CDPATH= cd -P -- "$(dirname -- "$self")" && pwd -P)
self=$self_directory/$(basename -- "$self")
;;
*)
self=$(command -v "$self") || {
echo "Cannot locate Echoion installer: $0" >&2
exit 2
}
case $self in
/*) ;;
*) self=$(pwd)/$self ;;
esac
;;
esac
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-installer.XXXXXX")
cleanup() {
rm -rf -- "$temporary"
}
trap cleanup EXIT HUP INT TERM
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
payload_line=$(awk '/^__ECHOION_PAYLOAD_BELOW__$/ { print NR + 1; exit }' "$self")
if [ -z "$payload_line" ]; then
echo "Echoion installer payload marker is missing" >&2
@@ -80,8 +98,7 @@ fi
tail -n "+$payload_line" "$self" |
tar --same-permissions --no-same-owner -xzf - -C "$temporary"
"$temporary/install.sh" "$@"
status=$?
exit "$status"
exit 0
__ECHOION_PAYLOAD_BELOW__
RUN_HEADER
cat "$header" "$gzip_payload" >"$installer_tmp"
+227 -10
View File
@@ -11,6 +11,20 @@ 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)
--update-sequence N
Monotonic feed sequence (default: SOURCE_DATE_EPOCH)
--update-valid-days N
Feed lifetime in days (default: 30)
--official-update-feed-url URL
HTTPS aggregate feed embedded as the official default
--void-source DIR Use an explicit VoidLibrary source tree
--void-teamspeak-source DIR
Use an explicit VoidTeamspeak source tree
--container Build with containers/release.Dockerfile (the default)
--host Explicitly build directly on this host
-h, --help Show this help
@@ -24,6 +38,26 @@ die() {
exit 2
}
canonical_release_version() {
local value=$1
local prerelease identifier
if [[ ! $value =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$ ]]; then
return 1
fi
prerelease=${BASH_REMATCH[5]:-}
while [[ -n $prerelease ]]; do
if [[ $prerelease == *.* ]]; then
identifier=${prerelease%%.*}
prerelease=${prerelease#*.}
else
identifier=$prerelease
prerelease=
fi
[[ ! $identifier =~ ^0[0-9]+$ ]] || return 1
done
return 0
}
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
source_dir=$(cd -- "$script_dir/.." && pwd -P)
version=
@@ -33,6 +67,14 @@ 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=
while (($#)); do
case $1 in
@@ -64,6 +106,46 @@ 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
shift 2
;;
--void-source)
(($# >= 2)) || die "--void-source requires a value"
void_source=$2
shift 2
;;
--void-teamspeak-source)
(($# >= 2)) || die "--void-teamspeak-source requires a value"
void_teamspeak_source=$2
shift 2
;;
--container)
use_container=1
shift
@@ -84,12 +166,35 @@ done
[[ $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] ||
die "--version must contain only letters, digits, dot, underscore, or dash"
canonical_release_version "$version" ||
die "--version must be canonical Semantic Versioning 2.0.0"
if [[ -n $jobs && ! $jobs =~ ^[1-9][0-9]*$ ]]; then
die "--jobs must be a positive integer"
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")
if [[ -n $void_source ]]; then
void_source=$(realpath -e -- "$void_source")
[[ -d $void_source && -f $void_source/CMakeLists.txt ]] ||
die "--void-source must name a VoidLibrary source directory"
fi
if [[ -n $void_teamspeak_source ]]; then
void_teamspeak_source=$(realpath -e -- "$void_teamspeak_source")
[[ -d $void_teamspeak_source && -f $void_teamspeak_source/CMakeLists.txt ]] ||
die "--void-teamspeak-source must name a VoidTeamspeak source directory"
fi
container_path() {
local path=$1
@@ -105,7 +210,18 @@ if ((use_container)); then
container_build_dir=$(container_path "$build_dir")
container_dist_dir=$(container_path "$dist_dir")
image="echoion-release-builder:gcc-16.1.0"
proxy_build_args=()
proxy_run_args=()
for proxy_name in HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy; do
if [[ -n ${!proxy_name:-} ]]; then
# Docker treats these predefined build arguments specially: their
# values are inherited without being recorded in the image history.
proxy_build_args+=(--build-arg "$proxy_name")
proxy_run_args+=(--env "$proxy_name")
fi
done
docker build \
"${proxy_build_args[@]}" \
--platform linux/amd64 \
--file "$source_dir/containers/release.Dockerfile" \
--tag "$image" \
@@ -118,6 +234,17 @@ if ((use_container)); then
--env HOME=/tmp/echoion-release-home
--env npm_config_cache=/tmp/echoion-npm-cache
)
container_args+=("${proxy_run_args[@]}")
if [[ -n $void_source ]]; then
container_args+=(
--volume "$void_source:/workspace-deps/VoidLibrary:ro"
)
fi
if [[ -n $void_teamspeak_source ]]; then
container_args+=(
--volume "$void_teamspeak_source:/workspace-deps/VoidTeamspeak:ro"
)
fi
if [[ -n ${SOURCE_DATE_EPOCH:-} ]]; then
container_args+=(--env "SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH")
fi
@@ -130,6 +257,24 @@ if ((use_container)); then
[[ -n $jobs ]] && release_args+=(--jobs "$jobs")
((run_tests)) || release_args+=(--skip-tests)
((clean_build)) || release_args+=(--no-clean)
[[ -z $void_source ]] ||
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
[[ -z $official_update_feed_url ]] ||
release_args+=(
--official-update-feed-url "$official_update_feed_url"
)
docker run --platform linux/amd64 "${container_args[@]}" "$image" \
bash scripts/release.sh "${release_args[@]}"
exit
@@ -141,12 +286,14 @@ case "$(uname -s)/$(uname -m)" in
esac
required_commands=(
cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum
cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum openssl
dpkg-query ldconfig
)
for command_name in "${required_commands[@]}"; do
command -v "$command_name" >/dev/null || die "required command not found: $command_name"
done
python3 "$source_dir/scripts/validate-semver.py" "$version" ||
die "--version must be canonical Semantic Versioning 2.0.0"
[[ -x $source_dir/packaging/install.sh ]] ||
die "installer source is missing: packaging/install.sh"
[[ -x $source_dir/packaging/uninstall.sh ]] ||
@@ -174,7 +321,30 @@ if ((clean_build)); then
fi
mkdir -p "$build_dir"
configure_args=(--preset linux-release -B "$build_dir")
configure_args=(
--preset linux-release
-B "$build_dir"
-DBUILD_SHARED_LIBS=ON
-DECHOION_STATIC_LINK=OFF
-DECHOION_REPRODUCIBLE_BUILD=ON
"-DECHOION_RUNTIME_VERSION=$version"
)
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"
official_update_keys_json=$(
python3 -c \
'import json,sys; print(json.dumps(json.load(open(sys.argv[1], encoding="utf-8")), separators=(",", ":")))' \
"$official_update_keys"
) || die "official update trust store is invalid"
configure_args+=(
"-DECHOION_UPDATE_PUBLIC_KEYS_JSON=$official_update_keys_json"
"-DECHOION_UPDATE_FEED_URL=$official_update_feed_url"
)
[[ -z $void_source ]] ||
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"
(
@@ -216,20 +386,47 @@ for runtime_name in libstdc++.so.6 libgcc_s.so.1; do
done
search_directories=$(IFS=';'; echo "${library_directories[*]}")
compiler_runtimes=$(IFS=';'; echo "${compiler_runtime_files[*]}")
resolver_libraries=("$build_dir/lib/Echoion.ts")
if [[ -d $stage/share/echoion/bootstrap-plugins ]]; then
while IFS= read -r -d '' plugin_library; do
resolver_libraries+=("$plugin_library")
done < <(
find "$stage/share/echoion/bootstrap-plugins" -type f -name '*.so' \
-print0 | LC_ALL=C sort -z
)
fi
resolver_library_list=$(IFS=';'; echo "${resolver_libraries[*]}")
cmake \
"-DBUNDLE_ROOT=$stage" \
"-DBUNDLE_RESOLVER_EXECUTABLE=$build_dir/bin/echoiond" \
"-DBUNDLE_RESOLVER_LIBRARIES=$build_dir/lib/Echoion.ts" \
"-DBUNDLE_RESOLVER_EXECUTABLES=$build_dir/bin/echoiond;$build_dir/bin/echoion-updater" \
"-DBUNDLE_RESOLVER_LIBRARIES=$resolver_library_list" \
"-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \
"-DBUNDLE_SEED_FILES=$compiler_runtimes" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_dir/cmake/BundleRuntimeDependencies.cmake"
# Bootstrap plugins are copied into writable managed-plugin state by the
# installer. Services and the portable launcher point the loader at current/lib;
# this relative path also keeps the immutable source artifact directly usable.
for plugin_library in "${resolver_libraries[@]:1}"; do
# shellcheck disable=SC2016 # Dynamic linker token, not a shell variable.
patchelf --set-rpath '$ORIGIN/../../../../../lib' "$plugin_library"
done
dependency_report="$build_dir/dependency-report.txt"
python3 "$source_dir/scripts/validate-release-elf.py" \
--root "$stage" \
--max-glibc 2.35 \
elf_validation_args=(
--root "$stage"
--report "$dependency_report"
--max-glibc 2.35
--forbid-content-prefix "$source_dir"
--forbid-content-prefix "$build_dir"
)
[[ -z $void_source ]] ||
elf_validation_args+=(--forbid-content-prefix "$void_source")
[[ -z $void_teamspeak_source ]] ||
elf_validation_args+=(--forbid-content-prefix "$void_teamspeak_source")
python3 "$source_dir/scripts/validate-release-elf.py" \
"${elf_validation_args[@]}"
collect_licenses() {
local destination=$1
@@ -325,10 +522,11 @@ 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"
rm -f -- \
"$archive" "$archive.tmp" \
"$installer" "$installer.tmp" \
"$external_manifest" "$external_report" \
"$external_manifest" "$external_report" "$feed_payload" \
"$dist_dir/SHA256SUMS"
bash "$source_dir/scripts/package-release-payload.sh" \
@@ -337,13 +535,31 @@ bash "$source_dir/scripts/package-release-payload.sh" \
install -m 0644 "$stage/manifest.json" "$external_manifest"
install -m 0644 "$dependency_report" "$external_report"
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[@]}"
fi
(
cd "$dist_dir"
sha256sum \
checksum_files=(
"$(basename "$archive")" \
"$(basename "$installer")" \
"$(basename "$external_manifest")" \
"$(basename "$external_report")" >SHA256SUMS
"$(basename "$external_report")"
)
[[ -z $update_url ]] || checksum_files+=("$(basename "$feed_payload")")
sha256sum "${checksum_files[@]}" >SHA256SUMS
)
echo "Release created without starting Echoion:"
@@ -351,4 +567,5 @@ echo " $archive"
echo " $installer"
echo " $external_manifest"
echo " $external_report"
[[ -z $update_url ]] || echo " $feed_payload"
echo " $dist_dir/SHA256SUMS"
+10 -155
View File
@@ -1,6 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
if [[ $# -lt 3 || $# -gt 4 ]]; then
echo "usage: $0 RELEASE_ROOT VERSION BUNDLE_ROOT [MANIFEST]" >&2
exit 2
@@ -30,6 +32,10 @@ if [[ ! -x $bundle_root/bin/echoiond ]]; then
echo "echoiond is missing or not executable: $bundle_root/bin/echoiond" >&2
exit 2
fi
if [[ ! -x $bundle_root/bin/echoion-updater ]]; then
echo "updater is missing or not executable: $bundle_root/bin/echoion-updater" >&2
exit 2
fi
if [[ ! -f $bundle_root/lib/Echoion.ts ]]; then
echo "Core library is missing: $bundle_root/lib/Echoion.ts" >&2
exit 2
@@ -73,161 +79,10 @@ fi
mkdir -m 0755 -- "$staging"
cp -a -- "$bundle_root/." "$staging/"
python3 - "$staging" "$version" "$manifest_tmp" <<'PY'
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import stat
import sys
IMMUTABLE_ROOTS = ("bin", "lib", "service", "share")
UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH
def reject_unsafe_writable_mode(path, metadata):
if metadata.st_mode & UNSAFE_WRITABLE_MODE:
raise SystemExit(
f"immutable payload path is group- or world-writable: {path}"
)
root = Path(sys.argv[1]).resolve(strict=True)
version = sys.argv[2]
output = Path(sys.argv[3])
source = root / "manifest.json"
with source.open("r", encoding="utf-8") as stream:
manifest = json.load(stream)
if manifest.get("schemaVersion") != 2:
raise SystemExit("release manifest must use schemaVersion 2")
if manifest.get("version") != version:
raise SystemExit(
f"release version mismatch: expected {version!r}, got {manifest.get('version')!r}"
)
entries = manifest.get("files")
if not isinstance(entries, list):
raise SystemExit("release manifest files must be an array")
root_metadata = root.lstat()
if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink():
raise SystemExit(f"immutable payload root is not a directory: {root}")
reject_unsafe_writable_mode(root, root_metadata)
actual = set()
pending_directories = [root / name for name in IMMUTABLE_ROOTS]
for directory in pending_directories:
try:
metadata = directory.lstat()
except FileNotFoundError:
raise SystemExit(f"missing immutable payload directory: {directory}")
if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink():
raise SystemExit(f"missing immutable payload directory: {directory}")
reject_unsafe_writable_mode(directory, metadata)
while pending_directories:
directory = pending_directories.pop()
with os.scandir(directory) as iterator:
children = sorted(iterator, key=lambda item: item.name)
for child in children:
path = Path(child.path)
relative = path.relative_to(root).as_posix()
metadata = path.lstat()
if stat.S_ISDIR(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
pending_directories.append(path)
elif stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
if stat.S_ISREG(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
actual.add(relative)
else:
raise SystemExit(f"unsupported special file in payload: {path}")
seen = set()
entry_types = {}
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
raise SystemExit("invalid release manifest file entry")
relative = PurePosixPath(entry["path"])
if (
relative.is_absolute()
or not relative.parts
or relative.as_posix() != entry["path"]
or any(component in ("", ".", "..") for component in entry["path"].split("/"))
):
raise SystemExit(f"unsafe manifest path: {entry['path']!r}")
if entry["path"] in seen:
raise SystemExit(f"duplicate manifest path: {entry['path']}")
if relative.parts[0] not in IMMUTABLE_ROOTS:
raise SystemExit(
f"manifest path is outside immutable payload roots: {entry['path']}"
)
seen.add(entry["path"])
entry_types[entry["path"]] = entry.get("type")
path = root.joinpath(*relative.parts)
metadata = path.lstat()
if entry.get("type") == "file":
if not stat.S_ISREG(metadata.st_mode):
raise SystemExit(f"manifest regular file is missing: {entry['path']}")
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != entry.get("sha256") or metadata.st_size != entry.get("size"):
raise SystemExit(f"manifest file verification failed: {entry['path']}")
mode = f"{stat.S_IMODE(metadata.st_mode):04o}"
if mode != entry.get("mode"):
raise SystemExit(f"manifest mode verification failed: {entry['path']}")
reject_unsafe_writable_mode(path, metadata)
elif entry.get("type") == "symlink":
if not stat.S_ISLNK(metadata.st_mode):
raise SystemExit(f"manifest symlink is missing: {entry['path']}")
target = entry.get("target")
if not isinstance(target, str):
raise SystemExit(f"invalid manifest symlink target: {entry['path']}")
target_path = PurePosixPath(target)
if (
target_path.is_absolute()
or any(component in ("", ".", "..") for component in target.split("/"))
):
raise SystemExit(f"unsafe manifest symlink target: {entry['path']}")
if os.readlink(path) != target:
raise SystemExit(f"manifest symlink verification failed: {entry['path']}")
try:
path.resolve(strict=True).relative_to(root)
except (FileNotFoundError, RuntimeError, ValueError):
raise SystemExit(f"manifest symlink escapes release root: {entry['path']}")
else:
raise SystemExit(f"invalid manifest entry type: {entry.get('type')!r}")
if seen != actual:
undeclared = sorted(actual - seen)
missing = sorted(seen - actual)
details = []
if undeclared:
details.append("undeclared=" + ",".join(undeclared))
if missing:
details.append("missing=" + ",".join(missing))
raise SystemExit("immutable payload coverage mismatch: " + "; ".join(details))
required_files = {
"executable": "bin/echoiond",
"core": "lib/Echoion.ts",
"web dashboard": "share/echoion/web/index.html",
}
for description, required in required_files.items():
if description in ("executable", "core") and manifest.get(description) != required:
raise SystemExit(f"manifest {description} has a non-canonical path")
if required not in seen or entry_types.get(required) != "file":
raise SystemExit(f"manifest {description} is not declared as a file")
prefix = f"{version}/"
pending = dict(manifest)
pending["executable"] = prefix + manifest["executable"]
pending["core"] = prefix + manifest["core"]
pending["files"] = [dict(entry, path=prefix + entry["path"]) for entry in entries]
with output.open("w", encoding="utf-8", newline="\n") as stream:
json.dump(pending, stream, ensure_ascii=False, indent=2)
stream.write("\n")
os.chmod(output, 0o644)
PY
python3 "$script_dir/validate-release-manifest.py" \
--root "$staging" \
--version "$version" \
--pending-output "$manifest_tmp"
mv -T -- "$staging" "$destination"
destination_created=1
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env bash
set -euo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
verifier="$root/scripts/verify-gitea-release-tag.sh"
temporary=$(mktemp -d)
trap 'rm -rf -- "$temporary"' EXIT
repository="$temporary/repository"
mkdir -p "$repository"
git -C "$repository" init -q -b main
git -C "$repository" config user.name 'Echoion Release Test'
git -C "$repository" config user.email 'release-test@echoion.invalid'
ssh-keygen -q -t ed25519 -N '' -f "$temporary/release-key"
git -C "$repository" config gpg.format ssh
git -C "$repository" config user.signingkey "$temporary/release-key"
printf '%s\n' test >"$repository/source.txt"
git -C "$repository" add source.txt
git -C "$repository" commit -q -m 'Test release source'
git -C "$repository" tag -s -a v1.2.3 \
-m 'Echoion 1.2.3' \
-m $'First release-note paragraph.\n\nSecond paragraph.'
git -C "$repository" switch -q --detach v1.2.3
principal='release-test@echoion.invalid'
printf '%s %s\n' "$principal" "$(<"$temporary/release-key.pub")" \
>"$temporary/allowed-signers"
tag_object=$(git -C "$repository" rev-parse 'refs/tags/v1.2.3^{tag}')
target_commit=$(git -C "$repository" rev-parse 'refs/tags/v1.2.3^{}')
actual_target=$(
cd "$repository"
"$verifier" \
--tag v1.2.3 \
--event-sha "$tag_object" \
--allowed-signers "$temporary/allowed-signers" \
--notes-output "$temporary/notes.md"
)
test "$actual_target" = "$target_commit"
grep -Fqx 'Echoion 1.2.3' "$temporary/notes.md"
grep -Fqx 'First release-note paragraph.' "$temporary/notes.md"
grep -Fqx 'Second paragraph.' "$temporary/notes.md"
if grep -Fq -- 'SSH SIGNATURE' "$temporary/notes.md"; then
printf '%s\n' 'release notes contain the SSH signature' >&2
exit 1
fi
(
cd "$repository"
"$verifier" \
--tag v1.2.3 \
--event-sha "$target_commit" \
--allowed-signers "$temporary/allowed-signers" \
--notes-output "$temporary/notes-from-commit.md" \
>/dev/null
)
if (
cd "$repository"
"$verifier" \
--tag v1.2.3 \
--event-sha 0000000000000000000000000000000000000000 \
--allowed-signers "$temporary/allowed-signers" \
--notes-output "$temporary/rejected-notes.md" \
>/dev/null 2>&1
); then
printf '%s\n' 'mismatched event SHA was accepted' >&2
exit 1
fi
printf '%s\n' 'other@example.invalid ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA' \
>"$temporary/untrusted-signers"
if (
cd "$repository"
"$verifier" \
--tag v1.2.3 \
--event-sha "$target_commit" \
--allowed-signers "$temporary/untrusted-signers" \
--notes-output "$temporary/untrusted-notes.md" \
>/dev/null 2>&1
); then
printf '%s\n' 'untrusted SSH signer was accepted' >&2
exit 1
fi
git -C "$repository" tag lightweight "$target_commit"
if (
cd "$repository"
"$verifier" \
--tag lightweight \
--event-sha "$target_commit" \
--allowed-signers "$temporary/allowed-signers" \
--notes-output "$temporary/lightweight-notes.md" \
>/dev/null 2>&1
); then
printf '%s\n' 'lightweight tag was accepted' >&2
exit 1
fi
printf '%s\n' 'Gitea signed-tag verification tests passed'
+128 -1
View File
@@ -12,8 +12,9 @@ trap 'rm -rf -- "$temporary"' EXIT
stage="$temporary/stage"
mkdir -p "$stage/bin" "$stage/lib"
install -m 0755 /bin/true "$stage/bin/echoiond"
install -m 0755 /bin/true "$stage/bin/echoion-updater"
install -m 0644 /bin/true "$stage/lib/Echoion.ts"
printf '%s\n' '{}' >"$stage/manifest.json"
printf '%s\n' '{"schemaVersion":2,"version":"1.2.3"}' >"$stage/manifest.json"
cat >"$stage/install.sh" <<'INSTALL'
#!/bin/sh
set -eu
@@ -39,6 +40,121 @@ bash "$source_root/scripts/package-release-payload.sh" \
"$stage" "$base" 1700000000 "$archive_two" "$installer_two" "$temporary"
cmp "$archive_one" "$archive_two"
cmp "$installer_one" "$installer_two"
[[ $(stat -c '%a' -- "$archive_one") == 644 ]]
[[ $(stat -c '%a' -- "$archive_two") == 644 ]]
[[ $(stat -c '%a' -- "$installer_one") == 755 ]]
[[ $(stat -c '%a' -- "$installer_two") == 755 ]]
feed_payload="$temporary/update-payload.json"
core_feed_payload="$temporary/core-update-payload.json"
plugin_feed_payload="$temporary/plugin-update-payload.json"
feed_envelope="$temporary/update-envelope.json"
private_key="$temporary/update-private.pem"
public_key="$temporary/update-public.pem"
signature="$temporary/update-signature.bin"
SOURCE_DATE_EPOCH=1700000000 python3 \
"$source_root/scripts/generate-update-feed.py" \
--artifact "$archive_one" \
--manifest "$stage/manifest.json" \
--version 1.2.3 \
--url https://updates.example.invalid/echoion-1.2.3-linux-x86_64.tar.zst \
--channel beta \
--feed-id echoion-test \
--sequence 42 \
--output-payload "$feed_payload"
python3 - "$feed_payload" "$archive_one" "$stage/manifest.json" <<'PY'
import hashlib
import json
from pathlib import Path
import sys
payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
artifact = Path(sys.argv[2])
manifest = Path(sys.argv[3])
release = payload["releases"][0]
assert payload["schemaVersion"] == 1
assert payload["feedId"] == "echoion-test"
assert payload["sequence"] == 42
assert release["component"] == "runtime"
assert release["artifactId"] == ""
assert release["channel"] == "beta"
assert release["packageType"] == "tar.zst"
assert release["size"] == artifact.stat().st_size
assert release["sha256"] == hashlib.sha256(artifact.read_bytes()).hexdigest()
assert release["releaseManifestSha256"] == hashlib.sha256(
manifest.read_bytes()
).hexdigest()
PY
SOURCE_DATE_EPOCH=1700000000 python3 \
"$source_root/scripts/generate-update-feed.py" \
--artifact "$stage/lib/Echoion.ts" \
--component core \
--version 1.2.3 \
--url https://updates.example.invalid/Echoion-1.2.3.so \
--feed-id echoion-core-test \
--sequence 43 \
--output-payload "$core_feed_payload"
SOURCE_DATE_EPOCH=1700000000 python3 \
"$source_root/scripts/generate-update-feed.py" \
--artifact "$stage/lib/Echoion.ts" \
--component plugin \
--artifact-id lyrics \
--version 2.3.4 \
--url https://updates.example.invalid/lyrics-2.3.4.so \
--feed-id echoion-plugin-test \
--sequence 44 \
--output-payload "$plugin_feed_payload"
python3 - "$core_feed_payload" "$plugin_feed_payload" <<'PY'
import json
from pathlib import Path
import sys
core = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))["releases"][0]
plugin = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))["releases"][0]
assert core["component"] == "core"
assert core["artifactId"] == ""
assert core["packageType"] == "shared-library"
assert "releaseManifestSha256" not in core
assert plugin["component"] == "plugin"
assert plugin["artifactId"] == "lyrics"
assert plugin["packageType"] == "shared-library"
assert "releaseManifestSha256" not in plugin
PY
openssl genpkey -algorithm ED25519 -out "$private_key" >/dev/null 2>&1
SOURCE_DATE_EPOCH=1700000000 python3 \
"$source_root/scripts/generate-update-feed.py" \
--artifact "$archive_one" \
--manifest "$stage/manifest.json" \
--version 1.2.3 \
--url https://updates.example.invalid/echoion-1.2.3-linux-x86_64.tar.zst \
--sequence 42 \
--output-payload "$feed_payload" \
--output-envelope "$feed_envelope" \
--key-id test-key \
--private-key "$private_key"
python3 - "$feed_payload" "$feed_envelope" "$signature" <<'PY'
import base64
import json
from pathlib import Path
import sys
payload = Path(sys.argv[1]).read_bytes()
envelope = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))
def decode(value: str) -> bytes:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
assert envelope["schemaVersion"] == 1
assert envelope["keyId"] == "test-key"
assert decode(envelope["payload"]) == payload
Path(sys.argv[3]).write_bytes(decode(envelope["signature"]))
PY
openssl pkey -in "$private_key" -pubout -out "$public_key" >/dev/null 2>&1
openssl pkeyutl -verify -rawin -pubin -inkey "$public_key" \
-in "$feed_payload" -sigfile "$signature" >/dev/null
mapfile -t members < <(tar --zstd -tf "$archive_one")
((${#members[@]} > 0))
@@ -58,4 +174,15 @@ record="$temporary/installer-arguments"
printf '%s\n' alpha 'two words' >"$temporary/expected-arguments"
cmp "$temporary/expected-arguments" "$record"
path_installer_directory="$temporary/path-installer"
mkdir "$path_installer_directory"
install -m 0755 "$installer_one" "$path_installer_directory/echoion-installer"
path_record="$temporary/path-installer-arguments"
(
cd /
PATH="$path_installer_directory:$PATH" \
echoion-installer --record "$path_record" alpha 'two words'
)
cmp "$temporary/expected-arguments" "$path_record"
echo "release archive layout and .run regressions passed"
+57 -1
View File
@@ -10,17 +10,72 @@ source_root=$(realpath -e -- "$1")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-packaging.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
for version in 0.0.0 1.2.3 1.2.3-rc.1 10.20.30-beta.2; do
python3 "$source_root/scripts/validate-semver.py" "$version"
done
for version in 01.2.3 1.2 1.2.3-01 not-a-version; do
if python3 "$source_root/scripts/validate-semver.py" "$version" \
>/dev/null 2>&1; then
echo "invalid SemVer unexpectedly accepted: $version" >&2
exit 1
fi
done
for version in 01.2.3 1.2.3-01; do
release_error="$temporary/release-version-$version.error"
if "$source_root/scripts/release.sh" \
--version "$version" \
--build-dir "$temporary/build" \
--dist-dir "$temporary/dist" \
>/dev/null 2>"$release_error"; then
echo "release unexpectedly accepted a non-canonical version: $version" >&2
exit 1
fi
grep -q 'canonical Semantic Versioning' "$release_error"
done
if "$source_root/scripts/release.sh" \
--version 1.2.3+build \
--build-dir "$temporary/build" \
--dist-dir "$temporary/dist" \
>/dev/null 2>&1; then
echo "release unexpectedly accepted SemVer build metadata" >&2
exit 1
fi
pythonless_path="$temporary/pythonless-path"
mkdir "$pythonless_path"
for command_name in bash dirname id realpath; do
ln -s "$(command -v "$command_name")" "$pythonless_path/$command_name"
done
ln -s "$(type -P true)" "$pythonless_path/docker"
if PATH="$pythonless_path" command -v python3 >/dev/null; then
echo "Python unexpectedly exists in the container-host test PATH" >&2
exit 1
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
bundle="$temporary/bundle"
mkdir -p \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/web"
"$bundle/share/echoion/web" \
"$bundle/share/echoion/tools"
install -m 0755 /bin/true "$bundle/bin/echoiond"
install -m 0755 /bin/true "$bundle/bin/echoion-updater"
install -m 0644 /bin/true "$bundle/lib/Echoion.ts"
printf '%s\n' '<!doctype html><title>Echoion</title>' \
>"$bundle/share/echoion/web/index.html"
printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in"
printf '%s\n' '[Service]' >"$bundle/service/echoion-updater.service.in"
printf '%s\n' '[Timer]' >"$bundle/service/echoion-updater.timer.in"
printf '%s\n' '{}' >"$bundle/share/echoion/config.example.json"
install -m 0755 "$source_root/scripts/validate-release-manifest.py" \
"$bundle/share/echoion/tools/validate-release-manifest.py"
ln -s Echoion.ts "$bundle/lib/Echoion-current.ts"
python3 "$source_root/scripts/generate-release-manifest.py" \
@@ -57,6 +112,7 @@ with open(sys.argv[1], encoding="utf-8") as stream:
assert manifest["schemaVersion"] == 2
assert manifest["version"] == "1.2.3"
assert manifest["executable"] == "bin/echoiond"
assert manifest["updater"] == "bin/echoion-updater"
assert manifest["core"] == "lib/Echoion.ts"
paths = [entry["path"] for entry in manifest["files"]]
assert paths == sorted(paths)
+67 -12
View File
@@ -7,23 +7,36 @@ if [[ $# != 1 ]]; then
fi
source_root=$(realpath -e -- "$1")
for command_name in cc cmake patchelf readelf python3; do
for command_name in cmake patchelf readelf python3; do
command -v "$command_name" >/dev/null || {
echo "missing test command: $command_name" >&2
exit 2
}
done
c_compiler_name=${CC:-cc}
c_compiler_path=$(command -v -- "$c_compiler_name") || {
echo "missing test C compiler: $c_compiler_name" >&2
exit 2
}
c_compiler=$(realpath -e -- "$c_compiler_path")
cxx_compiler_name=${CXX:-c++}
cxx_compiler_path=$(command -v -- "$cxx_compiler_name") || {
echo "missing test C++ compiler: $cxx_compiler_name" >&2
exit 2
}
cxx_compiler=$(realpath -e -- "$cxx_compiler_path")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-runtime-deps.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
configured_build="$temporary/configured-build"
mkdir -p "$configured_build"
configured_compiler=$(realpath -e -- "$(command -v c++)")
printf 'CMAKE_CXX_COMPILER:FILEPATH=%s\n' "$configured_compiler" \
printf 'CMAKE_CXX_COMPILER:FILEPATH=%s\n' "$cxx_compiler" \
>"$configured_build/CMakeCache.txt"
queried_compiler=$(CXX=/bin/false \
"$source_root/scripts/configured-cxx-compiler.sh" "$configured_build")
[[ $queried_compiler == "$configured_compiler" ]] || {
[[ $queried_compiler == "$cxx_compiler" ]] || {
echo "runtime compiler query followed CXX instead of the configured cache" >&2
exit 1
}
@@ -41,7 +54,8 @@ mkdir -p \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/web"
"$bundle/share/echoion/web" \
"$bundle/share/echoion/bootstrap-plugins/fixture-shortener/1.0.0"
cat >"$temporary/dependency.c" <<'C'
int echoion_dependency(void) { return 42; }
@@ -51,6 +65,9 @@ C
cat >"$temporary/core.c" <<'C'
extern int echoion_dependency(void);
extern int echoion_compiler_runtime(void);
__attribute__((used))
static const char echoion_forbidden_path[] =
"/tmp/echoion-forbidden-build-path/source.cpp";
int echoion_core(void) {
return echoion_dependency() + echoion_compiler_runtime();
}
@@ -63,13 +80,20 @@ int echoion_compiler_runtime(void) { return 7; }
__attribute__((used, section(".echoion_compiler_variant")))
static const char echoion_compiler_variant[] = ECHOION_VARIANT;
C
cat >"$temporary/plugin.c" <<'C'
extern int echoion_dependency(void);
__attribute__((used))
static const char echoion_plugin_forbidden_path[] =
"/tmp/echoion-plugin-forbidden-build-path/plugin.c";
int echoion_plugin(void) { return echoion_dependency(); }
C
for variant in preferred other; do
case $variant in
preferred) variant_lib=$preferred_lib ;;
other) variant_lib=$other_lib ;;
esac
cc -fPIC -shared "$temporary/dependency.c" \
"$c_compiler" -fPIC -shared "$temporary/dependency.c" \
'-DECHOION_VARIANT="'"$variant"'-runtime"' \
-Wl,-soname,libechoion-dependency.so.1 \
-o "$variant_lib/libechoion-dependency.so.1.2.3"
@@ -89,7 +113,7 @@ for variant in seeded resolver; do
variant_version=200
;;
esac
cc -fPIC -shared "$temporary/compiler-runtime.c" \
"$c_compiler" -fPIC -shared "$temporary/compiler-runtime.c" \
'-DECHOION_VARIANT="'"$variant"'-compiler-runtime"' \
-Wl,-soname,libstdc++.so.6 \
-o "$variant_lib/libstdc++.so.6.0.$variant_version"
@@ -97,7 +121,7 @@ for variant in seeded resolver; do
"$variant_lib/libstdc++.so.6"
done
resolver_core="$resolver/Echoion.ts"
cc -fPIC -shared "$temporary/core.c" \
"$c_compiler" -fPIC -shared "$temporary/core.c" \
-L"$preferred_lib" -lechoion-dependency \
-Wl,-l:libstdc++.so.6 \
-Wl,-soname,Echoion.ts \
@@ -105,18 +129,25 @@ cc -fPIC -shared "$temporary/core.c" \
-o "$resolver_core"
install -m 0644 "$resolver_core" "$bundle/lib/Echoion.ts"
patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts"
cc "$temporary/main.c" -o "$bundle/bin/echoiond"
bundle_plugin="$bundle/share/echoion/bootstrap-plugins/fixture-shortener/1.0.0/fixture-shortener.so"
"$c_compiler" -fPIC -shared "$temporary/plugin.c" \
-L"$preferred_lib" -lechoion-dependency \
-Wl,-rpath,"$preferred_lib" \
-o "$bundle_plugin"
"$c_compiler" "$temporary/main.c" -o "$bundle/bin/echoiond"
install -m 0755 "$bundle/bin/echoiond" "$bundle/bin/echoion-updater"
printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in"
printf '%s\n' '<!doctype html><title>Echoion</title>' \
>"$bundle/share/echoion/web/index.html"
cmake \
"-DBUNDLE_ROOT=$bundle" \
"-DBUNDLE_RESOLVER_LIBRARIES=$resolver_core" \
"-DBUNDLE_RESOLVER_LIBRARIES=$resolver_core;$bundle_plugin" \
"-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \
"-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_root/cmake/BundleRuntimeDependencies.cmake"
patchelf --set-rpath "\$ORIGIN/../../../../../lib" "$bundle_plugin"
python3 - "$source_root/scripts/validate-release-elf.py" <<'PY'
import importlib.util
@@ -169,9 +200,9 @@ cat >"$temporary/evil-user.c" <<'C'
extern int echoion_evil_dependency(void);
int echoion_evil_user(void) { return echoion_evil_dependency(); }
C
cc -fPIC -shared "$temporary/evil-dependency.c" \
"$c_compiler" -fPIC -shared "$temporary/evil-dependency.c" \
-Wl,-soname,libc.so.evil -o "$evil_build/libc.so.evil"
cc -fPIC -shared "$temporary/evil-user.c" \
"$c_compiler" -fPIC -shared "$temporary/evil-user.c" \
-L"$evil_build" -Wl,-l:libc.so.evil -Wl,-rpath,"$evil_build" \
-o "$evil_build/libevil-user.so"
rm "$evil_build/libc.so.evil"
@@ -190,8 +221,24 @@ fi
report="$temporary/dependencies.txt"
python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" --max-glibc 2.35 --report "$report"
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" \
--forbid-content-prefix /tmp/echoion-forbidden-build-path \
>/dev/null 2>&1; then
echo "embedded build/source path unexpectedly passed validation" >&2
exit 1
fi
grep -F $'NEEDED\tlib/Echoion.ts\tlibechoion-dependency.so.1\tbundled' "$report"
grep -F $'NEEDED\tbin/echoiond\tlibc.so.6\tsystem' "$report"
grep -F $'ELF\tshare/echoion/bootstrap-plugins/fixture-shortener/1.0.0/fixture-shortener.so\tRUNPATH=$ORIGIN/../../../../../lib' "$report"
grep -F $'NEEDED\tshare/echoion/bootstrap-plugins/fixture-shortener/1.0.0/fixture-shortener.so\tlibechoion-dependency.so.1\tbundled' "$report"
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" \
--forbid-content-prefix /tmp/echoion-plugin-forbidden-build-path \
>/dev/null 2>&1; then
echo "embedded plugin build/source path unexpectedly passed validation" >&2
exit 1
fi
[[ -L $bundle/lib/libechoion-dependency.so.1 ]]
[[ $(readlink "$bundle/lib/libechoion-dependency.so.1") != /* ]]
[[ -f $bundle/lib/libechoion-dependency.so.1.2.3 ]]
@@ -213,6 +260,14 @@ if find "$bundle/lib" -maxdepth 1 -name 'libc.so*' | grep -q .; then
exit 1
fi
patchelf --set-rpath "\$ORIGIN" "$bundle_plugin"
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" >/dev/null 2>&1; then
echo "incorrect bootstrap plugin RUNPATH unexpectedly passed validation" >&2
exit 1
fi
patchelf --set-rpath "\$ORIGIN/../../../../../lib" "$bundle_plugin"
patchelf --set-rpath /tmp/unsafe-build-path "$bundle/lib/Echoion.ts"
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" >/dev/null 2>&1; then
+354
View File
@@ -0,0 +1,354 @@
#!/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_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()
+447
View File
@@ -0,0 +1,447 @@
#!/usr/bin/env python3
"""Offline regression tests for scripts/gitea_release.py."""
from __future__ import annotations
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import threading
import unittest
from urllib.parse import parse_qs, unquote, urlsplit
SOURCE_ROOT = Path(__file__).resolve().parents[2]
SCRIPT = SOURCE_ROOT / "scripts" / "gitea_release.py"
class State:
def __init__(self) -> None:
self.releases: dict[int, dict] = {}
self.assets: dict[int, bytes] = {}
self.next_release = 1
self.next_asset = 1
self.uploads = 0
self.upload_attempts = 0
self.fail_upload_attempt: int | None = None
self.downloads = 0
self.tag_protections = [
{
"id": 1,
"name_pattern": "v*",
"whitelist_usernames": ["release-maintainer"],
"whitelist_teams": [],
}
]
def release_document(self, release_id: int, server: ThreadingHTTPServer) -> dict:
release = dict(self.releases[release_id])
release["assets"] = [
{
"id": asset["id"],
"name": asset["name"],
"size": len(self.assets[asset["id"]]),
"browser_download_url": (
f"http://127.0.0.1:{server.server_port}/downloads/"
f"{asset['id']}/{asset['name']}"
),
}
for asset in release.get("assets", [])
]
return release
class Handler(BaseHTTPRequestHandler):
server: "Server"
def log_message(self, *_args: object) -> None:
pass
def json_response(self, status: int, document: object) -> None:
body = json.dumps(document).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def empty_response(self, status: int) -> None:
self.send_response(status)
self.send_header("Content-Length", "0")
self.end_headers()
def read_json(self) -> dict:
size = int(self.headers["Content-Length"])
return json.loads(self.rfile.read(size))
def do_GET(self) -> None:
target = urlsplit(self.path)
if target.path.startswith("/downloads/"):
asset_id = int(target.path.split("/")[2])
body = self.server.state.assets[asset_id]
self.server.state.downloads += 1
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
tag_match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/releases/tags/(.+)", target.path
)
if tag_match:
tag = unquote(tag_match.group(1))
for release_id, release in self.server.state.releases.items():
if release["tag_name"] == tag:
self.json_response(
200,
self.server.state.release_document(release_id, self.server),
)
return
self.json_response(404, {"message": "not found"})
return
repository_tag_match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/tags/(.+)", target.path
)
if repository_tag_match:
tag = unquote(repository_tag_match.group(1))
for release in self.server.state.releases.values():
if release["tag_name"] == tag:
self.json_response(
200,
{
"name": tag,
"commit": {"sha": release["target_commitish"]},
},
)
return
self.json_response(404, {"message": "not found"})
return
release_match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/releases/([0-9]+)", target.path
)
if release_match:
release_id = int(release_match.group(1))
self.json_response(
200, self.server.state.release_document(release_id, self.server)
)
return
if target.path == "/api/v1/repos/Void/Echoion/releases":
releases = [
self.server.state.release_document(release_id, self.server)
for release_id in sorted(self.server.state.releases, reverse=True)
]
self.json_response(200, releases)
return
if target.path == "/api/v1/repos/Void/Echoion/tag_protections":
self.json_response(200, self.server.state.tag_protections)
return
self.json_response(404, {"message": "unknown route"})
def do_POST(self) -> None:
target = urlsplit(self.path)
if target.path == "/api/v1/repos/Void/Echoion/releases":
document = self.read_json()
release_id = self.server.state.next_release
self.server.state.next_release += 1
self.server.state.releases[release_id] = {
**document,
"id": release_id,
"assets": [],
"created_at": f"2026-07-{release_id:02d}T00:00:00Z",
"published_at": None,
}
self.json_response(
201, self.server.state.release_document(release_id, self.server)
)
return
asset_match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/releases/([0-9]+)/assets", target.path
)
if asset_match:
release_id = int(asset_match.group(1))
filename = parse_qs(target.query)["name"][0]
content_type = self.headers["Content-Type"]
boundary = content_type.partition("boundary=")[2].encode("ascii")
body = self.rfile.read(int(self.headers["Content-Length"]))
payload = body.split(b"\r\n\r\n", 1)[1].rsplit(
b"\r\n--" + boundary, 1
)[0]
self.server.state.upload_attempts += 1
if (
self.server.state.fail_upload_attempt
== self.server.state.upload_attempts
):
self.json_response(500, {"message": "injected upload failure"})
return
asset_id = self.server.state.next_asset
self.server.state.next_asset += 1
self.server.state.assets[asset_id] = payload
self.server.state.releases[release_id]["assets"].append(
{"id": asset_id, "name": filename}
)
self.server.state.uploads += 1
document = self.server.state.release_document(release_id, self.server)[
"assets"
][-1]
self.json_response(201, document)
return
self.json_response(404, {"message": "unknown route"})
def do_PATCH(self) -> None:
target = urlsplit(self.path)
match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/releases/([0-9]+)", target.path
)
if not match:
self.json_response(404, {"message": "unknown route"})
return
release_id = int(match.group(1))
self.server.state.releases[release_id].update(self.read_json())
if not self.server.state.releases[release_id]["draft"]:
self.server.state.releases[release_id]["published_at"] = (
"2026-07-22T00:00:00Z"
)
self.json_response(
200, self.server.state.release_document(release_id, self.server)
)
def do_DELETE(self) -> None:
target = urlsplit(self.path)
tag_match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/tags/(.+)", target.path
)
if tag_match:
self.empty_response(204)
return
asset_match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/releases/([0-9]+)/assets/([0-9]+)",
target.path,
)
if asset_match:
release_id = int(asset_match.group(1))
asset_id = int(asset_match.group(2))
del self.server.state.assets[asset_id]
self.server.state.releases[release_id]["assets"] = [
asset
for asset in self.server.state.releases[release_id]["assets"]
if asset["id"] != asset_id
]
self.empty_response(204)
return
release_match = re.fullmatch(
r"/api/v1/repos/Void/Echoion/releases/([0-9]+)", target.path
)
if release_match:
del self.server.state.releases[int(release_match.group(1))]
self.empty_response(204)
return
self.json_response(404, {"message": "unknown route"})
class Server(ThreadingHTTPServer):
def __init__(self) -> None:
super().__init__(("127.0.0.1", 0), Handler)
self.state = State()
class GiteaReleaseTest(unittest.TestCase):
def setUp(self) -> None:
self.server = Server()
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.temporary = tempfile.TemporaryDirectory()
def tearDown(self) -> None:
self.server.shutdown()
self.server.server_close()
self.thread.join()
self.temporary.cleanup()
def run_script(self, *arguments: str, check: bool = True) -> subprocess.CompletedProcess:
environment = {
**os.environ,
"TEST_GITEA_TOKEN": "test-token",
"NO_PROXY": "127.0.0.1,localhost",
"no_proxy": "127.0.0.1,localhost",
}
command = [
os.fspath(SCRIPT),
"--api-url",
f"http://127.0.0.1:{self.server.server_port}/api/v1",
"--token-env",
"TEST_GITEA_TOKEN",
"--allow-http",
*arguments,
]
completed = subprocess.run(
command,
check=False,
env=environment,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
if check and completed.returncode != 0:
self.fail(
f"gitea_release.py failed with {completed.returncode}:\n"
f"stdout: {completed.stdout}\nstderr: {completed.stderr}"
)
return completed
def test_publish_is_verified_and_idempotent(self) -> None:
artifacts = Path(self.temporary.name, "artifacts")
artifacts.mkdir()
Path(artifacts, "one.bin").write_bytes(b"first")
Path(artifacts, "two.bin").write_bytes(b"second")
arguments = (
"publish",
"--owner",
"Void",
"--repo",
"Echoion",
"--tag",
"v1.2.3",
"--target",
"0123456789abcdef0123456789abcdef01234567",
"--name",
"Echoion 1.2.3",
"--body",
"test release",
"--artifacts",
os.fspath(artifacts),
)
self.run_script(*arguments)
self.assertFalse(self.server.state.releases[1]["draft"])
self.assertEqual(self.server.state.uploads, 2)
self.assertEqual(self.server.state.downloads, 2)
self.run_script(*arguments)
self.assertEqual(self.server.state.uploads, 2)
self.assertEqual(self.server.state.downloads, 4)
Path(artifacts, "one.bin").write_bytes(b"FIRST")
failed = self.run_script(*arguments, check=False)
self.assertNotEqual(failed.returncode, 0)
self.assertIn("download verification failed", failed.stderr)
self.assertEqual(self.server.state.uploads, 2)
def test_prune_keeps_fourteen_newest_nightlies(self) -> None:
for index in range(1, 17):
self.server.state.releases[index] = {
"id": index,
"tag_name": f"nightly-202607{index:02d}-1",
"prerelease": True,
"draft": False,
"assets": [],
"created_at": f"2026-07-{index:02d}T00:00:00Z",
"published_at": f"2026-07-{index:02d}T00:00:00Z",
}
self.server.state.next_release = 17
self.run_script(
"prune-nightlies",
"--owner",
"Void",
"--repo",
"Echoion",
"--keep",
"14",
"--protect-tag",
"nightly-20260716-1",
)
self.assertEqual(len(self.server.state.releases), 14)
self.assertNotIn(1, self.server.state.releases)
self.assertNotIn(2, self.server.state.releases)
def test_prune_counts_an_old_protected_nightly_within_retention(self) -> None:
for index in range(1, 17):
self.server.state.releases[index] = {
"id": index,
"tag_name": f"nightly-202607{index:02d}-1",
"prerelease": True,
"draft": False,
"assets": [],
"created_at": f"2026-07-{index:02d}T00:00:00Z",
"published_at": f"2026-07-{index:02d}T00:00:00Z",
}
self.server.state.next_release = 17
self.run_script(
"prune-nightlies",
"--owner",
"Void",
"--repo",
"Echoion",
"--keep",
"14",
"--protect-tag",
"nightly-20260701-1",
)
self.assertEqual(len(self.server.state.releases), 14)
self.assertIn(1, self.server.state.releases)
self.assertNotIn(2, self.server.state.releases)
self.assertNotIn(3, self.server.state.releases)
def test_rerun_recovers_an_incomplete_draft(self) -> None:
artifacts = Path(self.temporary.name, "artifacts")
artifacts.mkdir()
Path(artifacts, "one.bin").write_bytes(b"first")
Path(artifacts, "two.bin").write_bytes(b"second")
arguments = (
"publish",
"--owner",
"Void",
"--repo",
"Echoion",
"--tag",
"v2.0.0",
"--target",
"89abcdef0123456789abcdef0123456789abcdef",
"--name",
"Echoion 2.0.0",
"--artifacts",
os.fspath(artifacts),
)
self.server.state.fail_upload_attempt = 2
failed = self.run_script(*arguments, check=False)
self.assertNotEqual(failed.returncode, 0)
self.assertTrue(self.server.state.releases[1]["draft"])
self.assertEqual(len(self.server.state.releases[1]["assets"]), 1)
self.server.state.fail_upload_attempt = None
self.run_script(*arguments)
self.assertFalse(self.server.state.releases[1]["draft"])
self.assertEqual(len(self.server.state.releases[1]["assets"]), 2)
self.assertEqual(self.server.state.uploads, 3)
def test_required_tag_protection_is_verified(self) -> None:
completed = self.run_script(
"verify-tag-protection",
"--owner",
"Void",
"--repo",
"Echoion",
"--required-pattern",
"v*",
)
self.assertIn("verified protected tag pattern", completed.stdout)
self.server.state.tag_protections[0]["whitelist_usernames"] = []
rejected = self.run_script(
"verify-tag-protection",
"--owner",
"Void",
"--repo",
"Echoion",
"--required-pattern",
"v*",
check=False,
)
self.assertNotEqual(rejected.returncode, 0)
self.assertIn("empty allowlist", rejected.stderr)
if __name__ == "__main__":
unittest.main()
+111 -16
View File
@@ -36,6 +36,15 @@ INTERPRETER_PATTERN = re.compile(r"Requesting program interpreter: ([^]]+)]")
GLIBC_NAME_PATTERN = re.compile(r"\bName: (GLIBC_[A-Za-z0-9_.]+)\b")
GLIBC_VERSION_PATTERN = re.compile(r"^GLIBC_(\d+)\.(\d+)(?:\.(\d+))?$")
GLIBC_ABI_MINIMUMS = {"GLIBC_ABI_DT_RELR": (2, 36)}
PLUGIN_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
PLUGIN_VERSION_PATTERN = 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-]*))*)?$"
)
PLUGIN_RUNPATH = "$ORIGIN/../../../../../lib"
def parse_version(value: str) -> tuple[int, ...]:
@@ -118,26 +127,91 @@ def validate_symlinks(library_dir: Path) -> None:
ensure_inside(path, library_dir, "library symlink")
def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[str]:
def bootstrap_plugin_libraries(root: Path) -> list[Path]:
plugin_root = root / "share/echoion/bootstrap-plugins"
if not plugin_root.exists() and not plugin_root.is_symlink():
return []
if plugin_root.is_symlink() or not plugin_root.is_dir():
raise ValueError(
f"bootstrap plugin root is not a real directory: {plugin_root}"
)
libraries: list[Path] = []
for plugin_directory in sorted(plugin_root.iterdir()):
plugin_id = plugin_directory.name
if (
plugin_directory.is_symlink()
or not plugin_directory.is_dir()
or PLUGIN_IDENTIFIER_PATTERN.fullmatch(plugin_id) is None
):
raise ValueError(f"invalid bootstrap plugin directory: {plugin_directory}")
versions = sorted(plugin_directory.iterdir())
if len(versions) != 1:
raise ValueError(
f"bootstrap plugin {plugin_id!r} must contain exactly one version"
)
version_directory = versions[0]
if (
version_directory.is_symlink()
or not version_directory.is_dir()
or len(version_directory.name) > 64
or PLUGIN_VERSION_PATTERN.fullmatch(version_directory.name) is None
):
raise ValueError(
f"invalid bootstrap plugin version: {version_directory}"
)
expected = version_directory / f"{plugin_id}.so"
entries = sorted(version_directory.iterdir())
if entries != [expected]:
raise ValueError(
f"bootstrap plugin {plugin_id!r} version "
f"{version_directory.name!r} has unexpected files"
)
if expected.is_symlink() or not expected.is_file() or not is_elf(expected):
raise ValueError(f"missing regular bootstrap plugin ELF: {expected}")
libraries.append(expected)
return libraries
def validate(
root: Path,
maximum_glibc: tuple[int, ...] | None = None,
forbidden_content_prefixes: tuple[bytes, ...] = (),
) -> list[str]:
executable = root / "bin/echoiond"
updater = root / "bin/echoion-updater"
core = root / "lib/Echoion.ts"
executable_dir = (root / "bin").resolve(strict=True)
library_dir = (root / "lib").resolve(strict=True)
for required in (executable, core):
for required in (executable, updater, core):
if not required.is_file() or required.is_symlink() or not is_elf(required):
raise ValueError(f"missing regular ELF payload: {required}")
validate_symlinks(library_dir)
elf_files: list[Path] = [executable]
elf_files: list[Path] = []
for path in sorted(executable_dir.iterdir()):
if path.is_symlink() or not path.is_file() or not is_elf(path):
raise ValueError(f"unexpected non-ELF entry in bin/: {path}")
elf_files.append(path)
for path in sorted(library_dir.iterdir()):
if path.is_symlink():
continue
if not path.is_file() or not is_elf(path):
raise ValueError(f"unexpected non-ELF entry in lib/: {path}")
elf_files.append(path)
plugin_files = set(bootstrap_plugin_libraries(root))
elf_files.extend(sorted(plugin_files))
report: list[str] = []
for path in elf_files:
relative = path.relative_to(root).as_posix()
contents = path.read_bytes()
for prefix in forbidden_content_prefixes:
if prefix in contents:
rendered = os.fsdecode(prefix)
raise ValueError(
f"{relative} embeds forbidden build/source path: {rendered}"
)
header = command_output(["readelf", "-hW", os.fspath(path)])
if not re.search(r"^\s*Class:\s+ELF64\s*$", header, re.MULTILINE):
raise ValueError(f"{relative} is not a 64-bit ELF")
@@ -149,7 +223,12 @@ def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[s
raise ValueError(f"{relative} is not an x86-64 ELF")
dynamic = command_output(["readelf", "-dW", os.fspath(path)])
runpaths = RUNPATH_PATTERN.findall(dynamic)
expected_runpath = "$ORIGIN/../lib" if path == executable else "$ORIGIN"
if path in plugin_files:
expected_runpath = PLUGIN_RUNPATH
elif path.parent == executable_dir:
expected_runpath = "$ORIGIN/../lib"
else:
expected_runpath = "$ORIGIN"
if runpaths != [expected_runpath]:
raise ValueError(
f"{relative} RUNPATH must be {expected_runpath!r}, got {runpaths!r}"
@@ -189,17 +268,18 @@ def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[s
newest = ".".join(map(str, max(glibc_versions)))
report.append(f"ABI\t{relative}\tGLIBC_MAX={newest}")
program_headers = command_output(["readelf", "-lW", os.fspath(executable)])
interpreter_match = INTERPRETER_PATTERN.search(program_headers)
if interpreter_match is None:
raise ValueError("echoiond has no ELF interpreter")
interpreter = interpreter_match.group(1)
if not re.fullmatch(
r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)",
interpreter,
):
raise ValueError(f"unexpected ELF interpreter: {interpreter}")
report.append(f"INTERPRETER\tbin/echoiond\t{interpreter}\tsystem")
if path.parent == executable_dir:
program_headers = command_output(["readelf", "-lW", os.fspath(path)])
interpreter_match = INTERPRETER_PATTERN.search(program_headers)
if interpreter_match is None:
raise ValueError(f"{relative} has no ELF interpreter")
interpreter = interpreter_match.group(1)
if not re.fullmatch(
r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)",
interpreter,
):
raise ValueError(f"unexpected ELF interpreter in {relative}: {interpreter}")
report.append(f"INTERPRETER\t{relative}\t{interpreter}\tsystem")
return sorted(report)
@@ -229,13 +309,28 @@ def main() -> int:
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--report", type=Path)
parser.add_argument("--max-glibc", type=parse_version)
parser.add_argument(
"--forbid-content-prefix",
action="append",
default=[],
help="reject ELF files containing this build/source path (repeatable)",
)
arguments = parser.parse_args()
if shutil.which("readelf") is None:
parser.error("readelf is required")
try:
root = arguments.root.resolve(strict=True)
report = validate(root, arguments.max_glibc)
forbidden_content_prefixes = tuple(
os.fsencode(prefix)
for prefix in arguments.forbid_content_prefix
if prefix
)
report = validate(
root,
arguments.max_glibc,
forbidden_content_prefixes,
)
except (OSError, ValueError) as error:
parser.error(str(error))
if arguments.report:
+240
View File
@@ -0,0 +1,240 @@
#!/usr/bin/env python3
"""Validate an Echoion release tree without executing payload binaries."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import stat
import tempfile
IMMUTABLE_ROOTS = ("bin", "lib", "service", "share")
UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for block in iter(lambda: source.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def reject_unsafe_writable_mode(path: Path, metadata: os.stat_result) -> None:
if metadata.st_mode & UNSAFE_WRITABLE_MODE:
raise ValueError(
f"immutable payload path is group- or world-writable: {path}"
)
def safe_relative_path(value: object) -> PurePosixPath:
if not isinstance(value, str):
raise ValueError("manifest file entry has no string path")
relative = PurePosixPath(value)
if (
relative.is_absolute()
or not relative.parts
or relative.as_posix() != value
or any(component in ("", ".", "..") for component in value.split("/"))
or relative.parts[0] not in IMMUTABLE_ROOTS
):
raise ValueError(f"unsafe manifest path: {value!r}")
return relative
def collect_actual_entries(root: Path) -> set[str]:
root_metadata = root.lstat()
if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink():
raise ValueError(f"immutable payload root is not a directory: {root}")
reject_unsafe_writable_mode(root, root_metadata)
actual: set[str] = set()
pending = [root / name for name in IMMUTABLE_ROOTS]
for directory in pending:
try:
metadata = directory.lstat()
except FileNotFoundError as error:
raise ValueError(
f"missing immutable payload directory: {directory}"
) from error
if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink():
raise ValueError(f"missing immutable payload directory: {directory}")
reject_unsafe_writable_mode(directory, metadata)
while pending:
directory = pending.pop()
with os.scandir(directory) as iterator:
children = sorted(iterator, key=lambda item: item.name)
for child in children:
path = Path(child.path)
relative = path.relative_to(root).as_posix()
metadata = path.lstat()
if stat.S_ISDIR(metadata.st_mode):
if path.is_symlink():
raise ValueError(f"directory symlink is not allowed: {path}")
reject_unsafe_writable_mode(path, metadata)
pending.append(path)
elif stat.S_ISREG(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
actual.add(relative)
elif stat.S_ISLNK(metadata.st_mode):
actual.add(relative)
else:
raise ValueError(f"unsupported special file in payload: {path}")
return actual
def load_and_validate(root: Path, expected_version: str | None = None) -> dict:
manifest_path = root / "manifest.json"
with manifest_path.open("r", encoding="utf-8") as stream:
manifest = json.load(stream)
if not isinstance(manifest, dict) or manifest.get("schemaVersion") != 2:
raise ValueError("release manifest must use schemaVersion 2")
version = manifest.get("version")
if not isinstance(version, str) or not version:
raise ValueError("release manifest has no version")
if expected_version is not None and version != expected_version:
raise ValueError(
f"release version mismatch: expected {expected_version!r}, got {version!r}"
)
entries = manifest.get("files")
if not isinstance(entries, list):
raise ValueError("release manifest files must be an array")
actual = collect_actual_entries(root)
seen: set[str] = set()
entry_types: dict[str, str] = {}
for entry in entries:
if not isinstance(entry, dict):
raise ValueError("invalid release manifest file entry")
relative = safe_relative_path(entry.get("path"))
relative_text = relative.as_posix()
if relative_text in seen:
raise ValueError(f"duplicate manifest path: {relative_text}")
seen.add(relative_text)
path = root.joinpath(*relative.parts)
try:
metadata = path.lstat()
except FileNotFoundError as error:
raise ValueError(f"manifest entry is missing: {relative_text}") from error
entry_type = entry.get("type")
if entry_type == "file":
if not stat.S_ISREG(metadata.st_mode):
raise ValueError(f"manifest regular file is missing: {relative_text}")
reject_unsafe_writable_mode(path, metadata)
if metadata.st_size != entry.get("size") or sha256(path) != entry.get(
"sha256"
):
raise ValueError(f"manifest file verification failed: {relative_text}")
mode = f"{stat.S_IMODE(metadata.st_mode):04o}"
if mode != entry.get("mode"):
raise ValueError(f"manifest mode verification failed: {relative_text}")
elif entry_type == "symlink":
if not stat.S_ISLNK(metadata.st_mode):
raise ValueError(f"manifest symlink is missing: {relative_text}")
target = entry.get("target")
if not isinstance(target, str):
raise ValueError(f"invalid manifest symlink target: {relative_text}")
target_path = PurePosixPath(target)
if (
not target
or target_path.is_absolute()
or any(component in ("", ".", "..") for component in target.split("/"))
or os.readlink(path) != target
):
raise ValueError(f"unsafe manifest symlink target: {relative_text}")
try:
path.resolve(strict=True).relative_to(root)
except (FileNotFoundError, RuntimeError, ValueError) as error:
raise ValueError(
f"manifest symlink escapes release root: {relative_text}"
) from error
else:
raise ValueError(f"invalid manifest entry type: {entry_type!r}")
entry_types[relative_text] = entry_type
if seen != actual:
details = []
if undeclared := sorted(actual - seen):
details.append("undeclared=" + ",".join(undeclared))
if missing := sorted(seen - actual):
details.append("missing=" + ",".join(missing))
raise ValueError("immutable payload coverage mismatch: " + "; ".join(details))
required = {
"executable": "bin/echoiond",
"updater": "bin/echoion-updater",
"core": "lib/Echoion.ts",
"web dashboard": "share/echoion/web/index.html",
"configuration template": "share/echoion/config.example.json",
"manifest validator": "share/echoion/tools/validate-release-manifest.py",
"service template": "service/echoion.service.in",
"updater service template": "service/echoion-updater.service.in",
"updater timer template": "service/echoion-updater.timer.in",
}
if manifest.get("executable") != required["executable"]:
raise ValueError("manifest executable has a non-canonical path")
if manifest.get("updater") != required["updater"]:
raise ValueError("manifest updater has a non-canonical path")
if manifest.get("core") != required["core"]:
raise ValueError("manifest core has a non-canonical path")
for description, path in required.items():
if entry_types.get(path) != "file":
raise ValueError(f"manifest {description} is not declared as a file")
for description in ("executable", "updater"):
executable = root / required[description]
if stat.S_IMODE(executable.stat().st_mode) & 0o111 == 0:
raise ValueError(f"manifest {description} is not executable")
return manifest
def write_pending(manifest: dict, version: str, output: Path) -> None:
prefix = f"{version}/"
pending = dict(manifest)
pending["executable"] = prefix + str(manifest["executable"])
pending["updater"] = prefix + str(manifest["updater"])
pending["core"] = prefix + str(manifest["core"])
pending["files"] = [
dict(entry, path=prefix + str(entry["path"])) for entry in manifest["files"]
]
output.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{output.name}.", dir=output.parent
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
json.dump(pending, stream, ensure_ascii=False, indent=2)
stream.write("\n")
os.chmod(temporary_name, 0o644)
os.replace(temporary_name, output)
except BaseException:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
raise
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--version")
parser.add_argument("--pending-output", type=Path)
arguments = parser.parse_args()
try:
root = arguments.root.resolve(strict=True)
manifest = load_and_validate(root, arguments.version)
if arguments.pending_output is not None:
write_pending(manifest, str(manifest["version"]), arguments.pending_output)
except (OSError, ValueError, json.JSONDecodeError) as error:
parser.error(str(error))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Validate one canonical Semantic Versioning 2.0.0 value."""
from __future__ import annotations
import re
import sys
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-]+)*)?$"
)
def main() -> int:
if len(sys.argv) != 2:
print("usage: validate-semver.py VERSION", file=sys.stderr)
return 2
if not SEMVER.fullmatch(sys.argv[1]):
print(
f"validate-semver: version is not canonical SemVer: {sys.argv[1]!r}",
file=sys.stderr,
)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
printf '%s\n' \
'Usage: verify-gitea-release-tag.sh --tag TAG --event-sha SHA' \
' --allowed-signers FILE --notes-output FILE'
}
tag=
event_sha=
allowed_signers=
notes_output=
while (($# > 0)); do
case "$1" in
--tag)
tag=${2-}
shift 2
;;
--event-sha)
event_sha=${2-}
shift 2
;;
--allowed-signers)
allowed_signers=${2-}
shift 2
;;
--notes-output)
notes_output=${2-}
shift 2
;;
--help|-h)
usage
exit 0
;;
*)
printf 'verify-gitea-release-tag: unknown argument: %s\n' "$1" >&2
usage >&2
exit 2
;;
esac
done
if [[ -z "$tag" || -z "$event_sha" || -z "$allowed_signers" ||
-z "$notes_output" ]]; then
usage >&2
exit 2
fi
if [[ ! "$event_sha" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]; then
printf '%s\n' \
'verify-gitea-release-tag: event SHA is not a full object id' >&2
exit 1
fi
if ! git check-ref-format "refs/tags/$tag"; then
printf '%s\n' 'verify-gitea-release-tag: invalid tag name' >&2
exit 1
fi
if [[ ! -f "$allowed_signers" || -L "$allowed_signers" ||
! -s "$allowed_signers" ]]; then
printf '%s\n' \
'verify-gitea-release-tag: allowed signers must be a non-empty regular file' \
>&2
exit 1
fi
tag_ref="refs/tags/$tag"
tag_object=$(git rev-parse --verify "$tag_ref^{tag}")
tag_target=$(
git cat-file tag "$tag_object" |
sed -n '1s/^object //p'
)
target_type=$(
git cat-file tag "$tag_object" |
sed -n '2s/^type //p'
)
if [[ "$target_type" != commit ||
! "$tag_target" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]; then
printf '%s\n' \
'verify-gitea-release-tag: annotated tag must directly target a commit' >&2
exit 1
fi
git cat-file -e "$tag_target^{commit}"
signature=$(
git for-each-ref --count=1 --format='%(contents:signature)' "$tag_ref"
)
if [[ "$signature" != '-----BEGIN SSH SIGNATURE-----'* ]]; then
printf '%s\n' \
'verify-gitea-release-tag: annotated tag must use an SSH signature' >&2
exit 1
fi
git -c gpg.ssh.allowedSignersFile="$allowed_signers" \
verify-tag "$tag_ref" >&2
checked_out_commit=$(git rev-parse --verify 'HEAD^{commit}')
if [[ "$checked_out_commit" != "$tag_target" ]]; then
printf '%s\n' \
'verify-gitea-release-tag: checkout HEAD differs from the tag target' >&2
exit 1
fi
if [[ "$event_sha" != "$tag_object" && "$event_sha" != "$tag_target" ]]; then
printf '%s\n' \
'verify-gitea-release-tag: event SHA differs from the tag and target objects' \
>&2
exit 1
fi
subject=$(
git for-each-ref --count=1 --format='%(contents:subject)' "$tag_ref"
)
body=$(
git for-each-ref --count=1 --format='%(contents:body)' "$tag_ref"
)
if [[ -z "$subject" ]]; then
printf '%s\n' \
'verify-gitea-release-tag: annotated tag has no release-note subject' >&2
exit 1
fi
{
printf '%s\n' "$subject"
if [[ -n "$body" ]]; then
printf '\n%s\n' "$body"
fi
} >"$notes_output"
printf '%s\n' "$tag_target"