feat(node): add confirmed board shutdown with expiring commands
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
// Installer-owned: only graceful host power-off for the unprivileged Node.
|
||||
// Inhibitors, reboot and arbitrary systemd unit management are not granted.
|
||||
polkit.addRule(function(action, subject) {
|
||||
if (subject.user === "mission-core-node" &&
|
||||
(action.id === "org.freedesktop.login1.power-off" ||
|
||||
action.id === "org.freedesktop.login1.power-off-multiple-sessions")) {
|
||||
return polkit.Result.YES;
|
||||
}
|
||||
});
|
||||
@@ -12,7 +12,7 @@ import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BINARY_VERSION = "0.8.53"
|
||||
VERSION = "0.8.53-111"
|
||||
VERSION = "0.8.53-112"
|
||||
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
|
||||
from debian import package
|
||||
|
||||
@@ -106,6 +106,7 @@ Description: Mission Core onboard computer configuration
|
||||
files.append(("usr/lib/mission-core-node/" + name, (p / name).read_bytes(), 0o644))
|
||||
for name in ("mission-core-realsense.service", "mission-core-node-realsense-prepare.service"):
|
||||
files.append(("usr/lib/systemd/system/" + name, (p / name).read_bytes(), 0o644))
|
||||
files.append(("usr/share/polkit-1/rules.d/50-mission-core-node-power.rules", (p / "50-mission-core-node-power.rules").read_bytes(), 0o644))
|
||||
files.append(("usr/share/polkit-1/rules.d/50-mission-core-device-prepare.rules", (p / "50-mission-core-device-prepare.rules").read_bytes(), 0o644))
|
||||
# Node owns the first-use bootstrap; the optional model package owns its
|
||||
# SDK, worker processes, USB grants and runtime preparation. No overlapping
|
||||
|
||||
@@ -15,7 +15,7 @@ sys.path.insert(0, str(REPO / "scripts/packaging"))
|
||||
from build_retention import input_hold, publish_input # noqa: E402
|
||||
|
||||
DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE"
|
||||
DG_COMMIT = "972944e6f234eaaa24cd73543f9f1eef871f24c8"
|
||||
DG_COMMIT = "bbbfa8912f9f51914c6927e13ef32b823c536b9f"
|
||||
USB_CAN_SDK_SHA256 = "3f4681c64b086ecd4bf538908e09ed5203a05286632c0d99485b88f9b069285c"
|
||||
|
||||
|
||||
|
||||
@@ -129,6 +129,38 @@ def finish_legacy_monitor_pager():
|
||||
raise RuntimeError("Старая транзакция ещё не завершилась; она не прерывалась.")
|
||||
|
||||
|
||||
def resume_interrupted_node(run, version):
|
||||
"""Resume only this release's half-configured Node after power loss.
|
||||
|
||||
Never configure all packages, remove locks, or stop a package manager.
|
||||
dpkg owns its lock and refuses a concurrent transaction itself.
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["/usr/bin/dpkg-query", "-W", "-f", "${binary:Package}\t${Version}\t${Status}\n"],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Не удалось прочитать состояние пакетов для восстановления Node.")
|
||||
pending = []
|
||||
for line in result.stdout.splitlines():
|
||||
name, installed, status = line.split("\t", 2)
|
||||
if status.split()[-1] not in {"installed", "config-files", "not-installed"}:
|
||||
pending.append((name, installed, status))
|
||||
node = next((item for item in pending if item[0] == "mission-core-node"), None)
|
||||
if node is None:
|
||||
return {"required": False}
|
||||
# These installed dependencies refresh caches for files in the Node payload.
|
||||
# They are not half-installed packages and need no configuration recovery.
|
||||
cache_triggers = {"dbus", "desktop-file-utils", "gnome-menus", "hicolor-icon-theme"}
|
||||
foreign = [item for item in pending if item != node and not (
|
||||
item[0] in cache_triggers and item[2] == "install ok triggers-pending"
|
||||
)]
|
||||
if node != ("mission-core-node", version, "install ok half-configured") or foreign:
|
||||
raise RuntimeError("Незавершённая транзакция содержит другую версию или другие пакеты; автоматическое восстановление отменено.")
|
||||
run("node-configure-recovery", ["/usr/bin/dpkg", "--no-triggers", "--configure", "mission-core-node"], timeout=None)
|
||||
return {"required": True, "version": version, "state": "configured", "deferred_cache_triggers": [item[0] for item in pending if item != node]}
|
||||
|
||||
|
||||
def update_installed_x4(run):
|
||||
"""Upgrade an existing model through its fixed profile, even with camera off.
|
||||
|
||||
@@ -297,14 +329,15 @@ def main():
|
||||
"NRestarts",
|
||||
],
|
||||
)
|
||||
maintenance.begin()
|
||||
report["interrupted_node_recovery"] = resume_interrupted_node(run, version)
|
||||
publish()
|
||||
# APT refuses package removal and downgrade without explicit flags.
|
||||
# Its transaction is never killed by an observer timeout.
|
||||
run(
|
||||
"apt-plan",
|
||||
["/usr/bin/apt-get", "--simulate", "--no-remove", "install", *package_paths],
|
||||
)
|
||||
maintenance.begin()
|
||||
publish()
|
||||
run(
|
||||
"package",
|
||||
[
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Bounded prepared-Ubuntu package smoke check; never installs or opens hardware."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
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
|
||||
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.power.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="power-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 "Version: 0.8.53-112" in control
|
||||
rule = (
|
||||
root / "payload/usr/share/polkit-1/rules.d/50-mission-core-node-power.rules"
|
||||
).read_text()
|
||||
assert 'subject.user === "mission-core-node"' in rule
|
||||
assert 'action.id === "org.freedesktop.login1.power-off"' in rule
|
||||
assert 'action.id === "org.freedesktop.login1.power-off-multiple-sessions"' in rule
|
||||
assert "ignore-inhibit" not in rule and "manage-units" not in rule
|
||||
report["checks"].append(dict(id="narrow-power-policy", exit_code=0))
|
||||
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,
|
||||
)
|
||||
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,
|
||||
)
|
||||
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)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Node112 over the installed, qualified Node111; retain all other payloads."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
NODE = REPO / "apps/node-agent"
|
||||
VERSION = "0.8.53-112"
|
||||
BASE_SHA = "ff0327f13b4c25cc00ef81048c2341e993cfcf2dbf322adfa64ea4e6322a998b"
|
||||
sys.path.insert(0, str(REPO / "scripts/packaging"))
|
||||
from debian import package # noqa: E402
|
||||
|
||||
|
||||
def build(binary, output):
|
||||
if output.exists():
|
||||
raise FileExistsError("Published releases are immutable")
|
||||
raw = (NODE / "build/bms-111/mission-core-node_0.8.53-111_amd64.deb").read_bytes()
|
||||
if hashlib.sha256(raw).hexdigest() != BASE_SHA:
|
||||
raise ValueError("Qualified baseline changed")
|
||||
stream = io.BytesIO(raw)
|
||||
assert stream.read(8) == b"!<arch>\n"
|
||||
archives = {}
|
||||
while header := stream.read(60):
|
||||
size = int(header[48:58])
|
||||
name = header[:16].decode().strip().rstrip("/")
|
||||
archives[name] = stream.read(size)
|
||||
if size % 2:
|
||||
stream.read(1)
|
||||
|
||||
def members(name):
|
||||
with tarfile.open(fileobj=io.BytesIO(archives[name]), mode="r:gz") as archive:
|
||||
return [(m.name, archive.extractfile(m).read(), m.mode) for m in archive if m.isfile()]
|
||||
|
||||
controls, files = members("control.tar.gz"), members("data.tar.gz")
|
||||
old = {n: d for n, d, _ in files}
|
||||
compiled = binary.read_bytes()
|
||||
assert compiled[:6] == b"\x7fELF\x02\x01" and compiled[18:20] == b"\x3e\x00"
|
||||
source_files = {
|
||||
str(p.relative_to(REPO)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for directory in (NODE / "internal", NODE / "cmd", NODE / "packaging", NODE / "web/dist")
|
||||
for p in sorted(directory.rglob("*"))
|
||||
if p.is_file() and "__pycache__" not in p.parts
|
||||
}
|
||||
provenance = dict(
|
||||
schema="missioncore.node.packaging-revision/v1",
|
||||
version=VERSION,
|
||||
qualified_base_sha256=BASE_SHA,
|
||||
qualified_base_provenance=json.loads(
|
||||
old["usr/share/doc/mission-core-node/provenance.json"]
|
||||
),
|
||||
scope="Confirmed graceful power-off via paired mTLS heartbeat and scoped logind policy",
|
||||
binary_sha256=hashlib.sha256(compiled).hexdigest(),
|
||||
source_files=source_files,
|
||||
)
|
||||
changes = {
|
||||
"usr/lib/mission-core-node/node-agent": compiled,
|
||||
"usr/share/doc/mission-core-node/provenance.json": (
|
||||
json.dumps(provenance, indent=2) + "\n"
|
||||
).encode(),
|
||||
}
|
||||
rule = "usr/share/polkit-1/rules.d/50-mission-core-node-power.rules"
|
||||
assert rule not in old
|
||||
replaced = []
|
||||
for name, data, mode in controls:
|
||||
if name == "control":
|
||||
assert b"Version: 0.8.53-111\n" in data
|
||||
data = data.replace(b"Version: 0.8.53-111\n", f"Version: {VERSION}\n".encode())
|
||||
replaced.append((name, data, mode))
|
||||
payload = [(n, changes.get(n, d), m) for n, d, m in files]
|
||||
payload.append(
|
||||
(rule, (NODE / "packaging/50-mission-core-node-power.rules").read_bytes(), 0o644)
|
||||
)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_bytes(package(replaced, payload))
|
||||
report = dict(
|
||||
version=VERSION,
|
||||
base_sha256=BASE_SHA,
|
||||
sha256=hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
bytes=output.stat().st_size,
|
||||
changed_controls=["control"],
|
||||
changed_payloads=list(changes),
|
||||
added_payloads=[rule],
|
||||
retained_payload_count=len(files) - len(changes),
|
||||
)
|
||||
output.with_suffix(".json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--binary", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
build(args.binary, args.output)
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Package retention and privilege boundary, using only synthetic payloads."""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def load():
|
||||
spec = importlib.util.spec_from_file_location("power_repack", ROOT / "repack_power.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def unpack(raw):
|
||||
stream = io.BytesIO(raw)
|
||||
assert stream.read(8) == b"!<arch>\n"
|
||||
result = {}
|
||||
while header := stream.read(60):
|
||||
size = int(header[48:58])
|
||||
name = header[:16].decode().strip().rstrip("/")
|
||||
data = stream.read(size)
|
||||
if size % 2:
|
||||
stream.read(1)
|
||||
if name.endswith("tar.gz"):
|
||||
with tarfile.open(fileobj=io.BytesIO(data)) as archive:
|
||||
result[name] = {
|
||||
m.name: (archive.extractfile(m).read(), m.mode) for m in archive if m.isfile()
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def test_power_release_retains_unrelated_drivers_and_installer(tmp_path, monkeypatch):
|
||||
module = load()
|
||||
node = tmp_path / "apps/node-agent"
|
||||
(node / "build/bms-111").mkdir(parents=True)
|
||||
(node / "packaging").mkdir()
|
||||
(node / "packaging/50-mission-core-node-power.rules").write_bytes(
|
||||
(ROOT / "50-mission-core-node-power.rules").read_bytes()
|
||||
)
|
||||
controls = [
|
||||
("control", b"Package: mission-core-node\nVersion: 0.8.53-111\n", 0o644),
|
||||
("postinst", b"keep service preparation", 0o755),
|
||||
("prerm", b"keep rollback", 0o755),
|
||||
]
|
||||
files = [
|
||||
("usr/lib/mission-core-node/node-agent", b"old", 0o755),
|
||||
("usr/share/doc/mission-core-node/provenance.json", b"{}", 0o644),
|
||||
("usr/lib/device/driver", b"preserve sdk", 0o755),
|
||||
]
|
||||
base = module.package(controls, files)
|
||||
(node / "build/bms-111/mission-core-node_0.8.53-111_amd64.deb").write_bytes(base)
|
||||
monkeypatch.setattr(module, "NODE", node)
|
||||
monkeypatch.setattr(module, "REPO", tmp_path)
|
||||
monkeypatch.setattr(module, "BASE_SHA", hashlib.sha256(base).hexdigest())
|
||||
binary = tmp_path / "node"
|
||||
binary.write_bytes(b"\x7fELF\x02\x01" + b"0" * 12 + b"\x3e\x00")
|
||||
output = tmp_path / "release.deb"
|
||||
module.build(binary, output)
|
||||
before, after = unpack(base), unpack(output.read_bytes())
|
||||
assert after["control.tar.gz"]["postinst"] == before["control.tar.gz"]["postinst"]
|
||||
assert after["control.tar.gz"]["prerm"] == before["control.tar.gz"]["prerm"]
|
||||
assert (
|
||||
after["data.tar.gz"]["usr/lib/device/driver"]
|
||||
== before["data.tar.gz"]["usr/lib/device/driver"]
|
||||
)
|
||||
assert json.loads(output.with_suffix(".json").read_text())["retained_payload_count"] == 1
|
||||
with pytest.raises(FileExistsError):
|
||||
module.build(binary, output)
|
||||
monkeypatch.setattr(module, "BASE_SHA", "wrong")
|
||||
with pytest.raises(ValueError):
|
||||
module.build(binary, tmp_path / "other.deb")
|
||||
|
||||
|
||||
def test_policy_only_grants_graceful_poweroff_to_node():
|
||||
rule = (ROOT / "50-mission-core-node-power.rules").read_text()
|
||||
assert re.findall(r'action.id === "([^"]+)"', rule) == [
|
||||
"org.freedesktop.login1.power-off",
|
||||
"org.freedesktop.login1.power-off-multiple-sessions",
|
||||
]
|
||||
assert re.findall(r'subject.user === "([^"]+)"', rule) == ["mission-core-node"]
|
||||
assert "50-mission-core-node-power.rules" in (ROOT / "build_deb.py").read_text()
|
||||
Reference in New Issue
Block a user