From ab8e977f11fa4f34f4f20cbe921b6b12338df193 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Wed, 4 Nov 2026 15:52:46 +0300 Subject: [PATCH] feat(node): add confirmed board shutdown with expiring commands --- .../src/core/fleet/useBoardPower.ts | 34 +++++ .../src/workspaces/fleet/BoardComputer.tsx | 2 + .../src/workspaces/fleet/BoardPowerAction.tsx | 17 +++ apps/node-agent/cmd/node-agent/main.go | 1 + apps/node-agent/internal/node/pairing.go | 1 + .../internal/node/pairing_transport.go | 6 + apps/node-agent/internal/node/power.go | 107 +++++++++++++++ apps/node-agent/internal/node/power_test.go | 111 +++++++++++++++ .../50-mission-core-node-power.rules | 9 ++ apps/node-agent/packaging/build_deb.py | 3 +- .../packaging/build_linux_source.py | 2 +- .../packaging/install_owner_release.py | 37 ++++- apps/node-agent/packaging/qualify_power.py | 94 +++++++++++++ apps/node-agent/packaging/repack_power.py | 99 ++++++++++++++ .../packaging/test_power_package.py | 90 ++++++++++++ docs/node/45_BOARD_POWER.md | 53 ++++++++ src/k1link/fleet/power.py | 126 +++++++++++++++++ src/k1link/fleet/registry.py | 3 + src/k1link/web/fleet_api.py | 2 + src/k1link/web/fleet_power_api.py | 46 +++++++ tests/fleet/test_power.py | 128 ++++++++++++++++++ 21 files changed, 967 insertions(+), 4 deletions(-) create mode 100644 apps/control-station/src/core/fleet/useBoardPower.ts create mode 100644 apps/control-station/src/workspaces/fleet/BoardPowerAction.tsx create mode 100644 apps/node-agent/internal/node/power.go create mode 100644 apps/node-agent/internal/node/power_test.go create mode 100644 apps/node-agent/packaging/50-mission-core-node-power.rules create mode 100644 apps/node-agent/packaging/qualify_power.py create mode 100644 apps/node-agent/packaging/repack_power.py create mode 100644 apps/node-agent/packaging/test_power_package.py create mode 100644 docs/node/45_BOARD_POWER.md create mode 100644 src/k1link/fleet/power.py create mode 100644 src/k1link/web/fleet_power_api.py create mode 100644 tests/fleet/test_power.py diff --git a/apps/control-station/src/core/fleet/useBoardPower.ts b/apps/control-station/src/core/fleet/useBoardPower.ts new file mode 100644 index 00000000..06136166 --- /dev/null +++ b/apps/control-station/src/core/fleet/useBoardPower.ts @@ -0,0 +1,34 @@ +import {useEffect, useRef, useState} from 'react'; +import {fleetRequest} from './useFleet'; + +export interface BoardPowerView { + available:boolean; epoch:string|null; reason:string; + operation:{id:string;state:string;message:string}|null; +} +export function useBoardPower(vehicleId:string) { + const [value,setValue]=useState(null); + const [error,setError]=useState(''); + const [busy,setBusy]=useState(false); + const sending=useRef(false); + useEffect(()=>{ + let active=true; let timer:ReturnType; + const controller=new AbortController(); + setValue(null);setError(''); + const poll=async()=>{ + try {const next=await fleetRequest(`/${encodeURIComponent(vehicleId)}/power`,'GET',undefined,8000,controller.signal);if(active)setValue(next);} + catch {if(active)setValue(current=>current?{...current,available:false,reason:'Состояние борта недоступно.'}:null);} + finally {if(active)timer=setTimeout(poll,1000);} + }; + void poll(); return()=>{active=false;controller.abort();clearTimeout(timer);}; + },[vehicleId]); + const shutdown=async(expectedEpoch:string)=>{ + if(sending.current)return false; + sending.current=true;setBusy(true);setError(''); + try { + const next=await fleetRequest(`/${encodeURIComponent(vehicleId)}/power/shutdown`,'POST',{expected_epoch:expectedEpoch,request_id:crypto.randomUUID()}); + setValue(next);return true; + } catch(e) {setError(e instanceof Error?e.message:'Не удалось передать команду.');return false;} + finally {sending.current=false;setBusy(false);} + }; + return {value,error,busy,shutdown}; +} diff --git a/apps/control-station/src/workspaces/fleet/BoardComputer.tsx b/apps/control-station/src/workspaces/fleet/BoardComputer.tsx index 27406815..dc321595 100644 --- a/apps/control-station/src/workspaces/fleet/BoardComputer.tsx +++ b/apps/control-station/src/workspaces/fleet/BoardComputer.tsx @@ -1,4 +1,5 @@ import {useState} from 'react'; +import {BoardPowerAction} from './BoardPowerAction'; import {useBoardNetwork} from '../../core/fleet/useBoardNetwork'; import {useBoardNetworkStatus} from '../../core/fleet/useBoardNetworkStatus'; import {BoardNetworkSettings} from './BoardNetworkSettings'; @@ -18,6 +19,7 @@ export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicl const network=useBoardNetwork(vehicle.id); const interfaces=useBoardNetworkStatus(vehicle,enabled); return } identity={{title:vehicle.host?.hostname||'Mission Core Node',subtitle:vehicle.node_id,avatarLabel:'БК'}} sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'},{id:'interfaces',label:'Сеть',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose} footer={{section==='network'&&}}> diff --git a/apps/control-station/src/workspaces/fleet/BoardPowerAction.tsx b/apps/control-station/src/workspaces/fleet/BoardPowerAction.tsx new file mode 100644 index 00000000..bf8b6b3f --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/BoardPowerAction.tsx @@ -0,0 +1,17 @@ +import {useState} from 'react'; +import {Button,ConfirmationModal,Icon,IconButton,Window,WindowFooterActions} from '@nodedc/ui-react'; +import {useBoardPower} from '../../core/fleet/useBoardPower'; + +export function BoardPowerAction({vehicleId,name,enabled}:{vehicleId:string;name:string;enabled:boolean}) { + const power=useBoardPower(vehicleId); + const [epoch,setEpoch]=useState(null); + const [receiptOpen,setReceiptOpen]=useState(false); + const available=enabled&&power.value?.available&&!power.busy; + return <> + setEpoch(power.value?.epoch||null)}> + {if(!power.busy)setEpoch(null);}} + onConfirm={async()=>{if(epoch&&await power.shutdown(epoch)){setEpoch(null);setReceiptOpen(true);}}} + description={<>

Вы уверены, что хотите выключить бортовой компьютер «{name}»?

Связь с бортом и его устройствами будет потеряна. Для включения потребуется доступ к компьютеру.

{power.error&&

{power.error}

}}/> + setReceiptOpen(false)} footer={}>

{power.value?.operation?.message||'Проверяем состояние команды…'}

+ ; +} diff --git a/apps/node-agent/cmd/node-agent/main.go b/apps/node-agent/cmd/node-agent/main.go index 6c8b2482..a3e30a95 100644 --- a/apps/node-agent/cmd/node-agent/main.go +++ b/apps/node-agent/cmd/node-agent/main.go @@ -80,6 +80,7 @@ func run() error { if err != nil { return err } + pairing.Power = node.NewNodePower() app.Pairing = pairing pairing.Budget = app.Budget pairing.Monitor = app.Monitor diff --git a/apps/node-agent/internal/node/pairing.go b/apps/node-agent/internal/node/pairing.go index 49d2ca54..a383c710 100644 --- a/apps/node-agent/internal/node/pairing.go +++ b/apps/node-agent/internal/node/pairing.go @@ -43,6 +43,7 @@ type PairState struct { Revocations []CoreBinding `json:"revocations,omitempty"` } type Pairing struct { + Power *NodePower Budget *LinkBudget Routers *routers.Collector RoverConfiguration *RoverConfigurationStore diff --git a/apps/node-agent/internal/node/pairing_transport.go b/apps/node-agent/internal/node/pairing_transport.go index a7f6f0d0..b28ae37b 100644 --- a/apps/node-agent/internal/node/pairing_transport.go +++ b/apps/node-agent/internal/node/pairing_transport.go @@ -347,6 +347,9 @@ func (p *Pairing) channel(ctx context.Context) { if p.RoverConfiguration != nil { payload["rover_configuration"] = p.RoverConfiguration.Snapshot() } + if p.Power != nil { + payload["power"] = p.Power.Snapshot(ctx) + } payload["network_profile"] = p.networkSnapshot() payload["core_endpoint"] = binding.Endpoint payload["endpoint_revision"] = binding.EndpointRevision @@ -378,6 +381,9 @@ func (p *Pairing) channel(ctx context.Context) { p.mu.Lock() if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision { if e == nil && status == 200 { + if p.Power != nil { + p.Power.Accept(ctx, binding.BindingID, result["power_command"], result["power_ack"]) + } networkRequestResult = result["network_request_result"] netbirdOffer = result["netbird_offer"] networkChange = result["network_profile_change"] diff --git a/apps/node-agent/internal/node/power.go b/apps/node-agent/internal/node/power.go new file mode 100644 index 00000000..7d7dcd75 --- /dev/null +++ b/apps/node-agent/internal/node/power.go @@ -0,0 +1,107 @@ +package node + +import ( + "context" + "encoding/json" + "os/exec" + "strings" + "sync" + "time" +) + +const powerSchema = "missioncore.node-power/v1" + +type powerCommand struct { + Schema string `json:"schema"` + ID string `json:"id"` + BindingID string `json:"binding_id"` + Epoch string `json:"epoch"` + Action string `json:"action"` + ExpiresAt float64 `json:"expires_at"` +} +type powerResult struct { + ID string `json:"id"` + State string `json:"state"` +} + +// NodePower has no durable queue. A new process has a new epoch, so an old +// confirmation cannot shut down a restarted or rebound board. +type NodePower struct { + mu sync.Mutex + epoch string + command powerCommand + result powerResult + seen map[string]bool + now func() time.Time + run func(context.Context, string) ([]byte, error) +} + +func NewNodePower() *NodePower { + return &NodePower{epoch: token(), seen: map[string]bool{}, now: time.Now, run: loginPower} +} + +func loginPower(ctx context.Context, method string) ([]byte, error) { + // Fixed D-Bus methods only; never a shell, arbitrary unit or user-supplied argv. + args := []string{"--system", "--timeout=3", "call", "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", method} + if method == "PowerOff" { + args = append(args, "b", "false") + } + return exec.CommandContext(ctx, "/usr/bin/busctl", args...).Output() +} + +func (p *NodePower) Snapshot(ctx context.Context) any { + call, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + out, err := p.run(call, "CanPowerOff") + p.mu.Lock() + defer p.mu.Unlock() + p.expire() + return map[string]any{"schema": powerSchema, "epoch": p.epoch, + "available": err == nil && strings.TrimSpace(string(out)) == `s "yes"` && len(p.seen) < 64 && p.result.State != "accepted" && p.result.State != "executing" && p.result.State != "submitted", "result": p.result} +} + +func (p *NodePower) expire() { + if p.result.State == "accepted" && float64(p.now().UnixNano())/1e9 >= p.command.ExpiresAt { + p.result.State = "expired" + } +} + +// Called while Pairing.mu still proves this heartbeat belongs to the current +// owner. Acceptance is reported on the next heartbeat; only its matching ack +// can execute the command. Lost replies and repeated requests never execute twice. +func (p *NodePower) Accept(ctx context.Context, binding string, raw, ackRaw json.RawMessage) { + p.mu.Lock() + defer p.mu.Unlock() + p.expire() + var ack string + if json.Unmarshal(ackRaw, &ack) == nil && ack == p.result.ID && p.result.State == "accepted" && binding == p.command.BindingID { + p.result.State = "executing" + go func() { + call, cancel := context.WithTimeout(ctx, 4*time.Second) + defer cancel() + _, err := p.run(call, "PowerOff") + p.mu.Lock() + defer p.mu.Unlock() + if err != nil { + p.result.State = "failed" + } else { + p.result.State = "submitted" + } + }() + return + } + var c powerCommand + if json.Unmarshal(raw, &c) != nil || c.Schema != powerSchema || c.Action != "poweroff" || c.BindingID != binding || c.Epoch != p.epoch || len(c.ID) != 36 || p.seen[c.ID] { + return + } + if p.result.State == "accepted" || p.result.State == "executing" || p.result.State == "submitted" || len(p.seen) >= 64 { + return + } + now := float64(p.now().UnixNano()) / 1e9 + p.seen[c.ID] = true + p.command = c + p.result = powerResult{ID: c.ID, State: "accepted"} + if c.ExpiresAt <= now || c.ExpiresAt > now+30 { + p.result.State = "expired" + } +} diff --git a/apps/node-agent/internal/node/power_test.go b/apps/node-agent/internal/node/power_test.go new file mode 100644 index 00000000..d95598f7 --- /dev/null +++ b/apps/node-agent/internal/node/power_test.go @@ -0,0 +1,111 @@ +package node + +import ( + "context" + "encoding/json" + "errors" + "sync/atomic" + "testing" + "time" +) + +func powerFixture() (*NodePower, powerCommand) { + p := NewNodePower() + p.now = func() time.Time { return time.Unix(1000, 0) } + c := powerCommand{Schema: powerSchema, ID: "12345678-1234-4234-8234-123456789abc", BindingID: "owner", Epoch: p.epoch, Action: "poweroff", ExpiresAt: 1020} + return p, c +} +func rawPower(v any) json.RawMessage { b, _ := json.Marshal(v); return b } + +func TestPowerRequiresAcknowledgedAcceptanceAndExecutesOnce(t *testing.T) { + p, c := powerFixture() + done := make(chan string, 4) + p.run = func(_ context.Context, m string) ([]byte, error) { done <- m; return nil, nil } + p.Accept(context.Background(), "owner", rawPower(c), nil) + p.Accept(context.Background(), "owner", rawPower(c), rawPower("wrong")) + if len(done) != 0 { + t.Fatal("executed without acknowledgement") + } + p.Accept(context.Background(), "owner", nil, rawPower(c.ID)) + select { + case m := <-done: + if m != "PowerOff" { + t.Fatal(m) + } + case <-time.After(time.Second): + t.Fatal("no shutdown") + } + p.Accept(context.Background(), "owner", rawPower(c), rawPower(c.ID)) + if len(done) != 0 { + t.Fatal("duplicate shutdown") + } +} + +func TestPowerRejectsStaleOrForeignCommands(t *testing.T) { + for _, change := range []func(*powerCommand){ + func(c *powerCommand) { c.BindingID = "other" }, func(c *powerCommand) { c.Epoch = "previous-process" }, + func(c *powerCommand) { c.ExpiresAt = 999 }, func(c *powerCommand) { c.ExpiresAt = 1100 }, + func(c *powerCommand) { c.Action = "reboot" }, func(c *powerCommand) { c.Schema = "wrong" }, + } { + p, c := powerFixture() + change(&c) + var calls atomic.Int32 + p.run = func(context.Context, string) ([]byte, error) { calls.Add(1); return nil, nil } + p.Accept(context.Background(), "owner", rawPower(c), nil) + p.Accept(context.Background(), "owner", nil, rawPower(c.ID)) + if calls.Load() != 0 || p.result.State == "executing" { + t.Fatal("foreign/stale command executed") + } + } +} + +func TestPowerLostAckExpiresWithoutShutdown(t *testing.T) { + p, c := powerFixture() + p.run = func(context.Context, string) ([]byte, error) { t.Error("must not execute"); return nil, nil } + p.Accept(context.Background(), "owner", rawPower(c), nil) + p.now = func() time.Time { return time.Unix(1021, 0) } + p.Accept(context.Background(), "owner", nil, rawPower(c.ID)) + if p.result.State != "expired" { + t.Fatal(p.result) + } +} + +func TestPowerCapabilityProbeIsReadOnlyAndFailClosed(t *testing.T) { + p, _ := powerFixture() + for _, output := range []string{`s "yes"`, `s "challenge"`, `s "no"`, ""} { + p.run = func(_ context.Context, m string) ([]byte, error) { + if m != "CanPowerOff" { + t.Fatal(m) + } + return []byte(output), nil + } + state := p.Snapshot(context.Background()).(map[string]any) + if state["available"] != (output == `s "yes"`) { + t.Fatal(state) + } + } + p.run = func(context.Context, string) ([]byte, error) { return nil, errors.New("denied") } + if p.Snapshot(context.Background()).(map[string]any)["available"] != false { + t.Fatal("failed open") + } +} + +func TestPowerFailureIsReportedAndNotRetried(t *testing.T) { + p, c := powerFixture() + done := make(chan bool) + p.run = func(context.Context, string) ([]byte, error) { defer close(done); return nil, errors.New("inhibited") } + p.Accept(context.Background(), "owner", rawPower(c), nil) + p.Accept(context.Background(), "owner", nil, rawPower(c.ID)) + <-done + deadline := time.Now().Add(time.Second) + for time.Now().Before(deadline) { + p.mu.Lock() + state := p.result.State + p.mu.Unlock() + if state == "failed" { + return + } + time.Sleep(time.Millisecond) + } + t.Fatal("failure not reported") +} diff --git a/apps/node-agent/packaging/50-mission-core-node-power.rules b/apps/node-agent/packaging/50-mission-core-node-power.rules new file mode 100644 index 00000000..5b8ed796 --- /dev/null +++ b/apps/node-agent/packaging/50-mission-core-node-power.rules @@ -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; + } +}); diff --git a/apps/node-agent/packaging/build_deb.py b/apps/node-agent/packaging/build_deb.py index 5038e465..4d8cb398 100644 --- a/apps/node-agent/packaging/build_deb.py +++ b/apps/node-agent/packaging/build_deb.py @@ -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 diff --git a/apps/node-agent/packaging/build_linux_source.py b/apps/node-agent/packaging/build_linux_source.py index 7ca8b165..ecd8a3ca 100644 --- a/apps/node-agent/packaging/build_linux_source.py +++ b/apps/node-agent/packaging/build_linux_source.py @@ -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" diff --git a/apps/node-agent/packaging/install_owner_release.py b/apps/node-agent/packaging/install_owner_release.py index cd427bd6..69f55242 100644 --- a/apps/node-agent/packaging/install_owner_release.py +++ b/apps/node-agent/packaging/install_owner_release.py @@ -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", [ diff --git a/apps/node-agent/packaging/qualify_power.py b/apps/node-agent/packaging/qualify_power.py new file mode 100644 index 00000000..f6d87bf6 --- /dev/null +++ b/apps/node-agent/packaging/qualify_power.py @@ -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) diff --git a/apps/node-agent/packaging/repack_power.py b/apps/node-agent/packaging/repack_power.py new file mode 100644 index 00000000..06178fb0 --- /dev/null +++ b/apps/node-agent/packaging/repack_power.py @@ -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"!\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) diff --git a/apps/node-agent/packaging/test_power_package.py b/apps/node-agent/packaging/test_power_package.py new file mode 100644 index 00000000..fb293699 --- /dev/null +++ b/apps/node-agent/packaging/test_power_package.py @@ -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"!\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() diff --git a/docs/node/45_BOARD_POWER.md b/docs/node/45_BOARD_POWER.md new file mode 100644 index 00000000..e52ed022 --- /dev/null +++ b/docs/node/45_BOARD_POWER.md @@ -0,0 +1,53 @@ +# Confirmed board shutdown + +The operator opens the existing **Бортовой компьютер** settings window and +uses the canonical `power` header action beside move/close. The danger +confirmation names the board; cancelling or Escape sends no command. This +extends the existing window: a new fleet route or a terminal command form is +not needed. Disabled, pending, accepted, expired and OS failure states are +visible. An acknowledgement never claims proof that the host has powered off. + +`POST /api/v1/fleet/{vehicle_id}/power/shutdown` is local-operator-only, takes +an expected process epoch and a request UUID, and accepts no command text. +`GET .../power` is no-store. Power support and its last receipt are bounded +latest state in RAM. There is no persistent command or historical telemetry. + +Node advertises `missioncore.node-power/v1` and a random per-process epoch on +the existing authenticated heartbeat. Core requires a capability less than +12 seconds old. Commands are bound to the current pairing and expire after +20 seconds. Node rejects wrong epochs, bindings, methods and expired commands; +it records acceptance, then waits for the matching Core acknowledgement before +invoking the OS once. A lost ack expires without execution. Reconnection, +process restart and duplicate delivery cannot replay an old power-off. +Clocks must agree within the short command window; disagreement fails closed. + +The fixed executor uses systemd-logind `PowerOff(false)` over the system bus +via `/usr/bin/busctl`. Capability discovery calls only `CanPowerOff`. +The installer-owned policy grants the `mission-core-node` account only +`org.freedesktop.login1.power-off` and `power-off-multiple-sessions`. +It grants neither reboot, arbitrary service control nor ignoring inhibitors. +See the [systemd interface](https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.login1.html). + +Node112 is an incremental package over qualified Node111; the Node binary, +provenance and package version change, and one policy is added. Other driver +payloads and maintainer scripts remain byte-identical. The full builder includes +the same policy. Distribution profile stays Ubuntu 24.04 amd64. Removing the +package or installing the pinned Node111 rollback removes the package-owned +policy; operator/runtime data stays intact. Downgrade is an explicit installer +operation, never an automatic retry of shutdown. + +Validation uses a fake OS executor for actual power-off. Live acceptance checks +the installed capability and opens/cancels the confirmation; it deliberately +does not shut down Rover006. Prepared-board acceptance does not claim a new +clean-image qualification. Detailed local evidence lives in +`outputs/board-power-20261104`. + +The release launcher also resumes a power-interrupted, half-configured Node +package only when it is the same version carried by the release and the only +package needing configuration. Pending cache triggers for dbus, +desktop-file-utils, gnome-menus and hicolor-icon-theme are allowed; they remain +for the normal APT transaction. It runs +`dpkg --no-triggers --configure mission-core-node` under the existing +CAN maintenance barrier, then continues normal APT installation. It never runs +`dpkg --configure -a`, deletes locks or interrupts a package manager. Recovery +is installer-owned; a different version or another incomplete package stops it. diff --git a/src/k1link/fleet/power.py b/src/k1link/fleet/power.py new file mode 100644 index 00000000..3f2e2fb5 --- /dev/null +++ b/src/k1link/fleet/power.py @@ -0,0 +1,126 @@ +"""Ephemeral, owner-bound power-off handshake. Never replay a persisted command.""" + +import time + +SCHEMA = "missioncore.node-power/v1" + + +class BoardPower: + # All access is under FleetRegistry.lock; no disk queue or background retry. + def __init__(self): + self.nodes = {} + self.operations = {} + + def heartbeat(self, row, value): + now = time.time() + key = row["id"] + binding = row["binding"]["binding_id"] + power = value.get("power") + if not isinstance(power, dict) or power.get("schema") != SCHEMA: + self.nodes.pop(key, None) + return {} + epoch = power.get("epoch") + if not isinstance(epoch, str) or len(epoch) != 43: + self.nodes.pop(key, None) + return {} + self.nodes[key] = dict( + at=now, binding=binding, epoch=epoch, available=power.get("available") is True + ) + op = self.operations.get(key) + if not op: + return {} + if op["binding"] != binding or op["epoch"] != epoch: + op.update(state="expired", message="Борт переподключился. Команда отменена.") + return {} + result = power.get("result") + if isinstance(result, dict) and result.get("id") == op["id"]: + state = result.get("state") + if state in ("accepted", "executing", "submitted", "failed", "expired"): + op["state"] = state + op["message"] = { + "accepted": "Борт принял команду выключения.", + "executing": "Борт выполняет выключение.", + "submitted": "Выключение запрошено. Связь с бортом будет потеряна.", + "failed": "Борт не смог выполнить выключение. Проверьте состояние системы.", + "expired": "Срок действия команды истёк. Выключение не выполнено.", + }[state] + self._expire(op, now) + if op["state"] == "queued": + return { + "power_command": { + "schema": SCHEMA, + "id": op["id"], + "binding_id": binding, + "epoch": epoch, + "action": "poweroff", + "expires_at": op["expires_at"], + } + } + if op["state"] == "accepted": + return {"power_ack": op["id"]} + return {} + + @staticmethod + def _expire(op, now): + if now >= op["expires_at"] and op["state"] in ("queued", "accepted", "executing"): + uncertain = op["state"] != "queued" + op.update( + state="unknown" if uncertain else "expired", + message=( + "Связь прервалась после приёма команды. Проверьте, выключился ли борт." + if uncertain + else "Борт не принял команду вовремя. Выключение отменено." + ), + ) + + def view(self, row): + now = time.time() + node = self.nodes.get(row["id"], {}) + op = self.operations.get(row["id"]) + if op: + self._expire(op, now) + bound = row.get("enrollment") == "paired" and node.get("binding") == ( + row.get("binding") or {} + ).get("binding_id") + fresh = bound and now - node.get("at", 0) < 12 + available = fresh and node.get("available", False) + pending = ( + op + and op["state"] in ("queued", "accepted", "executing", "submitted", "unknown") + and op["epoch"] == node.get("epoch") + ) + return { + "available": bool(available and not pending), + "epoch": node.get("epoch"), + "reason": "" + if available + else ( + "Выключение недоступно в текущей версии или окружении борта." + if not node + and row.get("enrollment") == "paired" + and now - (row.get("last_seen") or 0) < 12 + else ( + "Нет связи с бортом." + if not fresh + else "Выключение недоступно в текущем окружении борта." + ) + ), + "operation": {k: op[k] for k in ("id", "state", "message")} if op else None, + } + + def start(self, row, epoch, request_id): + current = self.operations.get(row["id"]) + if current and current["id"] == request_id: + return self.view(row) + view = self.view(row) + if not view["available"] or view["epoch"] != epoch: + raise ValueError(view["reason"] or "Состояние борта изменилось. Обновите окно.") + self.operations[row["id"]] = dict( + id=request_id, + epoch=epoch, + binding=row["binding"]["binding_id"], + expires_at=time.time() + 20, + state="queued", + message="Передаём команду выключения…", + ) + return self.view(row) diff --git a/src/k1link/fleet/registry.py b/src/k1link/fleet/registry.py index af6b0252..c4d8902c 100644 --- a/src/k1link/fleet/registry.py +++ b/src/k1link/fleet/registry.py @@ -38,6 +38,8 @@ class FleetRegistry: self.vps_hosts: VPSHosts | None = None self.lock = threading.RLock() self.presence: dict[str, dict] = {} + from .power import BoardPower + self.power = BoardPower() from .events import FleetEvents self.events = FleetEvents() @@ -574,6 +576,7 @@ class FleetRegistry: **sensor_response, **enrollment_response, **router_response, + **self.power.heartbeat(row, value), } def receive_liveness(self, row, value, address): diff --git a/src/k1link/web/fleet_api.py b/src/k1link/web/fleet_api.py index 6baf2ea8..9eee8c25 100644 --- a/src/k1link/web/fleet_api.py +++ b/src/k1link/web/fleet_api.py @@ -66,6 +66,8 @@ from .fleet_router_api import register as register_router_equipment register_router_equipment(router, local_operator) from .fleet_network_api import register as register_network_profiles register_network_profiles(router, local_operator) +from .fleet_power_api import register as register_power +register_power(router, local_operator) from .netbird_api import register as register_netbird register_netbird(router, local_operator) diff --git a/src/k1link/web/fleet_power_api.py b/src/k1link/web/fleet_power_api.py new file mode 100644 index 00000000..c2f8807e --- /dev/null +++ b/src/k1link/web/fleet_power_api.py @@ -0,0 +1,46 @@ +"""Explicit local-operator shutdown, delivered only over the bound mTLS channel.""" + +from typing import Annotated +from uuid import UUID + +from fastapi import Depends, HTTPException, Response +from pydantic import BaseModel, ConfigDict, Field + +from k1link.fleet.registry import FleetRegistry + + +class ShutdownRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + expected_epoch: str = Field(min_length=43, max_length=43) + request_id: UUID + + +def register(router, local_operator): + @router.get("/{vehicle_id}/power") + def view( + vehicle_id: str, + response: Response, + fleet: Annotated[FleetRegistry, Depends(local_operator)], + ): + response.headers["Cache-Control"] = "no-store" + with fleet.lock: + try: + return fleet.power.view(fleet.find(vehicle_id)) + except ValueError as error: + raise HTTPException(404, str(error)) from None + + @router.post("/{vehicle_id}/power/shutdown", status_code=202) + def shutdown( + vehicle_id: str, + body: ShutdownRequest, + response: Response, + fleet: Annotated[FleetRegistry, Depends(local_operator)], + ): + response.headers["Cache-Control"] = "no-store" + with fleet.lock: + try: + return fleet.power.start( + fleet.find(vehicle_id), body.expected_epoch, str(body.request_id) + ) + except ValueError as error: + raise HTTPException(409, str(error)) from None diff --git a/tests/fleet/test_power.py b/tests/fleet/test_power.py new file mode 100644 index 00000000..89c04f13 --- /dev/null +++ b/tests/fleet/test_power.py @@ -0,0 +1,128 @@ +"""No real power action: exercise expiry, identity, handshake and HTTP admission.""" + +import threading +from types import SimpleNamespace + +import pytest +from fastapi import APIRouter, FastAPI +from fastapi.testclient import TestClient + +from k1link.fleet.power import SCHEMA, BoardPower +from k1link.web.fleet_api import local_operator +from k1link.web.fleet_power_api import register + +EPOCH = "a" * 43 +ID = "12345678-1234-4234-8234-123456789abc" +ROW = {"id": "vehicle", "enrollment": "paired", "binding": {"binding_id": "owner"}} + + +@pytest.fixture +def power(monkeypatch): + clock = [1000.0] + monkeypatch.setattr("k1link.fleet.power.time.time", lambda: clock[0]) + p = BoardPower() + p.heartbeat(ROW, {"power": dict(schema=SCHEMA, epoch=EPOCH, available=True)}) + return p, clock + + +def test_operator_handshake_needs_fresh_capability_and_preserves_command_identity(power): + p, clock = power + assert p.view(ROW)["available"] + p.start(ROW, EPOCH, ID) + assert not p.view(ROW)["available"] + assert p.start(ROW, EPOCH, ID)["operation"]["id"] == ID + command = p.heartbeat(ROW, {"power": dict(schema=SCHEMA, epoch=EPOCH, available=True)}) + assert command["power_command"]["action"] == "poweroff" + assert command["power_command"]["binding_id"] == "owner" + assert "power_ack" not in command + ack = p.heartbeat( + ROW, + { + "power": dict( + schema=SCHEMA, epoch=EPOCH, available=True, result=dict(id=ID, state="accepted") + ) + }, + ) + assert ack == {"power_ack": ID} + assert p.view(ROW)["operation"]["state"] == "accepted" + clock[0] += 25 + assert p.view(ROW)["operation"]["state"] == "unknown" + assert not p.view(ROW)["available"] + + +@pytest.mark.parametrize( + "change", [{"epoch": "b" * 43}, {"binding": {"binding_id": "new"}}, {"enrollment": "revoked"}] +) +def test_wrong_epoch_rebinding_and_revocation_cannot_queue_shutdown(power, change): + p, _ = power + with pytest.raises(ValueError): + p.start( + ROW | {k: v for k, v in change.items() if k != "epoch"}, change.get("epoch", EPOCH), ID + ) + assert not p.operations + + +def test_expiry_and_missing_capability_never_replay_after_reconnection(power): + p, clock = power + p.start(ROW, EPOCH, ID) + clock[0] += 21 + assert p.heartbeat(ROW, {"power": dict(schema=SCHEMA, epoch=EPOCH, available=True)}) == {} + assert p.view(ROW)["operation"]["state"] == "expired" + p.heartbeat(ROW, {}) + with pytest.raises(ValueError): + p.start(ROW, EPOCH, "new") + assert not BoardPower().view(ROW)["available"] + + +def test_failed_os_call_is_visible_without_resubmitting(power): + p, _ = power + p.start(ROW, EPOCH, ID) + assert ( + p.heartbeat( + ROW, + { + "power": dict( + schema=SCHEMA, epoch=EPOCH, available=True, result=dict(id=ID, state="failed") + ) + }, + ) + == {} + ) + assert p.view(ROW)["operation"]["state"] == "failed" + + +def test_offline_or_restarted_node_requires_new_confirmation(power): + p, clock = power + clock[0] += 13 + with pytest.raises(ValueError): + p.start(ROW, EPOCH, ID) + p.heartbeat(ROW, {"power": dict(schema=SCHEMA, epoch="b" * 43, available=True)}) + with pytest.raises(ValueError): + p.start(ROW, EPOCH, ID) + + +def test_http_requires_local_operator_and_exact_body(power): + p, _ = power + app = FastAPI() + router = APIRouter(prefix="/api/v1/fleet") + register(router, local_operator) + app.include_router(router) + app.state.fleet = SimpleNamespace(power=p, lock=threading.RLock(), find=lambda _: ROW) + body = {"expected_epoch": EPOCH, "request_id": ID} + with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345)) as web: + path = "/api/v1/fleet/vehicle/power/shutdown" + assert ( + web.post(path, json=body, headers={"Origin": "https://unrelated.example"}).status_code + == 403 + ) + assert ( + web.post(path, json=body, headers={"Sec-Fetch-Site": "cross-site"}).status_code == 403 + ) + assert web.post(path, json=body | {"command": "reboot"}).status_code == 422 + assert web.post(path, json=body | {"request_id": "bad"}).status_code == 422 + assert not p.operations + assert web.post(path, json=body).status_code == 202 + assert web.post(path, json=body).status_code == 202 + result = web.get("/api/v1/fleet/vehicle/power") + assert result.headers["Cache-Control"] == "no-store" + assert result.json()["operation"]["state"] == "queued"