feat(vps): ship durable ARNavi host with reproducible install and recovery

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:43:39 +03:00
parent b6efae3272
commit d684eb7e05
30 changed files with 5520 additions and 0 deletions
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Build a dependency-free, content-addressed VPS release; no private state."""
import argparse
import hashlib
import json
import shutil
import tarfile
import tempfile
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def build(output):
with tempfile.TemporaryDirectory() as directory:
release = Path(directory) / "ndc-mission-vps"
shutil.copytree(
ROOT / "apps/vps-host", release, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")
)
shutil.copyfile(
ROOT / "src/k1link/device_plugins/arnavi_b2/internal.py", release / "ndc_vps/arnavi.py"
)
for name in ("usb_protocol.py", "web_protocol.py", "sim_network.py"):
shutil.copyfile(
ROOT / "src/k1link/device_plugins/arnavi_b2" / name, release / "ndc_vps" / name
)
files = {
str(p.relative_to(release)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted(release.rglob("*"))
if p.is_file()
}
(release / "manifest.json").write_text(
json.dumps(
{
"schema": "missioncore.vps-release/v1",
"environment": "ubuntu-24.04-amd64",
"files": files,
},
sort_keys=True,
indent=2,
)
+ "\n"
)
output = Path(output)
output.parent.mkdir(parents=True, exist_ok=True)
with tarfile.open(output, "w") as archive:
for file in sorted(release.rglob("*")):
info = archive.gettarinfo(
file, arcname="ndc-mission-vps/" + str(file.relative_to(release))
)
info.uid = info.gid = info.mtime = 0
info.uname = info.gname = ""
info.mode = 0o755 if file.is_dir() else 0o644
if file.is_file():
with file.open("rb") as stream:
archive.addfile(info, stream)
else:
archive.addfile(info)
installer = output.with_suffix(".pyz")
with zipfile.ZipFile(installer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
content = {"__main__.py": (release / "owner_entry.py").read_bytes()}
content.update(
{
"payload/" + str(p.relative_to(release)): p.read_bytes()
for p in sorted(release.rglob("*"))
if p.is_file()
}
)
for name, value in sorted(content.items()):
info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, value)
print(
json.dumps(
{
"artifact": str(output),
"installer": str(installer),
"installer_sha256": hashlib.sha256(installer.read_bytes()).hexdigest(),
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
"manifest_sha256": hashlib.sha256(
(release / "manifest.json").read_bytes()
).hexdigest(),
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--output", required=True)
build(parser.parse_args().output)
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Guest-only synthetic client for the isolated clean-host installer check."""
import base64
import http.client
import json
import os
import secrets
import ssl
import sys
from pathlib import Path
os.umask(0o077)
state = Path("/var/lib/ndc-mission-vps")
context = ssl.create_default_context(cafile=str(state / "tls.crt"))
context.check_hostname = False # This exact generated certificate is the only CA.
credentials = Path("/acceptance-client.json")
def request(method, path, body=None, token=None):
connection = http.client.HTTPSConnection("127.0.0.1", 19443, context=context, timeout=10)
headers = {"Content-Type": "application/json"}
if token:
headers["Authorization"] = "Bearer " + token
connection.request(method, path, json.dumps(body or {}), headers)
response = connection.getresponse()
value = json.loads(response.read())
connection.close()
assert response.status == 200, response.status
return value
if sys.argv[1] == "seed":
encoded = (state / "connect.key").read_text().strip().removeprefix("MCV1.")
invitation = json.loads(base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4)))
client = {
"core_id": "e" * 32,
"token": secrets.token_urlsafe(32),
"secret": invitation["secret"],
}
paired = request("POST", "/v1/pair", client)
client["host_id"] = paired["host_id"]
credentials.write_text(json.dumps(client))
request(
"PUT",
"/v1/devices",
{"items": [{"imei": "123456789012345", "instance_id": "a" * 32}]},
client["token"],
)
operation = request(
"POST",
"/v1/operations",
{
"id": "b" * 32,
"kind": "request-position",
"imei": "123456789012345",
"model": 231,
"firmware": "0.01",
},
client["token"],
)
assert operation["state"] == "queued" and operation["attempt_count"] == 0
else:
client = json.loads(credentials.read_text())
status = request("GET", "/v1/status", token=client["token"])
assert status["host_id"] == client["host_id"] and status["devices"] == 1
operation = request("GET", "/v1/operations/" + "b" * 32, token=client["token"])
assert operation["state"] == "queued" and operation["attempt_count"] == 0
print(json.dumps({"paired_identity": True, "device_registered": True, "queued_job_retained": True}))
+339
View File
@@ -0,0 +1,339 @@
#!/usr/bin/env python3
"""Owned server-only clean Ubuntu userspace acceptance in private namespaces.
Requires an official SHA256-verified Ubuntu Server 24.04 root tar and the shipped
installer. Does not install packages on the host or share its network/services.
This qualifies clean userspace, not a provider firewall or a different kernel.
"""
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import tarfile
import time
from pathlib import Path
def run(*argv, **kwargs):
return subprocess.run(argv, check=True, capture_output=True, text=True, **kwargs)
def main():
p = argparse.ArgumentParser()
p.add_argument("--stage", type=Path, required=True)
p.add_argument("--installer", type=Path, required=True)
p.add_argument("--image-sha256", required=True)
p.add_argument("--client", type=Path, required=True)
p.add_argument("--reuse-uninstalled-image", action="store_true")
mode = p.add_mutually_exclusive_group()
mode.add_argument("--migration-export", action="store_true")
mode.add_argument("--migration-import", type=Path)
p.add_argument("--state-sha256")
p.add_argument("--client-credentials", type=Path)
args = p.parse_args()
stage = args.stage.resolve()
if (
os.geteuid() != 0
or stage.parent != Path("/tmp")
or not stage.name.startswith("ndc-vps-clean-")
):
raise ValueError("root and an owned temporary stage required")
os.umask(0o077)
image = stage / "ubuntu-24.04-server-cloudimg-amd64-root.tar.xz"
with image.open("rb") as f:
if hashlib.file_digest(f, "sha256").hexdigest() != args.image_sha256:
raise ValueError("image digest mismatch")
root = stage / "rootfs"
if not args.reuse_uninstalled_image:
if shutil.disk_usage(stage).free < 2 * 1024**3:
raise ValueError("insufficient bounded staging disk")
root.mkdir(mode=0o755)
with tarfile.open(image) as tar:
for member in tar:
if member.name.startswith("/") or ".." in Path(member.name).parts:
raise ValueError("unsafe image path")
run("tar", "-xJf", str(image), "-C", str(root), timeout=120)
elif not root.is_dir():
raise ValueError("uninstalled image root missing")
# The enclosing evidence stage is private, but the guest's / must be
# traversable by its own service accounts. Tar may omit a root entry.
root.chmod(0o755)
assert not (root / "opt/nodedc-mission-vps").exists()
assert not (root / "var/lib/ndc-mission-vps").exists()
shutil.copyfile(args.installer, root / "installer.pyz")
shutil.copyfile(args.client, root / "acceptance-client.py")
if args.migration_import:
shutil.copyfile(args.migration_import, root / "portable-state.tar.gz")
shutil.copyfile(args.client_credentials, root / "acceptance-client.json")
# The following is the container substrate only. Product services, firewall,
# credentials, accounts and application paths are exclusively installer-owned.
script = stage / "init.sh"
script.write_text("""#!/bin/sh
set -eux
mount --make-rprivate /
R="$1"
mount --bind "$R" "$R"
mount -t proc proc "$R/proc"
mount -t sysfs sysfs "$R/sys"
mount -t cgroup2 cgroup2 "$R/sys/fs/cgroup"
mount -t tmpfs -o mode=755 tmpfs "$R/run"
mount -t tmpfs -o mode=755 tmpfs "$R/dev"
touch "$R/dev/console"
mount --bind "$2" "$R/dev/console"
for node in null zero random urandom tty; do
touch "$R/dev/$node"
mount --bind "/dev/$node" "$R/dev/$node"
done
mkdir -p "$R/dev/pts" "$R/dev/shm"
mount -t devpts devpts "$R/dev/pts"
mount -t tmpfs tmpfs "$R/dev/shm"
ln -s /proc/self/fd "$R/dev/fd"
ip link set lo up
hostname ndc-vps-clean
mkdir -p "$R/.old-root"
cd "$R"
pivot_root . .old-root
cd /
umount -l /.old-root
rmdir /.old-root
exec env container=other SYSTEMD_LOG_TARGET=console SYSTEMD_LOG_LEVEL=debug /sbin/init
""")
script.chmod(0o700)
unit = stage.name[:90]
results = {
"utc": time.time(),
"monotonic": time.monotonic(),
"image_sha256": args.image_sha256,
"installer_sha256": hashlib.sha256(args.installer.read_bytes()).hexdigest(),
"scope": "isolated clean Ubuntu userspace; host kernel shared",
}
try:
run(
"systemd-run",
"--quiet",
"--collect",
"--unit",
unit,
"--property=MemoryMax=256M",
"--property=CPUQuota=35%",
"--property=TasksMax=160",
"--property=TimeoutStopSec=5s",
"--property=RuntimeMaxSec=900",
"--property=Delegate=yes",
"--property=StandardOutput=append:" + str(stage / "console.log"),
"--property=StandardError=append:" + str(stage / "console.log"),
"--service-type=exec",
"unshare",
"--mount",
"--pid",
"--fork",
"--kill-child",
"--uts",
"--ipc",
"--net",
"--cgroup",
str(script),
str(root),
str(stage / "console.log"),
)
pid = None
for _ in range(30):
parent = run("systemctl", "show", unit, "--property=MainPID", "--value").stdout.strip()
if parent != "0":
children = Path(f"/proc/{parent}/task/{parent}/children").read_text().split()
if children:
candidate = children[0]
if Path(f"/proc/{candidate}/comm").read_text().strip() == "systemd":
pid = candidate
break
time.sleep(1)
if pid is None:
raise ValueError("isolated systemd did not start")
for namespace in ("mnt", "net", "pid", "uts", "ipc", "cgroup"):
assert os.readlink(f"/proc/{pid}/ns/{namespace}") != os.readlink(
f"/proc/1/ns/{namespace}"
), namespace
def inside(*command, timeout=120):
return run(
"nsenter",
"--target",
pid,
"--mount",
"--uts",
"--ipc",
"--net",
"--pid",
"--cgroup",
"--root",
"--wd",
*command,
timeout=timeout,
)
# Real host OS release, Python and product installation with no apt/pip.
results["os"] = inside("cat", "/etc/os-release").stdout
# A stock cloud image waits for a provider NIC during its first boot.
# This isolated guest deliberately has only loopback; let that existing
# OS wait expire before timing the product installer.
print(json.dumps({"phase": "waiting_for_guest_boot", "utc": time.time()}), flush=True)
for _ in range(90):
jobs = inside("systemctl", "list-jobs", "--no-pager", "--no-legend").stdout
if not jobs.strip():
break
time.sleep(2)
(stage / "boot-jobs.log").write_text(jobs)
print(json.dumps({"phase": "install", "utc": time.time()}), flush=True)
if args.migration_import:
result = inside(
"python3",
"/installer.pyz",
"--import-state",
"/portable-state.tar.gz",
"--sha256",
args.state_sha256,
timeout=240,
)
(stage / "import.stdout").write_text(result.stdout)
results["import"] = json.loads(
inside("python3", "/acceptance-client.py", "check").stdout
)
results["service"] = inside("systemctl", "is-active", "ndc-mission-vps").stdout.strip()
results["enabled"] = inside("systemctl", "is-enabled", "ndc-mission-vps").stdout.strip()
state = root / "var/lib/ndc-mission-vps"
with tarfile.open(args.migration_import) as archive:
for name in ("host.json", "tls.key", "tls.crt", "connect.key"):
assert (
archive.extractfile("state/" + name).read() == (state / name).read_bytes()
)
results["restored_identity_exact"] = True
results["listeners"] = inside("ss", "-lnt").stdout
assert ":19443" in results["listeners"] and ":9922" in results["listeners"]
inside("systemctl", "restart", "ndc-mission-vps")
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
inside("python3", "/acceptance-client.py", "check")
results.update(status="passed", restored_restart_accepted=True)
print(json.dumps(results), flush=True)
return
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test", timeout=240)
(stage / "install.stdout").write_text(result.stdout)
results["service"] = inside("systemctl", "is-active", "ndc-mission-vps").stdout.strip()
results["enabled"] = inside("systemctl", "is-enabled", "ndc-mission-vps").stdout.strip()
results["pairing"] = json.loads(inside("python3", "/acceptance-client.py", "seed").stdout)
before = {
name: hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
for name in ("host.json", "tls.crt", "tls.key", "connect.key")
}
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test")
(stage / "repeat.stdout").write_text(result.stdout)
assert "already_current" in result.stdout
after = {
name: hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
for name in before
}
assert before == after
results["repeat_preserves_identity"] = True
results["listeners"] = inside("ss", "-lnt").stdout
assert ":19443" in results["listeners"] and ":9922" in results["listeners"]
inside("systemctl", "restart", "ndc-mission-vps")
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
inside("python3", "/acceptance-client.py", "check")
results["restart_accepted"] = True
result = inside("python3", "/installer.pyz", "--host", "trackers.example.test", "--fresh")
(stage / "fresh.stdout").write_text(result.stdout)
backups = list((root / "var/backups/ndc-mission-vps").glob("*/backup.json"))
assert len(backups) == 1
assert (
hashlib.sha256((root / "var/lib/ndc-mission-vps/tls.crt").read_bytes()).hexdigest()
!= before["tls.crt"]
)
backup = "/" + str(backups[0].parent.relative_to(root))
result = inside(
"python3", "/installer.pyz", "--host", "trackers.example.test", "--restore", backup
)
(stage / "restore.stdout").write_text(result.stdout)
for name, digest in before.items():
assert (
hashlib.sha256((root / "var/lib/ndc-mission-vps" / name).read_bytes()).hexdigest()
== digest
)
results["restore"] = json.loads(inside("python3", "/acceptance-client.py", "check").stdout)
results["restore_identity_exact"] = True
if args.migration_export:
result = inside("python3", "/installer.pyz", "--export-state", "/portable-state.tar.gz")
(stage / "export.stdout").write_text(result.stdout)
receipt = json.loads(result.stdout)
assert receipt["status"] == "source_fenced"
inside("systemctl", "start", "ndc-mission-vps")
state = inside(
"systemctl", "show", "ndc-mission-vps", "--property=ActiveState", "--value"
)
assert state.stdout.strip() == "inactive"
# A subsequent installer must not bypass the persistent fence.
try:
inside("python3", "/installer.pyz", "--host", "trackers.example.test")
except subprocess.CalledProcessError:
pass
else:
raise AssertionError("normal installer bypassed source fencing")
results["source_fence_blocks_restart_and_install"] = True
shutil.copyfile(root / "portable-state.tar.gz", stage / "portable-state.private.tar.gz")
shutil.copyfile(
root / "acceptance-client.json", stage / "client-credentials.private.json"
)
results["state_sha256"] = receipt["sha256"]
# Exercise explicit abort before making the final transferable snapshot.
inside("python3", "/installer.pyz", "--resume-source")
inside("python3", "/acceptance-client.py", "check")
inside("python3", "/installer.pyz", "--export-state", "/portable-state-final.tar.gz")
shutil.copyfile(
root / "portable-state-final.tar.gz", stage / "portable-state.private.tar.gz"
)
results["state_sha256"] = hashlib.sha256(
(stage / "portable-state.private.tar.gz").read_bytes()
).hexdigest()
results["explicit_resume_accepted"] = True
results["status"] = "passed"
print(json.dumps(results), flush=True)
except Exception as exc:
if isinstance(exc, (subprocess.CalledProcessError, subprocess.TimeoutExpired)):
for name, value in (("stdout", exc.stdout), ("stderr", exc.stderr)):
(stage / ("failed." + name)).write_bytes(
value.encode() if isinstance(value, str) else value or b""
)
results.update(status="failed", error=type(exc).__name__ + ": " + str(exc))
(stage / "unit.log").write_text(
subprocess.run(
["journalctl", "-u", unit, "--no-pager", "-n", "120"],
capture_output=True,
text=True,
).stdout
)
raise
finally:
try:
subprocess.run(["systemctl", "stop", unit], capture_output=True, timeout=15)
except subprocess.TimeoutExpired:
subprocess.run(
["systemctl", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
capture_output=True,
timeout=10,
)
(stage / "result.json").write_text(json.dumps(results, indent=2))
print(
json.dumps(
{
"stage": str(stage),
"status": results.get("status"),
"temporary_unit_stopped": True,
}
),
flush=True,
)
if __name__ == "__main__":
main()