211 lines
7.2 KiB
Python
Executable File
211 lines
7.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Generate Echoion's deterministic v2 immutable-payload manifest."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path, PurePosixPath
|
|
import re
|
|
import stat
|
|
import tempfile
|
|
|
|
|
|
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
|
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 safe_symlink_target(root: Path, path: Path) -> str:
|
|
target = os.readlink(path)
|
|
target_path = PurePosixPath(target)
|
|
target_components = target.split("/")
|
|
if (
|
|
not target
|
|
or target_path.is_absolute()
|
|
or any(component in ("", ".", "..") for component in target_components)
|
|
):
|
|
raise ValueError(f"unsafe symlink target for {path}: {target!r}")
|
|
|
|
try:
|
|
resolved = path.resolve(strict=True)
|
|
resolved.relative_to(root)
|
|
except (FileNotFoundError, RuntimeError, ValueError) as error:
|
|
raise ValueError(f"symlink escapes the payload or is dangling: {path}") from error
|
|
return target
|
|
|
|
|
|
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 collect_entries(root: Path) -> list[dict[str, object]]:
|
|
entries: list[dict[str, object]] = []
|
|
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)
|
|
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_ISLNK(metadata.st_mode):
|
|
entries.append(
|
|
{
|
|
"path": relative,
|
|
"type": "symlink",
|
|
"target": safe_symlink_target(root, path),
|
|
}
|
|
)
|
|
elif stat.S_ISDIR(metadata.st_mode):
|
|
reject_unsafe_writable_mode(path, metadata)
|
|
pending.append(path)
|
|
elif stat.S_ISREG(metadata.st_mode):
|
|
reject_unsafe_writable_mode(path, metadata)
|
|
if metadata.st_size > (1 << 53) - 1:
|
|
raise ValueError(f"payload file is too large for the manifest: {path}")
|
|
entries.append(
|
|
{
|
|
"path": relative,
|
|
"type": "file",
|
|
"size": metadata.st_size,
|
|
"sha256": sha256(path),
|
|
"mode": f"{stat.S_IMODE(metadata.st_mode):04o}",
|
|
}
|
|
)
|
|
else:
|
|
raise ValueError(f"unsupported special file in payload: {path}")
|
|
|
|
entries.sort(key=lambda entry: str(entry["path"]))
|
|
return entries
|
|
|
|
|
|
def write_manifest(
|
|
root: Path,
|
|
version: str,
|
|
build_type: str,
|
|
build_signature: str,
|
|
output: Path,
|
|
) -> None:
|
|
entries = collect_entries(root)
|
|
regular_files = {
|
|
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}")
|
|
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,
|
|
"buildType": build_type,
|
|
"buildSignature": build_signature,
|
|
"executable": executable,
|
|
"updater": updater,
|
|
"core": core,
|
|
"files": entries,
|
|
}
|
|
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(manifest, 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", required=True)
|
|
parser.add_argument(
|
|
"--build-type",
|
|
choices=("RelWithDebInfo",),
|
|
default="RelWithDebInfo",
|
|
)
|
|
parser.add_argument("--build-signature")
|
|
parser.add_argument("--output", type=Path)
|
|
arguments = parser.parse_args()
|
|
|
|
if not VERSION_PATTERN.fullmatch(arguments.version):
|
|
parser.error("version must contain only letters, digits, dot, underscore, or dash")
|
|
root = arguments.root.resolve(strict=True)
|
|
output = arguments.output or root / "manifest.json"
|
|
build_signature = arguments.build_signature or f"development:{arguments.version}"
|
|
if (
|
|
not build_signature
|
|
or len(build_signature) > 256
|
|
or any(character in build_signature for character in "\r\n\0")
|
|
):
|
|
parser.error("build signature must be 1-256 characters without controls")
|
|
write_manifest(
|
|
root,
|
|
arguments.version,
|
|
arguments.build_type,
|
|
build_signature,
|
|
output,
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|