feat(k1): stabilize LAB bridge and isolate onboard device integration
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
"""Bounded, transient delivery of Node-owned wireless device operations.
|
||||
|
||||
Unlike ordinary sensor operations these can contain a WLAN password. The
|
||||
pending payload never enters Fleet's database, listing, event stream or result.
|
||||
The Node owns the durable, redacted operation journal and at-most-once dispatch.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from .trust import PairingError
|
||||
|
||||
ACTIONS = {"scan", "networks", "connect", "verify"}
|
||||
|
||||
|
||||
def validate(value):
|
||||
if not isinstance(value, dict) or set(value) != {
|
||||
"operation_id",
|
||||
"node_id",
|
||||
"runtime_id",
|
||||
"action",
|
||||
"deadline_at",
|
||||
"parameters",
|
||||
}:
|
||||
raise PairingError("Неверный запрос подключения устройства.")
|
||||
if (
|
||||
not re.fullmatch(r"op_[0-9a-f]{32}", str(value["operation_id"]))
|
||||
or value["action"] not in ACTIONS
|
||||
or len(json.dumps(value)) > 16384
|
||||
or not isinstance(value["runtime_id"], str)
|
||||
or not value["runtime_id"]
|
||||
or len(value["runtime_id"]) > 128
|
||||
):
|
||||
raise PairingError("Неподдерживаемая операция подключения.")
|
||||
try:
|
||||
delta = (datetime.fromisoformat(value["deadline_at"]) - datetime.now(UTC)).total_seconds()
|
||||
if not 0 < delta <= 180:
|
||||
raise ValueError
|
||||
except (ValueError, TypeError):
|
||||
raise PairingError("Срок запроса истёк. Обновите устройства.") from None
|
||||
parameters = value["parameters"]
|
||||
expected = {"device_id", "discovery_generation", "mode_revision"}
|
||||
if value["action"] == "connect":
|
||||
expected |= {"ssid", "password"}
|
||||
elif value["action"] in {"scan", "networks"}:
|
||||
expected = set()
|
||||
if not isinstance(parameters, dict) or set(parameters) != expected:
|
||||
raise PairingError("Неверные параметры подключения.")
|
||||
if "device_id" in expected and (
|
||||
not isinstance(parameters["device_id"], str)
|
||||
or not 1 <= len(parameters["device_id"]) <= 128
|
||||
or type(parameters["discovery_generation"]) is not int
|
||||
or type(parameters["mode_revision"]) is not int
|
||||
or min(parameters["discovery_generation"], parameters["mode_revision"]) < 0
|
||||
):
|
||||
raise PairingError("Обновите выбранное устройство.")
|
||||
if value["action"] == "connect" and any(
|
||||
not isinstance(parameters[key], str) or not 1 <= len(parameters[key].encode()) <= limit
|
||||
for key, limit in (("ssid", 32), ("password", 64))
|
||||
):
|
||||
raise PairingError("Проверьте название сети и пароль.")
|
||||
|
||||
|
||||
class DeviceEnrollment:
|
||||
def __init__(self):
|
||||
# Access only under the enclosing FleetRegistry.lock.
|
||||
self.pending = {}
|
||||
|
||||
def prune(self):
|
||||
now = time.time()
|
||||
for key, entry in list(self.pending.items()):
|
||||
if now - entry["created"] > 600:
|
||||
del self.pending[key]
|
||||
elif entry["deadline"] <= now and entry["public"]["state"] in {"queued", "running"}:
|
||||
entry["payload"] = None
|
||||
entry["public"] = {
|
||||
"operation_id": key[1],
|
||||
"state": "unknown",
|
||||
"error": "Подтверждение с БК не получено. Обновите состояние K1.",
|
||||
}
|
||||
|
||||
def submit(self, fleet, vehicle_id, value):
|
||||
validate(value)
|
||||
with fleet.lock:
|
||||
self.prune()
|
||||
row = fleet.find(vehicle_id)
|
||||
state = row.get("device_enrollment", {})
|
||||
if (
|
||||
fleet.public(row)["connectivity"] != "online"
|
||||
or value["node_id"] != row["node_id"]
|
||||
or value["runtime_id"] != state.get("runtime_id")
|
||||
or state.get("available") is not True
|
||||
):
|
||||
raise PairingError("БК или служба K1 недоступны. Обновите устройства.")
|
||||
key = (vehicle_id, value["operation_id"])
|
||||
existing = self.pending.get(key)
|
||||
if existing:
|
||||
# First intent owns this ID; never accept replacement secrets.
|
||||
return copy.deepcopy(existing["public"])
|
||||
if len(self.pending) >= 32:
|
||||
raise PairingError("Слишком много запросов. Повторите позже.")
|
||||
public = {"operation_id": value["operation_id"], "state": "queued"}
|
||||
self.pending[key] = {
|
||||
"public": public,
|
||||
"payload": copy.deepcopy(value),
|
||||
"binding": row["binding"]["binding_id"],
|
||||
"node_id": row["node_id"],
|
||||
"created": time.time(),
|
||||
"deadline": datetime.fromisoformat(value["deadline_at"]).timestamp(),
|
||||
}
|
||||
return dict(public)
|
||||
|
||||
def operation(self, fleet, vehicle_id, identifier):
|
||||
with fleet.lock:
|
||||
self.prune()
|
||||
row = fleet.find(vehicle_id)
|
||||
entry = self.pending.get((vehicle_id, identifier))
|
||||
if not entry or entry["binding"] != (row.get("binding") or {}).get("binding_id"):
|
||||
# A Core restart loses transient delivery; never recreate it
|
||||
# from browser credentials or imply that a physical write failed.
|
||||
return {
|
||||
"operation_id": identifier,
|
||||
"state": "unknown",
|
||||
"error": "Результат запроса недоступен. Обновите состояние устройства.",
|
||||
}
|
||||
return copy.deepcopy(entry["public"])
|
||||
|
||||
def heartbeat(self, row, value):
|
||||
self.prune()
|
||||
state = value.get("device_enrollment", {"available": False})
|
||||
if not isinstance(state, dict) or len(json.dumps(state)) > 32768:
|
||||
raise ValueError("Invalid device enrollment state")
|
||||
row["device_enrollment"] = state
|
||||
acknowledgements = []
|
||||
results = value.get("enrollment_results", [])
|
||||
if not isinstance(results, list) or len(results) > 32:
|
||||
raise ValueError("Invalid enrollment results")
|
||||
for result in results:
|
||||
if not isinstance(result, dict) or len(json.dumps(result)) > 65536:
|
||||
raise ValueError("Invalid enrollment result")
|
||||
key = (row["id"], result.get("operation_id"))
|
||||
entry = self.pending.get(key)
|
||||
if (
|
||||
entry
|
||||
and entry["binding"] == row["binding"]["binding_id"]
|
||||
and result.get("state") in {"running", "complete", "error", "unknown"}
|
||||
):
|
||||
entry["payload"] = None # Node's journal now owns the intent.
|
||||
entry["public"] = {
|
||||
k: result[k]
|
||||
for k in ("operation_id", "state", "error", "result")
|
||||
if k in result
|
||||
}
|
||||
if result["state"] != "running":
|
||||
acknowledgements.append(result["operation_id"])
|
||||
elif result.get("state") != "running":
|
||||
acknowledgements.append(result.get("operation_id"))
|
||||
commands = []
|
||||
for (vehicle_id, _), entry in self.pending.items():
|
||||
if vehicle_id != row["id"]:
|
||||
continue
|
||||
if entry["binding"] != row["binding"]["binding_id"]:
|
||||
entry["payload"] = None
|
||||
entry["public"]["state"] = "unknown"
|
||||
elif entry["payload"] is not None:
|
||||
commands.append(entry["payload"])
|
||||
return {
|
||||
"enrollment_commands": commands[:2],
|
||||
"enrollment_acknowledgements": acknowledgements,
|
||||
}
|
||||
@@ -30,6 +30,9 @@ class FleetRegistry:
|
||||
from .events import FleetEvents
|
||||
|
||||
self.events = FleetEvents()
|
||||
from .device_enrollment import DeviceEnrollment
|
||||
|
||||
self.device_enrollment = DeviceEnrollment()
|
||||
self.trust = CoreTrust(root)
|
||||
path = root / "fleet.sqlite3"
|
||||
if path.is_symlink():
|
||||
@@ -378,6 +381,7 @@ class FleetRegistry:
|
||||
return 400, {"error": "Invalid Node inventory"}
|
||||
sensor_state = sensors.validate_inventory(value, node_id)
|
||||
sensor_response = sensors.heartbeat(row, value)
|
||||
enrollment_response = self.device_enrollment.heartbeat(row, value)
|
||||
host = value.get("host")
|
||||
if (
|
||||
not isinstance(host, dict)
|
||||
@@ -403,4 +407,4 @@ class FleetRegistry:
|
||||
}
|
||||
row["binding"]["client_pem"] = self.trust.leaf(node_id, key)
|
||||
self.save(row)
|
||||
return 200, {"ok": True, "client_pem": row["binding"]["client_pem"], **sensor_response}
|
||||
return 200, {"ok": True, "client_pem": row["binding"]["client_pem"], **sensor_response, **enrollment_response}
|
||||
|
||||
Reference in New Issue
Block a user