327 lines
12 KiB
Python
Executable File
327 lines
12 KiB
Python
Executable File
#!/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
|
|
or manifest.get("buildType") != "RelWithDebInfo"
|
|
):
|
|
fail(
|
|
"release manifest schema/version/build type 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)
|
|
release["buildType"] = manifest["buildType"]
|
|
|
|
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": 3,
|
|
"keyId": arguments.key_id,
|
|
"document": payload_document,
|
|
"signedPayload": 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()
|