Files

140 lines
5.9 KiB
Python

"""Bounded prepared-Ubuntu package smoke check; never installs or opens hardware."""
import argparse
import hashlib
import json
import os
import platform
import re
import subprocess
import tempfile
import time
import uuid
from datetime import UTC, datetime
from pathlib import Path
def qualify(package, expected):
assert os.geteuid() != 0
match = re.fullmatch(
r"mission-core-node_([0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*)_amd64\.deb", package.name)
assert match, "Unexpected package identity"
version = match[1]
release = platform.freedesktop_os_release()
assert (release["ID"], release["VERSION_ID"], platform.machine()) == (
"ubuntu",
"24.04",
"x86_64",
)
raw = package.read_bytes()
assert hashlib.sha256(raw).hexdigest() == expected
report = dict(
schema="missioncore.uplink.prepared-host-package-check/v1",
session_id=uuid.uuid4().hex,
started_at=datetime.now(UTC).isoformat(),
monotonic_started=time.monotonic(),
clean_image_qualified=False,
hardware_access=False,
checks=[],
)
def run(name, args, allowed=(0,), **kwargs):
result = subprocess.run(args, capture_output=True, timeout=60, **kwargs)
assert result.returncode in allowed, name + ": " + result.stderr.decode()[:300]
report["checks"].append(dict(id=name, exit_code=result.returncode))
return result.stdout
with tempfile.TemporaryDirectory(prefix="router-api-package-", dir=package.parent) as scratch:
root = Path(scratch)
run("control", ["dpkg-deb", "-e", str(package), str(root / "control")])
run("payload", ["dpkg-deb", "-x", str(package), str(root / "payload")])
for name in ["postinst", "prerm"]:
run("shell-" + name, ["/bin/sh", "-n", str(root / "control" / name)])
control = (root / "control/control").read_text()
assert "python3-dbus" in control and "bluez (>= 5.72)" in control
assert f"Version: {version}\n" in control
profile_path = root / "payload/usr/share/mission-core-node/router-observation-profile.json"
profile = json.loads(profile_path.read_text())
assert profile["network_changes"] is False
assert any(
a["id"] == "dexaflow-client-api/v1" and a["identity"] == "device_ca"
for a in profile["adapters"]
)
report["checks"].append(dict(id="embedded-router-profile", exit_code=0))
uplink_root = root / "payload/usr/lib/mission-core-node"
for path in (uplink_root / "uplink").glob("*.py"):
compile(path.read_text(), str(path), "exec")
compile((uplink_root / "uplink_helper.py").read_text(), "uplink_helper.py", "exec")
run("netbird-policy-imports", ["/usr/bin/python3", "-B", "-c",
"import netbird_monitor; from netbird.client import safe_flags; "
"assert '--network-monitor=false' in safe_flags()"], cwd=uplink_root)
run(
"uplink-readonly-inventory",
[
"/usr/bin/python3",
"-B",
"-c",
"import json; from uplink.network_manager import NetworkManager; "
"from uplink.preferences import choice; "
"nm=NetworkManager(); state=nm.public(nm.inspect()); "
"assert state['supported']; assert state['current_id']; "
"assert len(state['candidates'])>=1; "
"profiles=nm.profile_preferences(); assert len(profiles)>0; "
"assert all(choice(p,p['id'],0)['metrics'][f]==p['saved']['metrics'][f] "
"for p in profiles.values() for f in p.get('inactive_families',[])); "
"print(json.dumps({'supported':state['supported'],'candidate_count':len(state['candidates'])}))",
],
cwd=uplink_root,
)
unit = root / "payload/usr/lib/systemd/system/mission-core-uplink.service"
# Verify service syntax against staged executable; no system installation.
text = unit.read_text().replace(
"/usr/lib/mission-core-node/uplink_helper.py", str(uplink_root / "uplink_helper.py")
)
unit.write_text(text)
run("uplink-unit-validation", ["systemd-analyze", "verify", str(unit)])
runtime = root / "payload/usr/lib/mission-core-jk-bms"
for path in runtime.rglob("*.py"):
compile(path.read_text(), str(path), "exec")
run(
"python-imports",
[
"/usr/bin/python3",
"-B",
"-c",
"import runtime.protocol, runtime.service, runtime.bluez, runtime.server; "
"from gi.repository import GLib",
],
cwd=runtime,
)
vesc = root / "payload/usr/lib/mission-core-vesc"
for path in (vesc / "runtime").glob("*.py"):
compile(path.read_text(), str(path), "exec")
run("vesc-recovery-imports", ["/usr/bin/python3", "-B", "-c",
"from runtime.remote_control import RemoteControl; "
"from runtime.preflight_recovery import PreflightRecovery; "
"assert PreflightRecovery({'bindings': {}}, cancelled=True).cancelled"], cwd=vesc)
help_text = run(
"node-executable-help",
[str(root / "payload/usr/lib/mission-core-node/node-agent"), "--help"],
allowed=(0, 1, 2),
)
assert len(help_text) < 65536
run("apt-simulation", ["apt-get", "--simulate", "--no-remove", "install", str(package)])
report.update(
state="complete",
finished_at=datetime.now(UTC).isoformat(),
duration_seconds=time.monotonic() - report["monotonic_started"],
package_sha256=expected,
version=version,
)
print(json.dumps(report))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("package", type=Path)
parser.add_argument("sha256")
args = parser.parse_args()
qualify(args.package.resolve(), args.sha256)