Files
Echoion/scripts/stage-release.sh
T
faumaray 639362fbf5 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-16 19:59:57 +03:00

243 lines
8.5 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 3 || $# -gt 4 ]]; then
echo "usage: $0 RELEASE_ROOT VERSION BUNDLE_ROOT [MANIFEST]" >&2
exit 2
fi
release_root=$(realpath -m -- "$1")
version=$2
bundle_root=$(realpath -e -- "$3")
manifest=${4:-"$release_root/pending-release.json"}
manifest=$(realpath -m -- "$manifest")
if [[ ! $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]]; then
echo "invalid release version: $version" >&2
exit 2
fi
if [[ $bundle_root == "$release_root" ||
$bundle_root == "$release_root"/* ||
$release_root == "$bundle_root"/* ]]; then
echo "bundle root and release root must not overlap" >&2
exit 2
fi
if [[ $(dirname -- "$manifest") != "$release_root" ]]; then
echo "pending manifest must be written directly below the release root" >&2
exit 2
fi
if [[ ! -x $bundle_root/bin/echoiond ]]; then
echo "echoiond is missing or not executable: $bundle_root/bin/echoiond" >&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
fi
if [[ ! -f $bundle_root/manifest.json ]]; then
echo "v2 release manifest is missing: $bundle_root/manifest.json" >&2
exit 2
fi
mkdir -p -- "$release_root" "$(dirname -- "$manifest")"
staging="$release_root/.staging-$version-$$"
destination="$release_root/$version"
manifest_tmp="$(dirname -- "$manifest")/.$(basename -- "$manifest").tmp.$$"
version_lock="$release_root/.stage-$version.lock"
destination_created=0
manifest_published=0
lock_acquired=0
cleanup() {
rm -rf -- "$staging"
rm -f -- "$manifest_tmp"
if ((destination_created && !manifest_published)); then
rm -rf -- "$destination"
fi
if ((lock_acquired)); then
rmdir -- "$version_lock" 2>/dev/null || true
fi
}
trap cleanup EXIT
if ! mkdir -- "$version_lock"; then
echo "release staging is already active for version $version" >&2
exit 2
fi
lock_acquired=1
if [[ -e $destination ]]; then
echo "release already exists: $destination" >&2
exit 2
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
mv -T -- "$staging" "$destination"
destination_created=1
mv -f -- "$manifest_tmp" "$manifest"
manifest_published=1
rmdir -- "$version_lock"
lock_acquired=0
trap - EXIT
echo "staged release $version"
echo "payload: $destination"
echo "manifest: $manifest"