From f3a7592d909739fe98a73c50af601b35681112ea Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Mon, 28 Sep 2026 18:44:12 +0300 Subject: [PATCH] feat(fleet): integrate independent trackers, VPS pairing and recoverable commands --- scripts/publish_equipment_firmware.py | 23 + scripts/publish_fleet_installer.py | 65 + src/k1link/fleet/equipment_actions.py | 46 + src/k1link/fleet/equipment_bootstrap.py | 65 + src/k1link/fleet/equipment_command_catalog.py | 80 + src/k1link/fleet/equipment_command_journal.py | 198 ++ .../fleet/equipment_command_reconciliation.py | 38 + src/k1link/fleet/equipment_command_runtime.py | 188 ++ src/k1link/fleet/equipment_configuration.py | 72 + src/k1link/fleet/equipment_connectivity.py | 67 + src/k1link/fleet/equipment_firmware.py | 132 + src/k1link/fleet/equipment_network.py | 902 +++++++ src/k1link/fleet/equipment_operations.py | 107 + src/k1link/fleet/equipment_outbox.py | 51 + src/k1link/fleet/independent_equipment.py | 285 ++ src/k1link/fleet/registry.py | 9 + src/k1link/fleet/vps_hosts.py | 467 ++++ src/k1link/fleet/vps_transport.py | 150 ++ src/k1link/web/app.py | 9 + src/k1link/web/equipment_firmware_api.py | 74 + src/k1link/web/independent_equipment_api.py | 258 ++ .../web/independent_equipment_composition.py | 19 + src/k1link/web/installer_api.py | 69 + src/k1link/web/vps_host_api.py | 108 + tests/test_b2_automatic_connectivity.py | 160 ++ tests/test_b2_cellular_telemetry.py | 161 ++ tests/test_b2_dual_sim.py | 131 + tests/test_b2_native_connectivity.py | 78 + tests/test_b2_output_telemetry.py | 86 + tests/test_b2_sim_identity.py | 254 ++ tests/test_b2_sim_network.py | 218 ++ tests/test_equipment_bootstrap.py | 81 + .../test_equipment_command_reconciliation.py | 114 + tests/test_equipment_command_runtime.py | 398 +++ tests/test_equipment_firmware.py | 82 + tests/test_equipment_network.py | 875 +++++++ tests/test_equipment_operations.py | 161 ++ tests/test_fleet_installers.py | 33 + tests/test_independent_equipment.py | 365 +++ tests/test_vps_command_receipts.py | 93 + tests/test_vps_host.py | 2303 +++++++++++++++++ tests/test_vps_installer_permissions.py | 60 + tests/test_vps_operations.py | 379 +++ tests/test_vps_packet_commit.py | 208 ++ tests/test_vps_portable_state.py | 284 ++ 45 files changed, 10006 insertions(+) create mode 100644 scripts/publish_equipment_firmware.py create mode 100644 scripts/publish_fleet_installer.py create mode 100644 src/k1link/fleet/equipment_actions.py create mode 100644 src/k1link/fleet/equipment_bootstrap.py create mode 100644 src/k1link/fleet/equipment_command_catalog.py create mode 100644 src/k1link/fleet/equipment_command_journal.py create mode 100644 src/k1link/fleet/equipment_command_reconciliation.py create mode 100644 src/k1link/fleet/equipment_command_runtime.py create mode 100644 src/k1link/fleet/equipment_configuration.py create mode 100644 src/k1link/fleet/equipment_connectivity.py create mode 100644 src/k1link/fleet/equipment_firmware.py create mode 100644 src/k1link/fleet/equipment_network.py create mode 100644 src/k1link/fleet/equipment_operations.py create mode 100644 src/k1link/fleet/equipment_outbox.py create mode 100644 src/k1link/fleet/independent_equipment.py create mode 100644 src/k1link/fleet/vps_hosts.py create mode 100644 src/k1link/fleet/vps_transport.py create mode 100644 src/k1link/web/equipment_firmware_api.py create mode 100644 src/k1link/web/independent_equipment_api.py create mode 100644 src/k1link/web/independent_equipment_composition.py create mode 100644 src/k1link/web/installer_api.py create mode 100644 src/k1link/web/vps_host_api.py create mode 100644 tests/test_b2_automatic_connectivity.py create mode 100644 tests/test_b2_cellular_telemetry.py create mode 100644 tests/test_b2_dual_sim.py create mode 100644 tests/test_b2_native_connectivity.py create mode 100644 tests/test_b2_output_telemetry.py create mode 100644 tests/test_b2_sim_identity.py create mode 100644 tests/test_b2_sim_network.py create mode 100644 tests/test_equipment_bootstrap.py create mode 100644 tests/test_equipment_command_reconciliation.py create mode 100644 tests/test_equipment_command_runtime.py create mode 100644 tests/test_equipment_firmware.py create mode 100644 tests/test_equipment_network.py create mode 100644 tests/test_equipment_operations.py create mode 100644 tests/test_fleet_installers.py create mode 100644 tests/test_independent_equipment.py create mode 100644 tests/test_vps_command_receipts.py create mode 100644 tests/test_vps_host.py create mode 100644 tests/test_vps_installer_permissions.py create mode 100644 tests/test_vps_operations.py create mode 100644 tests/test_vps_packet_commit.py create mode 100644 tests/test_vps_portable_state.py diff --git a/scripts/publish_equipment_firmware.py b/scripts/publish_equipment_firmware.py new file mode 100644 index 00000000..b00f6993 --- /dev/null +++ b/scripts/publish_equipment_firmware.py @@ -0,0 +1,23 @@ +"""Archive a local firmware file without contacting or flashing any device.""" + +import argparse +import json +from pathlib import Path + +from k1link.device_plugins.arnavi_b2.firmware import KNOWN_IMAGES +from k1link.fleet.equipment_firmware import FirmwareArchive + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--fleet-root", required=True, type=Path) + parser.add_argument("--file", required=True, type=Path) + parser.add_argument("--filename") + args = parser.parse_args() + store = FirmwareArchive(args.fleet_root, {"arnavi-b2": KNOWN_IMAGES}) + item = store.add("arnavi-b2", args.filename or args.file.name, args.file.read_bytes()) + print(json.dumps(item, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/scripts/publish_fleet_installer.py b/scripts/publish_fleet_installer.py new file mode 100644 index 00000000..b3339c41 --- /dev/null +++ b/scripts/publish_fleet_installer.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Publish an externally qualified installer with an explicit accepted checksum.""" + +import argparse +import hashlib +import json +import os +import re +import shutil +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--fleet-root", type=Path, required=True) + parser.add_argument("--file", type=Path, required=True) + parser.add_argument("--sha256", required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--kind", choices=("node", "vps-arnavi"), required=True) + args = parser.parse_args() + if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9]+)?", args.version): + raise ValueError("Invalid release version") + with args.file.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + if digest != args.sha256 or args.file.suffix != ".pyz": + raise ValueError("Qualified installer checksum mismatch") + root = args.fleet_root / "installers" + root.mkdir(mode=0o700, exist_ok=True) + name = f"{args.kind}-{args.version}-{digest[:12]}.pyz" + target = root / name + temporary = root / (name + ".new") + shutil.copyfile(args.file, temporary) + temporary.chmod(0o600) + os.replace(temporary, target) + vps = args.kind == "vps-arnavi" + value = { + "id": args.kind, + "filename": name, + "version": args.version, + "label": "VPS Host ARNavi" if vps else "Бортовой компьютер", + "os": "Ubuntu Server 24.04 LTS · x86-64" if vps else "Ubuntu 24.04 LTS · x86-64 · GNOME", + "bytes": target.stat().st_size, + "sha256": digest, + "instructions": [ + "Скопируйте файл на VPS. Запустите: sudo python3 mission-core-vps-install.pyz" + if vps + else "Перенесите файл на бортовой ПК. Откройте окно установки: " + "python3 mission-core-node-install.pyz --launch", + "Укажите публичный адрес сервера; дождитесь завершения установки." + if vps + else "Завершите установку и откройте Node.", + "Скопируйте ключ подключения VPS в поле ниже." + if vps + else "Создайте в Node код приглашения и вставьте его в поле ниже.", + ], + } + temporary = root / (args.kind + ".json.new") + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + temporary.chmod(0o600) + os.replace(temporary, root / (args.kind + ".json")) + print(json.dumps({"published": args.kind, "version": args.version, "sha256": digest})) + + +if __name__ == "__main__": + main() diff --git a/src/k1link/fleet/equipment_actions.py b/src/k1link/fleet/equipment_actions.py new file mode 100644 index 00000000..bd932fa0 --- /dev/null +++ b/src/k1link/fleet/equipment_actions.py @@ -0,0 +1,46 @@ +"""Firmware-qualified commands, separate from desired configuration/profile writes.""" + +from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration + +from .independent_equipment import Document, EquipmentError, EquipmentStore + +KINDS = {"request-position", "pulse-output", "set-output", "restart"} + + +def plan(equipment: EquipmentStore, row: Document, command: Document) -> Document: + if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01": + raise EquipmentError("Команды для этой версии устройства не проверены.") + kind = command.get("kind") + if kind not in KINDS: + raise EquipmentError("Эта команда не поддерживается.") + config = decode_configuration( + (equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").read_bytes() + ) + allowed = {"kind"} + if kind in ("pulse-output", "set-output"): + allowed |= {"pin", "seconds" if kind == "pulse-output" else "enabled"} + pin = command.get("pin") + if type(pin) is not int or pin not in (4, 5, 6): + raise EquipmentError("Выберите выход PIN4–PIN6.") + seconds = command.get("seconds") + if kind == "pulse-output" and (type(seconds) is not int or not 1 <= seconds <= 5): + raise EquipmentError("Длительность импульса — от 1 до 5 секунд.") + if kind == "set-output" and type(command.get("enabled")) is not bool: + raise EquipmentError("Укажите включение или выключение выхода.") + if config.integer(16 + pin, 1) != 1: + raise EquipmentError("У выбранного выхода не подтверждён ручной режим управления.") + if set(command) != allowed: + raise EquipmentError("Некорректные параметры команды.") + private = ( + {} + if kind in ("request-position", "restart") + else {"encoding": "text", "password": config.text(5)} + ) + return { + **command, + **private, + "imei": row["identity_key"], + "model": 231, + "firmware": "0.01", + "secondary": {"host": config.text(3), "port": config.integer(4, 2)}, + } diff --git a/src/k1link/fleet/equipment_bootstrap.py b/src/k1link/fleet/equipment_bootstrap.py new file mode 100644 index 00000000..7c69f83c --- /dev/null +++ b/src/k1link/fleet/equipment_bootstrap.py @@ -0,0 +1,65 @@ +"""Admit the owner VPS before touching the tracker's initial USB channels.""" + +import time + +from .independent_equipment import EquipmentError + + +def apply(hosts, identifier, revision): + equipment = hosts.equipment + with hosts.lock: + row = next((r for r in equipment.listing() if r["id"] == identifier), None) + if row is None or row["revision"] != revision: + raise EquipmentError("Настройки изменились. Откройте устройство заново.") + equipment.require_idle(row) + endpoint = row["settings"].get("endpoint") + if not endpoint or endpoint["slot"] != 1: + raise EquipmentError("Выберите ваш VPS как сервер 1 для первоначальной настройки.") + host = next( + ( + h + for h in hosts.rows() + if h["state"] == "paired" + and row["vehicle_id"] in h["vehicle_ids"] + and h.get("status", {}).get("tracker") == {k: endpoint[k] for k in ("host", "port")} + ), + None, + ) + if not host: + raise EquipmentError("Сначала подключите выбранный VPS к этому аппарату.") + hosts.sync(host) # durably admit this device before its first cellular connection + if ( + host.get("status", {}).get("version") + not in ( + "0.1.15", + "0.1.16", + "0.1.17", + "0.1.18", + "0.1.19", + "0.1.20", + "0.1.21", + "0.1.22", + "0.1.23", + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + ) + or time.time() - host["last_sync_at"] > 30 + ): + raise EquipmentError("Установите актуальный VPS Host и проверьте связь с ним.") + return equipment.apply(identifier, revision) diff --git a/src/k1link/fleet/equipment_command_catalog.py b/src/k1link/fleet/equipment_command_catalog.py new file mode 100644 index 00000000..363e4ec2 --- /dev/null +++ b/src/k1link/fleet/equipment_command_catalog.py @@ -0,0 +1,80 @@ +"""Firmware-qualified, human-readable actions. Previews never contain credentials.""" + +from .equipment_actions import plan +from .independent_equipment import Document, EquipmentError, EquipmentStore + + +def presets() -> list[Document]: + values = [ + { + "id": "position", + "label": "Запросить координаты", + "command": {"kind": "request-position"}, + "wire": "01 01", + "encoding": "INTERNAL · FF", + "queue_seconds": 30, + "confirmation": "Ответ B2 с токеном команды. Новая позиция зависит от GNSS.", + }, + { + "id": "restart", + "label": "Перезапустить B2", + "command": {"kind": "restart"}, + "wire": "01 07", + "encoding": "INTERNAL · FF", + "queue_seconds": 3, + "confirmation": "Свежие данные B2 по новому соединению после команды.", + }, + ] + for pin in (4, 5, 6): + for enabled in (True, False): + values.append( + { + "id": f"pin{pin}-{'on' if enabled else 'off'}", + "label": f"{'Включить' if enabled else 'Выключить'} выход PIN{pin}", + "command": {"kind": "set-output", "pin": pin, "enabled": enabled}, + "wire": f"••••••*SERV*8.{pin}.{int(enabled)}", + "encoding": "INTERNAL · FC", + "queue_seconds": 3, + "confirmation": "Текстовая команда без токена. " + "Ответ не доказывает положение контактов реле.", + } + ) + values.append( + { + "id": f"pin{pin}-pulse", + "label": f"Импульс PIN{pin} · 5 с", + "command": {"kind": "pulse-output", "pin": pin, "seconds": 5}, + "wire": f"••••••*SERV*24.{pin}.0.5", + "encoding": "INTERNAL · FC", + "queue_seconds": 3, + "confirmation": "Текстовая команда без токена. " + "Ответ не доказывает положение контактов реле.", + } + ) + return values + + +def describe(command: Document | None, kind: str) -> Document: + for value in presets(): + if value["command"] == command: + return {k: v for k, v in value.items() if k != "command"} + labels = { + "read-configuration": "Прочитать настройки", + "configure-all": "Применить настройки", + "select-sim": "Переключить SIM", + "read-settings": "Прочитать сервер", + "configure-server1": "Изменить сервер", + } + return {"label": labels.get(kind, "Операция B2"), "wire": "", "encoding": "INTERNAL"} + + +def catalog(equipment: EquipmentStore, row: Document) -> list[Document]: + result = [] + for preset in presets(): + reason = "" + try: + plan(equipment, row, preset["command"]) + except (EquipmentError, ValueError, OSError): + reason = "Команда недоступна для прочитанной прошивки или режима выхода." + result.append({**preset, "firmware": row["observed"]["firmware"], "unavailable": reason}) + return result diff --git a/src/k1link/fleet/equipment_command_journal.py b/src/k1link/fleet/equipment_command_journal.py new file mode 100644 index 00000000..62c677ab --- /dev/null +++ b/src/k1link/fleet/equipment_command_journal.py @@ -0,0 +1,198 @@ +"""Durable, redacted operation history and observed transitions in Core.""" + +import json +import time + +from .equipment_command_catalog import describe + +PENDING = {"waiting", "submitting", "queued", "dispatched"} +FIELDS = { + "id", + "host_id", + "state", + "scope", + "kind", + "command", + "stage", + "read_only", + "created_at", + "vps_created_at", + "expires_at", + "dispatched_at", + "received_at", + "verified_at", + "configuration_received_at", + "write_reply_sent_at", + "queue_seconds", + "roundtrip_seconds", + "device_code", + "device_accepted_at", + "durable", + "runtime_phase", + "attempt_count", + "next_attempt_at", + "attempt_expires_at", + "stop_requested", + "reconnected_at", + "reconnect_seconds", + "unchanged", + "active_sim", + "reconcile_pending", + "recovery_at", + "recovery_count", + "recovery_verification", +} + + +def initialize(db): + db.executescript(""" + CREATE TABLE IF NOT EXISTS command_journal(seq INTEGER PRIMARY KEY AUTOINCREMENT, + id TEXT UNIQUE NOT NULL, instance TEXT NOT NULL, + state TEXT NOT NULL, body TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS command_journal_device ON command_journal(instance,seq); + CREATE INDEX IF NOT EXISTS command_journal_pending ON command_journal(state,seq); + CREATE TABLE IF NOT EXISTS command_journal_migrations(name TEXT PRIMARY KEY); + CREATE TABLE IF NOT EXISTS command_result_probes(id TEXT PRIMARY KEY, + instance TEXT NOT NULL,host TEXT NOT NULL,body TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0,next_attempt REAL NOT NULL DEFAULT 0); + CREATE INDEX IF NOT EXISTS command_result_probes_due + ON command_result_probes(host,next_attempt); + """) + if db.execute("SELECT 1 FROM command_journal_migrations WHERE name='history-v1'").fetchone(): + return + for (body,) in db.execute("SELECT body FROM history ORDER BY revision").fetchall(): + row = json.loads(body) + capture(db, row, historical=True) + current = set() + for (body,) in db.execute("SELECT body FROM instances").fetchall(): + row = json.loads(body) + capture(db, row, historical=True) + current.add(row.get("network_operation", {}).get("id")) + for instance, body in db.execute( + "SELECT instance,body FROM command_journal " + "WHERE state IN ('submitting','queued','dispatched')" + ).fetchall(): + value = json.loads(body) + if value["id"] not in current: + finish(db, instance, value, "uncertain", "historical_result_missing") + db.execute("INSERT INTO command_journal_migrations VALUES('history-v1')") + + +def capture(db, row, *, historical=False): + op = row.get("network_operation") + if not op or not op.get("id"): + return + found = db.execute("SELECT body FROM command_journal WHERE id=?", (op["id"],)).fetchone() + old = json.loads(found[0]) if found else None + previous = dict(old or {}) + if op.get("durable"): + from .equipment_operations import ATTEMPT_FACTS + + for field in ATTEMPT_FACTS: + previous.pop(field, None) + value = {**previous, **{k: v for k, v in op.items() if k in FIELDS}} + value.setdefault("description", describe(op.get("command"), op.get("kind", ""))) + value.setdefault("firmware", row.get("observed", {}).get("firmware")) + value.setdefault("events", []) + if value.get("attempt_count", 0) > (old or {}).get("attempt_count", 0): + value["events"].append( + { + "state": "attempt_started", + "attempt": value["attempt_count"], + "observed_at": time.time(), + "occurred_at": op.get("dispatched_at", time.time()), + "historical": historical, + } + ) + if not historical: + for field, state in ( + ("vps_created_at", "queued"), + ("dispatched_at", "dispatched"), + ("device_accepted_at", "device_accepted"), + ("received_at", value["state"]), + ("reconnected_at", "reconnected"), + ("verified_at", value["state"]), + ("recovery_at", "queued"), + ): + if field in value and not any( + e.get("evidence") == field and e.get("occurred_at") == value[field] + for e in value["events"] + ): + value["events"].append( + { + "state": state, + "occurred_at": value[field], + "observed_at": time.time(), + "historical": False, + "evidence": field, + } + ) + transition = (value["state"], value.get("stage")) + if not old or transition != (old["state"], old.get("stage")): + value["events"].append( + { + "state": value["state"], + "stage": value.get("stage"), + "observed_at": time.time(), + "historical": historical, + } + ) + value["updated_at"] = time.time() + put(db, row["id"], value) + + +def put(db, instance, value): + db.execute( + "INSERT INTO command_journal(id,instance,state,body) VALUES(?,?,?,?) " + "ON CONFLICT(id) DO UPDATE SET state=excluded.state,body=excluded.body", + (value["id"], instance, value["state"], json.dumps(value)), + ) + + +def finish(db, instance, value, state, reason): + saved = db.execute("SELECT state FROM command_journal WHERE id=?", (value["id"],)).fetchone() + if saved and saved[0] not in PENDING: + return + value.update(state=state, reason=reason, finished_at=time.time(), updated_at=time.time()) + value["events"].append({"state": state, "observed_at": time.time(), "historical": False}) + put(db, instance, value) + + +def public(value): + return {k: v for k, v in value.items() if k not in {"guard", "digest", "preset_id"}} + + +def listing(equipment, identifier, before=None, limit=25, tracked=()): + with equipment.db() as db: + equipment._find(db, "instances", identifier) + rows = db.execute( + "SELECT seq,body FROM command_journal WHERE instance=? AND seq limit else None, + "counts": counts, + } diff --git a/src/k1link/fleet/equipment_command_reconciliation.py b/src/k1link/fleet/equipment_command_reconciliation.py new file mode 100644 index 00000000..9f0db8e3 --- /dev/null +++ b/src/k1link/fleet/equipment_command_reconciliation.py @@ -0,0 +1,38 @@ +"""Durable, bounded GET-only reconciliation after Core loses a VPS result.""" + +import http.client +import json +import time + + +def defer(db, identifier, op): + op["reconcile_pending"] = True + db.execute( + "INSERT OR IGNORE INTO command_result_probes(id,instance,host,body) VALUES(?,?,?,?)", + (op["id"], identifier, op["host_id"], json.dumps(op)), + ) + + +def refresh(hosts, host, request, record): + if host["state"] != "paired": + return + # Claim before network I/O; a restart cannot turn an outage into a busy loop. + with hosts.equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + due = db.execute( + "SELECT id,instance,attempts FROM command_result_probes " + "WHERE host=? AND next_attempt<=? ORDER BY next_attempt,id LIMIT 2", + (host["id"], time.time()), + ).fetchall() + for identifier, _, attempts in due: + delay = min(300, 5 * 2 ** min(attempts, 6)) + db.execute( + "UPDATE command_result_probes SET attempts=attempts+1,next_attempt=? WHERE id=?", + (time.time() + delay, identifier), + ) + for operation_id, instance, _ in due: + try: + result = request(host, "GET", "/v1/commands/" + operation_id) + record(hosts, instance, operation_id, result) + except (OSError, ValueError, http.client.HTTPException): + continue diff --git a/src/k1link/fleet/equipment_command_runtime.py b/src/k1link/fleet/equipment_command_runtime.py new file mode 100644 index 00000000..18d1a82f --- /dev/null +++ b/src/k1link/fleet/equipment_command_runtime.py @@ -0,0 +1,188 @@ +"""Bounded per-device FIFO. Core owns accepted intents; VPS owns dispatch/results.""" + +import hashlib +import json +import re +import time + +from . import equipment_command_journal as journal +from . import equipment_operations +from .equipment_command_catalog import catalog +from .independent_equipment import EquipmentError + +CAPACITY = 32 + + +def guard(row): + return { + "vehicle_id": row["vehicle_id"], + "identity": row["identity_key"], + "firmware": row["observed"]["firmware"], + } + + +def source(hosts, row): + from .equipment_network import plan + + endpoint = plan(hosts.equipment, row, True)["secondary"] + return next( + ( + h + for h in hosts.rows() + if h["state"] == "paired" + and row["vehicle_id"] in h["vehicle_ids"] + and h.get("status", {}).get("tracker") == endpoint + ), + None, + ) + + +def enqueue(hosts, identifier, request_id, preset_id): + if not re.fullmatch(r"[a-f0-9]{32}", request_id): + raise EquipmentError("Некорректный идентификатор запроса.") + digest = hashlib.sha256(f"{identifier}:{preset_id}".encode()).hexdigest() + equipment = hosts.equipment + # No hosts.lock or network I/O: accepting an intent cannot wait on a radio exchange. + with equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + old = db.execute("SELECT body FROM command_journal WHERE id=?", (request_id,)).fetchone() + if old: + value = json.loads(old[0]) + if value.get("digest") != digest: + raise EquipmentError("Этот ID уже принадлежит другой команде.") + return journal.public(value) + row = equipment._find(db, "instances", identifier) + selected = next((p for p in catalog(equipment, row) if p["id"] == preset_id), None) + if not selected or selected["unavailable"]: + raise EquipmentError("Команда недоступна для этого устройства.") + host = source(hosts, row) + if not host or host.get("status", {}).get("version") not in { + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + }: + raise EquipmentError("Подключите проверенную версию VPS Host с поддержкой очереди.") + count = db.execute( + "SELECT count(*) FROM command_journal WHERE instance=? AND state IN " + "('waiting','submitting','queued','dispatched')", + (identifier,), + ).fetchone()[0] + if count >= CAPACITY: + raise EquipmentError( + "Очередь устройства заполнена (32 операции). Дождитесь завершения." + ) + now = time.time() + value = { + "id": request_id, + "digest": digest, + "host_id": host["id"], + "preset_id": preset_id, + "guard": guard(row), + "firmware": row["observed"]["firmware"], + "command": selected["command"], + "kind": selected["command"]["kind"], + "description": { + k: v for k, v in selected.items() if k not in {"command", "unavailable"} + }, + "state": "waiting", + "scope": "command", + "created_at": now, + "queue_deadline": now + selected["queue_seconds"], + "expires_at": now + (180 if preset_id == "restart" else 30), + "events": [{"state": "waiting", "observed_at": now, "historical": False}], + } + if equipment_operations.supported(host, value["kind"]): + value["durable"] = True + value.pop("queue_deadline") + value.pop("expires_at") + journal.put(db, identifier, value) + hosts.command_wake.set() + return journal.public(value) + + +def cancel(equipment, identifier, request_id, hosts=None): + with equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + found = db.execute( + "SELECT body FROM command_journal WHERE instance=? AND id=?", (identifier, request_id) + ).fetchone() + if not found: + raise EquipmentError("Операция не найдена.") + value = json.loads(found[0]) + if value["state"] == "cancelled": + return journal.public(value) + if value.get("durable") and value["state"] in {"submitting", "queued", "dispatched"}: + row = equipment._find(db, "instances", identifier) + op = row.get("network_operation", {}) + if op.get("id") != request_id: + raise EquipmentError("Операция больше не является текущей.") + op["stop_requested"] = True + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + journal.capture(db, row) + if hosts is not None: + hosts.command_wake.set() + return journal.public({**value, "stop_requested": True}) + if value["state"] != "waiting": + raise EquipmentError("Передача уже началась. Отмену исполнения подтвердить нельзя.") + journal.finish(db, identifier, value, "cancelled", "operator_cancelled") + return journal.public(value) + + +def pump(hosts): + from .equipment_network import PENDING, start + + equipment = hosts.equipment + with equipment.db() as db: + rows = db.execute( + "SELECT instance,body FROM command_journal WHERE state='waiting' ORDER BY seq" + ).fetchall() + visited = set() + for identifier, body in rows: + value = json.loads(body) + with equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + value = json.loads( + db.execute( + "SELECT body FROM command_journal WHERE id=?", (value["id"],) + ).fetchone()[0] + ) + if value["state"] != "waiting": + continue + row = equipment._find(db, "instances", identifier) + if not value.get("durable") and value["queue_deadline"] <= time.time(): + journal.finish(db, identifier, value, "expired", "queue_deadline") + continue + if guard(row) != value["guard"]: + journal.finish(db, identifier, value, "rejected", "device_changed") + continue + if identifier in visited: + continue + visited.add(identifier) + if row.get("network_operation", {}).get("state") in PENDING: + continue + host = source(hosts, row) + if not host or host["id"] != value["host_id"]: + with equipment.db() as db: + journal.finish(db, identifier, value, "rejected", "host_changed") + continue + if time.time() - (host.get("last_sync_at") or 0) > 30: + continue + try: + start(hosts, identifier, row["revision"], command=value["command"], queued_job=value) + except EquipmentError: + # A concurrent config/USB change or an expired/cancelled intent is + # re-evaluated on the next tick; never manufacture a new ID. + continue diff --git a/src/k1link/fleet/equipment_configuration.py b/src/k1link/fleet/equipment_configuration.py new file mode 100644 index 00000000..3253f9df --- /dev/null +++ b/src/k1link/fleet/equipment_configuration.py @@ -0,0 +1,72 @@ +"""Private full-configuration evidence received from an authenticated owner VPS.""" + +import hashlib +import json +import math +import os +import time + +from k1link.device_plugins.arnavi_b2 import profiles +from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration + + +def snapshot(equipment, row, operation, result): + raw = bytes.fromhex(result["configuration"]) + config = decode_configuration(raw) + digest = hashlib.sha256(raw).hexdigest() + if digest != result.get("configuration_sha256"): + raise ValueError("configuration digest mismatch") + received = result.get("configuration_received_at") + if type(received) not in (int, float) or not math.isfinite(received) or received <= 0: + raise ValueError("invalid configuration observation time") + old = equipment.root / "evidence" / row["evidence_id"] + identity = (old / "identity.json").read_bytes() + if json.loads(identity)["imei"] != row["identity_key"]: + raise ValueError("configuration evidence identity mismatch") + directory = equipment.root / "evidence" / ("network-" + operation["id"]) + directory.mkdir(mode=0o700, exist_ok=True) + files = {"configuration.bin": raw, "identity.json": identity} + files["manifest.json"] = json.dumps( + { + "schema": "missioncore.b2-network-snapshot/v1", + "operation_id": operation["id"], + "host_id": operation["host_id"], + "received_at": received, + "recorded_at": time.time(), + "monotonic_ns": time.monotonic_ns(), + "configuration_sha256": digest, + "identity_source": row["evidence_id"], + "identity_note": ( + "Identity/SIM observations retained from previous snapshot; " + "not refreshed by configuration upload" + ), + }, + indent=2, + ).encode() + for name, data in files.items(): + temporary = directory / (name + ".new") + with os.fdopen(os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + os.replace(temporary, directory / name) + handle = os.open(directory, os.O_RDONLY) + try: + os.fsync(handle) + finally: + os.close(handle) + row["evidence_id"] = directory.name + row["observed"] = { + **row["observed"], + "configuration": config.summary(), + "output_modes": { + str(r.number - 16): r.value[0] + for r in config.records + if r.number in (20, 21, 22) and len(r.value) == 1 + }, + "configuration_read_at": received, + "configuration_transport": "vps", + "supported_profile_fields": list(profiles.portable(config)["parameters"]), + } + row["network_server1"] = {"host": config.text(1), "port": config.integer(2, 2)} + return config diff --git a/src/k1link/fleet/equipment_connectivity.py b/src/k1link/fleet/equipment_connectivity.py new file mode 100644 index 00000000..fd48d702 --- /dev/null +++ b/src/k1link/fleet/equipment_connectivity.py @@ -0,0 +1,67 @@ +"""Resolve a saved automatic policy at admission, then freeze the card-bound intent.""" + +import json +import time +from typing import TYPE_CHECKING + +from k1link.device_plugins.arnavi_b2 import sim_access +from k1link.device_plugins.arnavi_b2.connectivity import SIM_FIELDS +from k1link.device_plugins.arnavi_b2.sim_observation_store import SimObservationStore +from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration + +from .independent_equipment import Document, EquipmentError, EquipmentStore + +if TYPE_CHECKING: + from .vps_hosts import VPSHosts + + +def resolve(hosts: "VPSHosts", row: Document, source: Document | None) -> Document: + if not source or "arnavi-b2-sim-guard-v1" not in source.get("status", {}).get( + "capabilities", [] + ): + raise EquipmentError("Для автоподбора обновите VPS Host ARNavi.") + with hosts.db() as db: + record = db.execute( + "SELECT body FROM b2_sim_identity WHERE instance=?", (row["id"],) + ).fetchone() + value = json.loads(record[0]) if record else None + if not value or value["host_id"] != source["id"] or value.get("tracker") != row["identity_key"]: + raise EquipmentError("Ожидаем распознавание SIM через подключённый VPS.") + store = SimObservationStore(hosts.equipment.root / "evidence") + result = sim_access.resolve( + value, store, str(row["settings"]["connectivity"]["sim_slot"]), now=time.time() + ) + if result["state"] != "ready": + raise EquipmentError( + { + "waiting_identity": "Ожидаем подтверждение карты в выбранном слоте.", + "unknown_card": "Карта ещё не распознана. " + "Прочитайте её через USB или задайте APN вручную.", + "unsupported_operator": "Для этой карты нет сохранённых настроек интернета. " + "Задайте APN вручную.", + }[result["state"]] + ) + return result + + +def remember( + equipment: EquipmentStore, + row: Document, + op: Document, + result: Document, + config: Configuration, +) -> None: + card = op.get("automatic_card") + if not card or op["state"] != "sim_selected" or result.get("sim_guard_verified") is not True: + return + a, u, p = SIM_FIELDS[op["sim_slot"]] + access = (config.text(a), config.text(u), config.text(p)) + SimObservationStore(equipment.root / "evidence").remember_access( + row["identity_key"], + card["card_ref"], + access, + operation=op["id"], + verified_at=result["verified_at"], + configuration_sha256=result["configuration_sha256"], + ) + op["automatic_access_verified"] = True diff --git a/src/k1link/fleet/equipment_firmware.py b/src/k1link/fleet/equipment_firmware.py new file mode 100644 index 00000000..a63aa449 --- /dev/null +++ b/src/k1link/fleet/equipment_firmware.py @@ -0,0 +1,132 @@ +"""Local firmware archive. Storing bytes never authorizes a device update.""" + +import hashlib +import re +import sqlite3 +import time +from pathlib import Path +from typing import Any + +MAX_FIRMWARE_BYTES = 4 * 1024 * 1024 +MAX_ARCHIVE_BYTES = 128 * 1024 * 1024 + + +class FirmwareError(ValueError): + pass + + +class FirmwareArchive: + def __init__(self, root: Path, known: dict[str, dict[str, dict[str, Any]]]) -> None: + self.known = known + self.directory = root / "firmware" + self.directory.mkdir(mode=0o700, parents=True, exist_ok=True) + self.path = self.directory / "archive.sqlite3" + if self.directory.is_symlink() or self.path.is_symlink(): + raise FirmwareError("Хранилище прошивок недоступно.") + db = self.connect() + try: + with db: + db.execute("""CREATE TABLE IF NOT EXISTS images ( + model TEXT NOT NULL, digest TEXT NOT NULL, filename TEXT NOT NULL, + added REAL NOT NULL, payload BLOB NOT NULL, + PRIMARY KEY(model, digest))""") + finally: + db.close() + self.path.chmod(0o600) + + def connect(self) -> sqlite3.Connection: + db = sqlite3.connect(self.path, timeout=5) + db.row_factory = sqlite3.Row + db.execute("PRAGMA synchronous=FULL") + return db + + def require_model(self, model: str) -> None: + if model not in self.known: + raise FirmwareError("Архив прошивок для этой модели недоступен.") + + def describe(self, row: sqlite3.Row) -> dict[str, Any]: + data = bytes(row["payload"]) + if hashlib.sha256(data).hexdigest() != row["digest"]: + raise FirmwareError("Файл прошивки повреждён. Добавьте исходный файл повторно.") + source = self.known[row["model"]].get(row["digest"], {}) + return { + "id": row["digest"], + "model_id": row["model"], + "filename": row["filename"], + "bytes": len(data), + "sha256": row["digest"], + "added_at": row["added"], + "version": source.get("version"), + "source_url": source.get("source_url"), + "source": "manufacturer" if source else "user", + # A known manufacturer's image is not a qualified Mission Core update. + "installable": False, + } + + def listing(self, model: str) -> list[dict[str, Any]]: + self.require_model(model) + db = self.connect() + try: + return [ + self.describe(row) + for row in db.execute( + "SELECT * FROM images WHERE model=? ORDER BY added DESC, digest", (model,) + ) + ] + finally: + db.close() + + def add(self, model: str, filename: str, payload: bytes) -> dict[str, Any]: + self.require_model(model) + if not re.fullmatch(r"[\w ().-]{1,116}\.dfw", filename, re.IGNORECASE): + raise FirmwareError("Выберите файл .dfw с обычным именем без пути.") + if not 0 < len(payload) <= MAX_FIRMWARE_BYTES: + raise FirmwareError("Файл .dfw должен быть непустым и не больше 4 МБ.") + digest = hashlib.sha256(payload).hexdigest() + db = self.connect() + try: + with db: + db.execute("BEGIN IMMEDIATE") + previous = db.execute( + "SELECT * FROM images WHERE model=? AND digest=?", (model, digest) + ).fetchone() + if previous is not None: + if hashlib.sha256(bytes(previous["payload"])).hexdigest() != digest: + db.execute( + "UPDATE images SET payload=? WHERE model=? AND digest=?", + (payload, model, digest), + ) + previous = db.execute( + "SELECT * FROM images WHERE model=? AND digest=?", (model, digest) + ).fetchone() + return self.describe(previous) + size = db.execute("SELECT COALESCE(SUM(length(payload)),0) FROM images").fetchone()[ + 0 + ] + if size + len(payload) > MAX_ARCHIVE_BYTES: + raise FirmwareError("Недостаточно места в архиве прошивок.") + db.execute( + "INSERT INTO images VALUES (?,?,?,?,?)", + (model, digest, filename, time.time(), payload), + ) + row = db.execute( + "SELECT * FROM images WHERE model=? AND digest=?", (model, digest) + ).fetchone() + return self.describe(row) + finally: + db.close() + + def download(self, model: str, digest: str) -> tuple[dict[str, Any], bytes]: + self.require_model(model) + if not re.fullmatch(r"[0-9a-f]{64}", digest): + raise FirmwareError("Файл прошивки не найден.") + db = self.connect() + try: + row = db.execute( + "SELECT * FROM images WHERE model=? AND digest=?", (model, digest) + ).fetchone() + if row is None: + raise FirmwareError("Файл прошивки не найден.") + return self.describe(row), bytes(row["payload"]) + finally: + db.close() diff --git a/src/k1link/fleet/equipment_network.py b/src/k1link/fleet/equipment_network.py new file mode 100644 index 00000000..e77407c1 --- /dev/null +++ b/src/k1link/fleet/equipment_network.py @@ -0,0 +1,902 @@ +"""VPS-backed equipment operations; private wire state never enters browser models.""" + +import hashlib +import http.client +import json +import math +import re +import time +import uuid +from typing import TYPE_CHECKING + +from k1link.device_plugins.arnavi_b2 import connectivity, profiles +from k1link.device_plugins.arnavi_b2.usb_protocol import ( + decode_configuration, + prepare_server_slot, +) + +from . import equipment_command_reconciliation, equipment_operations, equipment_outbox +from .independent_equipment import Document, EquipmentError, EquipmentStore +from .vps_transport import request + +if TYPE_CHECKING: + from .vps_hosts import VPSHosts + +PENDING = {"submitting", "queued", "dispatched"} +TERMINAL = { + "verified", + "observed", + "rejected", + "not_applied", + "uncertain", + "unconfirmed", + "expired", + "device_confirmed", + "device_rejected", + "reconnected", + "sim_selected", + "accepted", + "stopped", +} + + +def idle(row: Document) -> None: + if row.get("network_operation", {}).get("state") in PENDING: + raise EquipmentError("Дождитесь результата текущей операции через VPS.") + + +def plan( + equipment: EquipmentStore, + row: Document, + read_only: bool = False, + full: bool = False, + *, + select_sim: bool = False, + automatic_access: Document | None = None, +) -> Document: + if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01": + raise EquipmentError("Сетевая запись для этой модели или версии ПО не проверена.") + config = decode_configuration( + (equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").read_bytes() + ) + if row.get("network_server1"): + config = prepare_server_slot(config, slot=1, **row["network_server1"]) + if full: + body = { + "kind": "read-configuration" if read_only else "configure-all", + "model": 231, + "firmware": "0.01", + "imei": row["identity_key"], + "password": config.text(5), + "secondary": {"host": config.text(3), "port": config.integer(4, 2)}, + } + if not read_only: + desired = profiles.prepare( + config, + row["settings"], + automatic_access=automatic_access["access"] if automatic_access else None, + ) + body.update( + expected_sha256=hashlib.sha256(config.encode()).hexdigest(), + target_configuration=desired.encode().hex(), + target={"host": desired.text(1), "port": desired.integer(2, 2)}, + ) + connection = row["settings"]["connectivity"] + # A portable desired SIM is not a recurring restart command. An + # explicit operator action still runs when the stored bits already + # match (the live modem may be using another SIM). + sim_mask = (1 << 10) | (1 << 20) + both_allowed = connection["strategy"] in ("both", "native") + selection_requested = connection.get("activate") or both_allowed + selection_changed = selection_requested and ( + (desired.integer(72, 4) ^ config.integer(72, 4)) & sim_mask + ) + if select_sim and not selection_requested: + raise EquipmentError("Выберите SIM для интернета перед применением.") + access_changed = automatic_access and any( + desired.value(n) != config.value(n) + for n in connectivity.SIM_FIELDS[connection["sim_slot"]] + ) + native_access_changed = connection["strategy"] == "native" and any( + desired.value(n) != config.value(n) + for numbers in connectivity.SIM_FIELDS.values() + for n in numbers + ) + if select_sim or selection_changed or access_changed or native_access_changed: + body["kind"] = "select-sim" + if both_allowed: + body["sim_policy"] = "both" + else: + body["sim_slot"] = connection["sim_slot"] + if automatic_access: + body["sim_guard"] = { + "slot": connection["sim_slot"], + "sid": automatic_access["firmware_sid"], + } + return body + if read_only: + return { + "kind": "read-settings", + "imei": row["identity_key"], + "password": config.text(5), + "secondary": {"host": config.text(3), "port": config.integer(4, 2)}, + } + target = row["settings"].get("endpoint") + if not target or target["slot"] != 1 or len(target["host"]) > 32: + raise EquipmentError( + "По сети доступна смена сервера 1 (адрес до 32 символов). " + "Сервер 2 должен сохранять связь с текущим VPS." + ) + desired = profiles.prepare(config, row["settings"]) + changed = {r.number for r in desired.records if r.value != config.value(r.number)} + if changed - {1, 2} or config.integer(9, 1) != 0: + raise EquipmentError( + "В этой операции можно изменить только адрес и порт сервера 1. " + "Сетевая запись остальных изменённых параметров пока не поддерживается." + ) + return { + "kind": "configure-server1", + "model": 231, + "firmware": "0.01", + "imei": row["identity_key"], + "password": config.text(5), + "expected": {"host": config.text(1), "port": config.integer(2, 2)}, + "target": {"host": target["host"], "port": target["port"]}, + "secondary": {"host": config.text(3), "port": config.integer(4, 2)}, + } + + +def start( + hosts: "VPSHosts", + identifier: str, + revision: int, + read_only: bool = False, + *, + command: Document | None = None, + queued_job: Document | None = None, + select_sim: bool = False, +) -> Document: + from .equipment_command_journal import capture + + equipment = hosts.equipment + # Serialize against VPS reassignment and USB operations; no DB transaction over the network. + with hosts.lock, equipment.read_lock: + with equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + row = equipment._find(db, "instances", identifier) + previous = row.get("network_operation", {}) + if queued_job is not None: + saved = db.execute( + "SELECT body FROM command_journal WHERE id=? AND instance=?", + (queued_job["id"], identifier), + ).fetchone() + if not saved: + raise EquipmentError("Операция очереди не найдена.") + queued_job = json.loads(saved[0]) + from .equipment_command_runtime import guard + + if ( + queued_job["state"] != "waiting" + or ( + not queued_job.get("durable") + and queued_job["queue_deadline"] <= time.time() + ) + or queued_job["guard"] != guard(row) + or queued_job["command"] != command + ): + raise EquipmentError("Операция отменена, просрочена или устройство изменилось.") + if ( + queued_job is None + and previous.get("requested_revision") == revision + and previous.get("read_only", False) == read_only + and previous.get("command") == command + and previous.get("select_sim", False) == select_sim + ): + return equipment.public(row) # lost response retry, same durable operation + if row["revision"] != revision: + raise EquipmentError("Настройки изменились. Откройте устройство заново.") + idle(row) + candidates = [ + h + for h in hosts.rows() + if h["state"] == "paired" and row["vehicle_id"] in h["vehicle_ids"] + ] + probe = plan(equipment, row, True) + source = next( + (h for h in candidates if h.get("status", {}).get("tracker") == probe["secondary"]), + None, + ) + full = ( + command is None + and source is not None + and source.get("status", {}).get("version") + in ( + "0.1.15", + "0.1.16", + "0.1.17", + "0.1.18", + "0.1.19", + "0.1.20", + "0.1.21", + "0.1.22", + "0.1.23", + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + ) + ) + automatic_access = None + if ( + command is None + and not read_only + and row["settings"]["connectivity"].get("automatic") + ): + from .equipment_connectivity import resolve + + automatic_access = resolve(hosts, row, source) + if not full: + raise EquipmentError("Автоподбор требует полной настройки через VPS.") + body = ( + plan( + equipment, + row, + read_only, + full, + select_sim=select_sim, + automatic_access=automatic_access, + ) + if command is None + else None + ) + # Only a SIM action or an actual SIM/APN overlay needs current + # presence. Stale cellular telemetry must not block unrelated edits. + connection_changed = False + if ( + body + and full + and not read_only + and row["settings"]["connectivity"]["strategy"] == "sim" + ): + baseline = decode_configuration( + ( + equipment.root / "evidence" / row["evidence_id"] / "configuration.bin" + ).read_bytes() + ) + desired = decode_configuration(bytes.fromhex(body["target_configuration"])) + slot = row["settings"]["connectivity"]["sim_slot"] + apn_number = 67 if slot == 1 else 89 + connection_changed = body["kind"] == "select-sim" or baseline.value( + apn_number + ) != desired.value(apn_number) + if not read_only and command is None and connection_changed: + slot = str(row["settings"]["connectivity"]["sim_slot"]) + report = next((t for t in hosts.telemetry() if t["instance_id"] == identifier), {}) + cellular = report.get("cellular") or {} + status = cellular.get("status") or {} + if ( + not report.get("online") + or not source + or cellular.get("host_id") != source["id"] + or not 0 <= time.time() - status.get("measured_at", 0) < 90 + or status.get("sim_states", {}).get(slot) not in (1, 2, 3, 5, 6) + ): + raise EquipmentError( + f"Наличие SIM {slot} не подтверждено свежими данными B2. " + "Дождитесь обновления сведений о SIM." + ) + if command is None: + assert body is not None + if body.get("sim_policy") == "both" and source.get("status", {}).get( + "version" + ) not in {"0.1.37", "0.1.38", "0.1.39", "0.1.40", "0.1.41"}: + raise EquipmentError("Для разрешения обеих SIM установите актуальный VPS Host.") + if body["kind"] == "select-sim" and source.get("status", {}).get("version") not in { + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + }: + raise EquipmentError("Для смены SIM установите актуальный VPS Host.") + else: + from .equipment_actions import plan as action_plan + + body = action_plan(equipment, row, command) + target = ( + source + if read_only or command is not None + else next( + (h for h in candidates if h.get("status", {}).get("tracker") == body["target"]), + None, + ) + ) + if not source or not target: + raise EquipmentError("Текущий и новый VPS должны быть подключены к этому аппарату.") + if queued_job is not None and source["id"] != queued_job["host_id"]: + raise EquipmentError("Привязка VPS изменилась.") + if command is not None: + versions = { + "restart": ( + "0.1.17", + "0.1.18", + "0.1.19", + "0.1.20", + "0.1.21", + "0.1.22", + "0.1.23", + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + ), + "request-position": ( + "0.1.8", + "0.1.9", + "0.1.10", + "0.1.11", + "0.1.12", + "0.1.13", + "0.1.14", + "0.1.15", + "0.1.16", + "0.1.17", + "0.1.18", + "0.1.19", + "0.1.20", + "0.1.21", + "0.1.22", + "0.1.23", + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + ), + "pulse-output": ( + "0.1.9", + "0.1.10", + "0.1.11", + "0.1.12", + "0.1.13", + "0.1.14", + "0.1.15", + "0.1.16", + "0.1.17", + "0.1.18", + "0.1.19", + "0.1.20", + "0.1.21", + "0.1.22", + "0.1.23", + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + ), + "set-output": ( + "0.1.10", + "0.1.11", + "0.1.12", + "0.1.13", + "0.1.14", + "0.1.15", + "0.1.16", + "0.1.17", + "0.1.18", + "0.1.19", + "0.1.20", + "0.1.21", + "0.1.22", + "0.1.23", + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + ), + } + if source.get("status", {}).get("version") not in versions[command["kind"]]: + raise EquipmentError("Для этой команды установите актуальную версию VPS Host.") + if any( + time.time() - (h.get("last_sync_at") or 0) > 30 + or h.get("status", {}).get("version") + not in ( + "0.1.6", + "0.1.7", + "0.1.8", + "0.1.9", + "0.1.10", + "0.1.11", + "0.1.12", + "0.1.13", + "0.1.14", + "0.1.15", + "0.1.16", + "0.1.17", + "0.1.18", + "0.1.19", + "0.1.20", + "0.1.21", + "0.1.22", + "0.1.23", + "0.1.24", + "0.1.25", + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + ) + for h in (source, target) + ): + raise EquipmentError("Проверьте связь с VPS и установите актуальную версию хоста.") + body.pop("secondary") + if full: + body.pop("target", None) + body["id"] = queued_job["id"] if queued_job is not None else uuid.uuid4().hex + # Admit the new destination before asking the device to move its primary channel. + op = { + "id": body["id"], + "host_id": source["id"], + "state": "submitting", + "requested_revision": revision, + "created_at": time.time(), + "expires_at": time.time() + + ( + 390 + if body["kind"] == "select-sim" + else 210 + if body["kind"] == "restart" + else 60 + if command is not None + else 240 + ), + "scope": "command" + if command is not None + else "sim-selection" + if body["kind"] == "select-sim" + else "configuration" + if full + else "server1", + "read_only": read_only, + "kind": body["kind"], + "command": command, + "select_sim": select_sim, + } + if body["kind"] == "select-sim": + if body.get("sim_policy") == "both": + op["sim_policy"] = "both" + else: + op["sim_slot"] = body["sim_slot"] + if automatic_access and body.get("sim_guard"): + op["automatic_card"] = { + key: automatic_access[key] for key in ("card_ref", "source", "home_network") + } + if full and not read_only: + op["target_configuration_sha256"] = hashlib.sha256( + bytes.fromhex(body["target_configuration"]) + ).hexdigest() + if queued_job is not None: + op["created_at"] = queued_job["created_at"] + if not queued_job.get("durable"): + op["expires_at"] = queued_job["expires_at"] + if equipment_operations.supported(source, body["kind"]): + op.update(durable=True, runtime_phase="reconciling") + op.pop("expires_at", None) + updated = { + **row, + "revision": revision + 1, + "network_operation": op, + "updated_at": time.time(), + } + db.execute("INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(row))) + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(updated), identifier)) + durable_delivery = source.get("status", {}).get("version") in { + "0.1.26", + "0.1.27", + "0.1.28", + "0.1.29", + "0.1.30", + "0.1.31", + "0.1.32", + "0.1.33", + "0.1.34", + "0.1.35", + "0.1.36", + "0.1.37", + "0.1.38", + "0.1.39", + "0.1.40", + "0.1.41", + } + if durable_delivery: + lifetime = ( + 360 + if body["kind"] == "select-sim" + else 180 + if full or body["kind"] == "restart" + else 30 + if command is not None + else 120 + ) + if not op.get("durable"): + body["not_after"] = op["created_at"] + lifetime + db.execute( + "INSERT INTO network_outbox(id,instance,host,target,body) VALUES(?,?,?,?,?)", + (op["id"], identifier, source["id"], target["id"], json.dumps(body)), + ) + capture(db, updated) + # Older VPS releases lack an original request deadline; retain GET-only + # reconciliation for those operations instead of making delayed writes. + try: + if durable_delivery: + result = equipment_outbox.attempt(hosts, source, op["id"], request) + else: + hosts.sync(target) + result = request(source, "POST", "/v1/commands", body) + if result is not None: + record(hosts, identifier, op["id"], result) + except (OSError, ValueError, http.client.HTTPException): + pass + with equipment.db() as db: + return equipment.public(equipment._find(db, "instances", identifier)) + + +def record( + hosts: "VPSHosts", + identifier: str, + operation_id: str, + result: Document, + *, + reconcile: bool = False, +) -> None: + from .equipment_command_journal import capture + + equipment = hosts.equipment + if result.get("id") != operation_id: + raise ValueError("operation identity mismatch") + if result.get("state") not in PENDING | TERMINAL | {"reply_received"}: + raise ValueError("invalid operation state") + with equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + row = equipment._find(db, "instances", identifier) + op = row.get("network_operation", {}) + historical = False + probe = db.execute( + "SELECT body FROM command_result_probes WHERE id=? AND instance=?", + (operation_id, identifier), + ).fetchone() + if op.get("id") != operation_id or op.get("state") not in PENDING: + if not probe or result["state"] in PENDING: + return + historical = op.get("id") != operation_id + op = json.loads(probe[0]) + kind = op.get("kind") or ("read-settings" if op.get("read_only") else "configure-server1") + if result.get("kind") != kind: + raise ValueError("operation kind mismatch") + equipment_operations.project(op, result) + # The VPS durably owns this exact operation, or Core has closed its + # uncertain outcome. The wire body must never enter public/history JSON. + db.execute("DELETE FROM network_outbox WHERE id=?", (operation_id,)) + deadline = result.get("expires_at") + if ( + not op.get("durable") + and type(deadline) in (int, float) + and math.isfinite(deadline) + and deadline > 0 + ): + # The VPS owns the transaction deadline. Never extend Core's bound. + op["expires_at"] = min(op["expires_at"], deadline) + if op.get("scope") in ("configuration", "sim-selection"): + for source, target in ( + ("created_at", "vps_created_at"), + ("dispatched_at", "dispatched_at"), + ("configuration_received_at", "configuration_received_at"), + ("write_reply_sent_at", "write_reply_sent_at"), + ("recovery_at", "recovery_at"), + ): + value = result.get(source) + if type(value) in (int, float) and math.isfinite(value) and value > 0: + op[target] = value + count = result.get("recovery_count") + if type(count) is int and count > 0 and result.get("recovery_verification") is True: + op.update(recovery_count=count, recovery_verification=True) + if result["state"] == "sim_selected" and ( + kind != "select-sim" + or type(result.get("active_sim")) is not int + or result["active_sim"] not in (1, 2) + or op.get("sim_policy") != "both" + and result["active_sim"] != op.get("sim_slot") + ): + raise ValueError("SIM selection result mismatch") + if kind == "select-sim" and result["state"] == "verified": + raise ValueError("configuration readback is not SIM selection") + if ( + op.get("automatic_card") + and result["state"] == "sim_selected" + and result.get("sim_guard_verified") is not True + ): + raise ValueError("card-bound connectivity result missing") + op.update( + { + k: result[k] + for k in ( + "state", + "stage", + "verified_at", + "unchanged", + "active_sim", + "telemetry_measured_at", + "reconnect_seconds", + ) + if k in result + } + ) + if result["state"] in TERMINAL and "configuration" in result: + from .equipment_configuration import snapshot + + config = snapshot(equipment, row, op, result) + op["configuration_sha256"] = result["configuration_sha256"] + op["record_count"] = len(config.records) + if ( + result["state"] in ("verified", "sim_selected") + and not op["read_only"] + and result["configuration_sha256"] != op["target_configuration_sha256"] + ): + op["state"] = "uncertain" + if not op["read_only"]: + from .equipment_connectivity import remember + + remember(equipment, row, op, result, config) + row["policy_state"] = ( + ("unchanged" if result.get("unchanged") else "applied") + if op["state"] in ("verified", "sim_selected") + else "not_applied" + if result["state"] in ("rejected", "not_applied") + else "uncertain" + ) + if result.get("reason") == "sim_card_changed" and result.get( + "write_reply_sent_at" + ): + row["policy_state"] = "uncertain" + elif result["state"] in TERMINAL and not op["read_only"]: + if result["state"] in ("verified", "sim_selected"): + op["state"] = "uncertain" + row["policy_state"] = ( + "not_started" + if (result["state"] == "stopped" and result.get("attempt_count") == 0) + or result["state"] in ("unconfirmed", "expired") + and result.get("stage") == "preflight" + and not result.get("write_reply_sent_at") + else "uncertain" + ) + row["network_operation"] = op + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + capture(db, row) + return + if op.get("scope") == "command": + if result["state"] not in PENDING | { + "device_confirmed", + "device_rejected", + "reconnected", + "expired", + "unconfirmed", + "uncertain", + "accepted", + "stopped", + "rejected", + }: + raise ValueError("invalid command outcome") + if result["state"] == "reconnected" and kind != "restart": + raise ValueError("reconnection is only a restart outcome") + if kind == "restart" and result["state"] == "device_confirmed": + raise ValueError("restart receipt is not reconnection") + op["state"] = result["state"] + if reconcile: + equipment_command_reconciliation.defer(db, identifier, op) + elif probe: + op["reconcile_pending"] = False + db.execute("DELETE FROM command_result_probes WHERE id=?", (operation_id,)) + for key in ( + "roundtrip_seconds", + "received_at", + "dispatched_at", + "device_code", + "device_accepted_at", + "reconnected_at", + "reconnect_seconds", + "telemetry_measured_at", + ): + value = result.get(key) + if type(value) in (int, float) and math.isfinite(value) and value >= 0: + op[key] = value + created, dispatched = result.get("created_at"), result.get("dispatched_at") + if type(created) in (int, float) and math.isfinite(created) and created > 0: + op["vps_created_at"] = created + if ( + type(created) in (int, float) + and type(dispatched) in (int, float) + and math.isfinite(dispatched - created) + and dispatched >= created + ): + op["queue_seconds"] = dispatched - created + if not historical: + row["network_operation"] = op + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + capture(db, {**row, "network_operation": op}) + return + # Explicit projection. Never expose GETP, password, APN credentials or arbitrary errors. + op.update({k: result[k] for k in ("state", "stage", "verified_at") if k in result}) + if result["state"] == "reply_received": + if not op.get("read_only"): + raise ValueError("write receipt is not readback") + replies = result.get("replies", []) + match = ( + re.match(r"^#1=([A-Za-z0-9.-]{1,32}),([0-9]{1,5}),0,0,#", replies[0]) + if len(replies) == 1 + else None + ) + if not match or not 1 <= int(match[2]) <= 65535: + op["state"] = "uncertain" + else: + endpoint = {"host": match[1], "port": int(match[2])} + row["network_server1"] = endpoint + op.update(state="observed", server1=endpoint, verified_at=time.time()) + if result["state"] == "verified": + target = row["settings"]["endpoint"] + expected = {"host": target["host"], "port": target["port"]} + if result.get("server1") != expected: + op["state"] = "uncertain" + else: + row["network_server1"] = expected + # Scope is intentionally not the entire USB profile. + op["server1"] = expected + row["network_operation"] = op + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + capture(db, row) + + +def refresh(hosts: "VPSHosts", host: Document) -> None: + equipment = hosts.equipment + equipment_command_reconciliation.refresh(hosts, host, request, record) + for row in equipment.listing(): + op = row.get("network_operation", {}) + if op.get("host_id") != host["id"] or op.get("state") not in PENDING: + continue + reconcile = False + try: + if host["state"] != "paired": + raise ValueError("host replaced") + if op.get("durable") and op.get("stop_requested"): + result = request( + host, + "POST", + equipment_operations.path(op) + op["id"] + "/cancel", + {"kind": op["kind"]}, + ) + else: + result = request(host, "GET", equipment_operations.path(op) + op["id"]) + except (OSError, ValueError, http.client.HTTPException): + if op.get("durable") or time.time() <= op["expires_at"]: + if op.get("durable"): + equipment_operations.disconnected(equipment, row["id"], op["id"]) + if op.get("stop_requested"): + continue + if op["state"] == "submitting" and host["state"] == "paired": + try: + receipt = equipment_outbox.attempt(hosts, host, op["id"], request) + if receipt is not None: + record(hosts, row["id"], op["id"], receipt) + except (OSError, ValueError, http.client.HTTPException): + pass + continue + result = { + "id": op["id"], + "kind": op.get("kind") + or ("read-settings" if op.get("read_only") else "configure-server1"), + "state": "uncertain", + } + reconcile = True + # Even an available but stuck VPS must not leave Core pending forever. + # This is unknown outcome, not cancellation or permission to retry a write. + if ( + not op.get("durable") + and result.get("state") in PENDING + and time.time() > op["expires_at"] + ): + result = {**result, "state": "uncertain"} + reconcile = True + record(hosts, row["id"], op["id"], result, reconcile=reconcile) diff --git a/src/k1link/fleet/equipment_operations.py b/src/k1link/fleet/equipment_operations.py new file mode 100644 index 00000000..de36d58f --- /dev/null +++ b/src/k1link/fleet/equipment_operations.py @@ -0,0 +1,107 @@ +"""Core projection of VPS-owned durable tracker maintenance operations.""" + +import json +import math + +ATTEMPT_FACTS = { + "dispatched_at", + "received_at", + "device_accepted_at", + "device_code", + "roundtrip_seconds", + "reconnected_at", + "reconnect_seconds", + "verified_at", + "configuration_received_at", + "write_reply_sent_at", + "active_sim", + "telemetry_measured_at", + "unchanged", + "stage", + "queue_seconds", + "attempt_expires_at", +} + +KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"} + + +def supported(host, kind): + return kind in KINDS and "arnavi-b2-durable-operations-v1" in host.get("status", {}).get( + "capabilities", [] + ) + + +def path(op): + return "/v1/operations/" if op.get("durable") else "/v1/commands/" + + +def project(op, result): + if not op.get("durable"): + return + if result.get("durable") is not True: + raise ValueError("durable operation result missing") + # A new attempt must not inherit an earlier ACK, timing or write stage. + for field in ATTEMPT_FACTS: + op.pop(field, None) + op["reconcile_pending"] = False + for field in ("attempt_count", "next_attempt_at", "attempt_expires_at"): + value = result.get(field) + if type(value) in (int, float) and math.isfinite(value) and value >= 0: + op[field] = value + phase = result.get("runtime_phase") + if phase in { + "waiting-link", + "waiting-identity", + "retry-wait", + "checking-result", + "executing", + "complete", + "stopped", + }: + op["runtime_phase"] = phase + if result.get("stop_requested") is True: + op["stop_requested"] = True + if result.get("reason") == "sim_card_changed": + op["reason"] = "sim_card_changed" + + +def disconnected(equipment, identifier, operation_id): + with equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + row = equipment._find(db, "instances", identifier) + op = row.get("network_operation", {}) + if op.get("id") != operation_id or not op.get("durable") or op.get("reconcile_pending"): + return + op.update(reconcile_pending=True, runtime_phase="reconciling") + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + from .equipment_command_journal import capture + + capture(db, row) + + +def attempts(hosts, identifier, request_id, before=None): + """Only the paired owning host may supply this instance's attempt history.""" + from .independent_equipment import EquipmentError + from .vps_transport import request + + with hosts.equipment.db() as db: + row = db.execute( + "SELECT body FROM command_journal WHERE instance=? AND id=?", + (identifier, request_id), + ).fetchone() + value = json.loads(row[0]) if row else {} + host = next( + (h for h in hosts.rows() if h["id"] == value.get("host_id") and h["state"] == "paired"), + None, + ) + if not value.get("durable") or not host: + raise EquipmentError("История попыток этой операции недоступна.") + suffix = f"?before={before}" if before is not None else "" + result = request(host, "GET", f"/v1/operations/{request_id}/attempts{suffix}") + allowed = ATTEMPT_FACTS | {"id", "number", "phase", "state", "observed_at"} + return { + "items": [ + {k: v for k, v in item.items() if k in allowed} for item in result.get("items", [])[:20] + ], + "next_before": result.get("next_before"), + } diff --git a/src/k1link/fleet/equipment_outbox.py b/src/k1link/fleet/equipment_outbox.py new file mode 100644 index 00000000..e1291050 --- /dev/null +++ b/src/k1link/fleet/equipment_outbox.py @@ -0,0 +1,51 @@ +"""Private, transactional Core → VPS delivery; never a second tracker operation.""" + +import json +import time +from collections.abc import Callable +from typing import TYPE_CHECKING + +from .independent_equipment import Document + +if TYPE_CHECKING: + from .vps_hosts import VPSHosts + + +def attempt( + hosts: "VPSHosts", source: Document, operation_id: str, send: Callable[..., Document] +) -> Document | None: + # The caller owns hosts.lock. Claim the backoff durably before network I/O. + # A process restart cannot generate a new ID, body, destination or deadline. + with hosts.equipment.db() as db: + db.execute("BEGIN IMMEDIATE") + row = db.execute( + "SELECT instance,host,target,body,attempts,next_attempt FROM network_outbox WHERE id=?", + (operation_id,), + ).fetchone() + if row is None or row[1] != source["id"] or source["state"] != "paired": + return None + instance = hosts.equipment._find(db, "instances", row[0]) + op = instance.get("network_operation", {}) + body = json.loads(row[3]) + now = time.time() + if ( + op.get("id") != operation_id + or op.get("state") != "submitting" + or (not op.get("durable") and min(op["expires_at"], body["not_after"]) <= now) + or row[5] > now + ): + return None + # Up to 30 s between retries, with stable per-operation staggering. + delay = min(30, 2 ** min(row[4] + 1, 5)) + int(operation_id[-4:], 16) / 65536 + db.execute( + "UPDATE network_outbox SET attempts=attempts+1,next_attempt=? WHERE id=?", + (now + delay, operation_id), + ) + target = next((h for h in hosts.rows() if h["id"] == row[2] and h["state"] == "paired"), None) + if target is None: + return None + hosts.sync(target) + # Sync may consume the remaining deadline; do not send stale requests. + if not op.get("durable") and time.time() >= body["not_after"]: + return None + return send(source, "POST", "/v1/operations" if op.get("durable") else "/v1/commands", body) diff --git a/src/k1link/fleet/independent_equipment.py b/src/k1link/fleet/independent_equipment.py new file mode 100644 index 00000000..88c8a139 --- /dev/null +++ b/src/k1link/fleet/independent_equipment.py @@ -0,0 +1,285 @@ +"""Independent equipment identities, immutable profiles and assignment history. + +No vehicle node_id is used for identity, availability, or enrollment. Saving a +policy never claims the hardware has applied it. Adapter owns vendor semantics. +""" + +import json +import secrets +import sqlite3 +import threading +import time +import uuid +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Protocol, cast + +Document = dict[str, Any] + + +class EnrollmentAdapter(Protocol): + def catalog(self) -> Document: ... + def validate_policy(self, value: Document) -> Document: ... + def inspect(self, evidence: Path) -> Document: ... + def check_policy(self, candidate: Document, evidence: Path, policy: Document) -> None: ... + def apply(self, instance: Document, evidence: Path) -> Document: ... + + +class EquipmentError(ValueError): + pass + + +class EquipmentStore: + @staticmethod + def require_idle(row: Document) -> None: + from .equipment_network import idle + + idle(row) + + def __init__(self, root: Path, adapters: dict[str, EnrollmentAdapter]) -> None: + self.root = root / "independent-equipment" + self.root.mkdir(mode=0o700, parents=True, exist_ok=True) + if self.root.is_symlink() or self.root.stat().st_mode & 0o077: + raise EquipmentError("Хранилище оборудования недоступно.") + self.path = self.root / "registry.sqlite3" + if self.path.is_symlink(): + raise EquipmentError("Хранилище оборудования недоступно.") + self.adapters = adapters + self.read_lock = threading.Lock() + with self.db() as db: + db.executescript(""" + CREATE TABLE IF NOT EXISTS profiles(id TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS candidates(id TEXT PRIMARY KEY, expires REAL NOT NULL, + body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS instances(id TEXT PRIMARY KEY, + identity_key TEXT UNIQUE NOT NULL, + body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS history(instance_id TEXT NOT NULL, + revision INTEGER NOT NULL, + body TEXT NOT NULL, PRIMARY KEY(instance_id, revision)); + CREATE TABLE IF NOT EXISTS network_outbox( + id TEXT PRIMARY KEY, instance TEXT NOT NULL, host TEXT NOT NULL, + target TEXT NOT NULL, body TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0); + """) + from .equipment_command_journal import initialize + + initialize(db) + self.path.chmod(0o600) + + @contextmanager + def db(self) -> Iterator[sqlite3.Connection]: + db = sqlite3.connect(self.path, timeout=5) + try: + db.execute("PRAGMA synchronous=FULL") + with db: + yield db + finally: + db.close() + + def adapter(self, model: str) -> EnrollmentAdapter: + if model not in self.adapters: + raise EquipmentError("Модель не поддерживается.") + return self.adapters[model] + + def catalog(self) -> Document: + return {"models": [a.catalog() for a in self.adapters.values()]} + + def public(self, row: Document) -> Document: + public = {k: v for k, v in row.items() if k not in ("identity_key", "evidence_id")} + details = getattr(self.adapters.get(row.get("model_id")), "observation_details", None) + if details and row.get("evidence_id"): + # Add newly supported observations from the immutable enrollment + # snapshot without requiring USB reconnection or altering policy. + public["observed"] = { + **row.get("observed", {}), + **details(self.root / "evidence" / row["evidence_id"]), + } + return public + + def profiles(self) -> list[Document]: + with self.db() as db: + return [ + json.loads(r[0]) + for r in db.execute("SELECT body FROM profiles ORDER BY rowid DESC") + ] + + def save_profile(self, name: str, model: str, settings: Document) -> Document: + settings = self.adapter(model).validate_policy(settings) + name = name.strip() + if not name or len(name) > 80: + raise EquipmentError("Укажите название профиля до 80 символов.") + row: Document = { + "id": uuid.uuid4().hex, + "name": name, + "model_id": model, + "settings": settings, + "created_at": time.time(), + } + with self.db() as db: + db.execute("INSERT INTO profiles VALUES(?,?)", (row["id"], json.dumps(row))) + return row + + def inspect(self, model: str) -> Document: + adapter = self.adapter(model) + if not self.read_lock.acquire(blocking=False): + raise EquipmentError("Чтение USB уже выполняется. Дождитесь результата.") + try: + row = adapter.inspect(self.root / "evidence") + row.update(id=secrets.token_urlsafe(32), expires_at=time.time() + 600) + with self.db() as db: + db.execute("DELETE FROM candidates WHERE expires < ?", (time.time(),)) + db.execute( + "INSERT INTO candidates VALUES(?,?,?)", + (row["id"], row["expires_at"], json.dumps(row)), + ) + return self.public(row) + finally: + self.read_lock.release() + + @staticmethod + def _find(db: sqlite3.Connection, table: str, identifier: str) -> Document: + # Table names are internal constants, never request data. + row = db.execute(f"SELECT body FROM {table} WHERE id=?", (identifier,)).fetchone() + if row is None: + raise EquipmentError("Запись не найдена. Обновите список.") + return cast(Document, json.loads(row[0])) + + def listing(self, vehicle: str | None = None) -> list[Document]: + with self.db() as db: + rows = [ + json.loads(r[0]) for r in db.execute("SELECT body FROM instances ORDER BY rowid") + ] + return [self.public(r) for r in rows if vehicle is None or r["vehicle_id"] == vehicle] + + def add( + self, candidate_id: str, name: str, vehicle_id: str, profile_id: str | None = None + ) -> Document: + name = name.strip() + if not name or len(name) > 80: + raise EquipmentError("Укажите название устройства до 80 символов.") + with self.db() as db: + db.execute("BEGIN IMMEDIATE") + candidate = self._find(db, "candidates", candidate_id) + if candidate["expires_at"] <= time.time(): + raise EquipmentError("Проверка USB устарела. Прочитайте трекер повторно.") + settings = candidate["settings"] + if profile_id: + profile = self._find(db, "profiles", profile_id) + if profile["model_id"] != candidate["model_id"]: + raise EquipmentError("Профиль предназначен для другой модели.") + settings = profile["settings"] + self.adapter(candidate["model_id"]).check_policy( + candidate, self.root / "evidence", settings + ) + row = { + **candidate, + "id": uuid.uuid4().hex, + "name": name, + "vehicle_id": vehicle_id, + "revision": 1, + "settings": settings, + "profile_id": profile_id, + "policy_state": "saved", + "updated_at": time.time(), + } + row.pop("expires_at") + try: + db.execute( + "INSERT INTO instances VALUES(?,?,?)", + (row["id"], row["identity_key"], json.dumps(row)), + ) + except sqlite3.IntegrityError: + raise EquipmentError( + "Этот трекер уже добавлен. Измените аппарат в его настройках." + ) from None + db.execute("DELETE FROM candidates WHERE id=?", (candidate_id,)) + return self.public(row) + + def update( + self, identifier: str, revision: int, name: str, vehicle_id: str, settings: Document + ) -> Document: + with self.db() as db: + db.execute("BEGIN IMMEDIATE") + old = self._find(db, "instances", identifier) + self.require_idle(old) + if old["revision"] != revision: + raise EquipmentError("Настройки изменились в другом окне. Откройте их заново.") + name = name.strip() + if not name or len(name) > 80: + raise EquipmentError("Укажите название устройства до 80 символов.") + settings = self.adapter(old["model_id"]).validate_policy(settings) + self.adapter(old["model_id"]).check_policy(old, self.root / "evidence", settings) + row = { + **old, + "name": name, + "vehicle_id": vehicle_id, + "settings": settings, + "revision": revision + 1, + "updated_at": time.time(), + } + if settings != old["settings"]: + row.update(policy_state="saved", profile_id=None) + db.execute( + "INSERT INTO history VALUES(?,?,?)", (old["id"], old["revision"], json.dumps(old)) + ) + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + return self.public(row) + + def refresh_observation(self, identifier: str, revision: int) -> Document: + with self.db() as db: + before = self._find(db, "instances", identifier) + self.require_idle(before) + if before["revision"] != revision: + raise EquipmentError("Настройки изменились. Откройте устройство заново.") + candidate = self.inspect(before["model_id"]) + with self.db() as db: + db.execute("BEGIN IMMEDIATE") + snapshot = self._find(db, "candidates", candidate["id"]) + old = self._find(db, "instances", identifier) + self.require_idle(old) + if old["revision"] != revision: + raise EquipmentError("Настройки изменились во время чтения. Повторите проверку.") + if snapshot["identity_key"] != old["identity_key"]: + raise EquipmentError("Подключён другой трекер. Существующая запись не изменена.") + row = { + **old, + "observed": snapshot["observed"], + "evidence_id": snapshot["evidence_id"], + "revision": revision + 1, + "updated_at": time.time(), + } + # Fresh USB observation supersedes the endpoint projection. + row.pop("network_server1", None) + if snapshot["observed"].get("configuration") != old["observed"].get("configuration"): + row["policy_state"] = "saved" + db.execute("INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(old))) + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + db.execute("DELETE FROM candidates WHERE id=?", (candidate["id"],)) + return self.public(row) + + def apply(self, identifier: str, revision: int) -> Document: + if not self.read_lock.acquire(blocking=False): + raise EquipmentError("USB занят. Дождитесь завершения текущего действия.") + try: + # Keep assignment/policy stable for the entire bounded USB operation. + with self.db() as db: + db.execute("BEGIN IMMEDIATE") + old = self._find(db, "instances", identifier) + self.require_idle(old) + if old["revision"] != revision: + raise EquipmentError("Настройки изменились. Откройте устройство заново.") + adapter = self.adapter(old["model_id"]) + adapter.check_policy(old, self.root / "evidence", old["settings"]) + result = adapter.apply(old, self.root / "evidence") + row = {**old, **result, "revision": revision + 1, "updated_at": time.time()} + if "observed" in result: + row.pop("network_server1", None) + db.execute( + "INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(old)) + ) + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) + return self.public(row) + finally: + self.read_lock.release() diff --git a/src/k1link/fleet/registry.py b/src/k1link/fleet/registry.py index 7fc14a8b..6ae65c0f 100644 --- a/src/k1link/fleet/registry.py +++ b/src/k1link/fleet/registry.py @@ -9,6 +9,11 @@ import time from contextlib import suppress from datetime import UTC, datetime, timedelta from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .independent_equipment import EquipmentStore + from .vps_hosts import VPSHosts from cryptography import x509 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey @@ -27,6 +32,8 @@ class FleetRegistry: raise PairingError("Хранилище реестра требует закрытый каталог.") self.started_at = time.time() self.root = root + self.independent_equipment: EquipmentStore | None = None + self.vps_hosts: VPSHosts | None = None self.lock = threading.RLock() from .events import FleetEvents @@ -119,6 +126,8 @@ class FleetRegistry: def close(self): self.stop.set() + if self.vps_hosts is not None: + self.vps_hosts.close() if self.worker: self.worker.join(timeout=20) if self.recovery_worker: diff --git a/src/k1link/fleet/vps_hosts.py b/src/k1link/fleet/vps_hosts.py new file mode 100644 index 00000000..67da2724 --- /dev/null +++ b/src/k1link/fleet/vps_hosts.py @@ -0,0 +1,467 @@ +"""Shared VPS hosts, durable pull cursors and independent tracker positions.""" + +import base64 +import http.client +import json +import logging +import secrets +import sqlite3 +import threading +import time +from collections.abc import Iterator +from contextlib import contextmanager, suppress +from pathlib import Path + +from k1link.device_plugins.arnavi_b2 import sim_access +from k1link.device_plugins.arnavi_b2.cellular import parse_telemetry_package as parse_package +from k1link.device_plugins.arnavi_b2.sim_network import merge as merge_sim_identity +from k1link.device_plugins.arnavi_b2.sim_network import public as public_sim_identity +from k1link.device_plugins.arnavi_b2.sim_observation_store import SimObservationStore + +from .independent_equipment import Document, EquipmentStore +from .trust import PairingError +from .vps_transport import invitation, request, validate_interface + + +class VPSHosts: + def __init__(self, root: Path, core_id: str, equipment: EquipmentStore) -> None: + self.root = root / "vps-hosts" + self.root.mkdir(mode=0o700, exist_ok=True) + if self.root.is_symlink() or self.root.stat().st_mode & 0o077: + raise PairingError("Хранилище VPS недоступно.") + self.path = self.root / "hosts.sqlite3" + self.core_id, self.equipment = core_id, equipment + self.lock, self.stop = threading.RLock(), threading.Event() + self.command_wake = threading.Event() + with self.db() as db: + db.executescript(""" + CREATE TABLE IF NOT EXISTS hosts(id TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS packets(host TEXT NOT NULL, seq INTEGER NOT NULL, + instance TEXT NOT NULL, received REAL NOT NULL, raw BLOB NOT NULL, + PRIMARY KEY(host,seq)); + CREATE TABLE IF NOT EXISTS positions(instance TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS outputs(instance TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS cellular(instance TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS b2_sim_identity( + instance TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS links(instance TEXT PRIMARY KEY, + host TEXT NOT NULL, received REAL NOT NULL); + """) + self.path.chmod(0o600) + self.worker = threading.Thread(target=self.run, daemon=True, name="mission-core-vps") + + @contextmanager + def db(self) -> Iterator[sqlite3.Connection]: + db = sqlite3.connect(self.path, timeout=10) + try: + db.execute("PRAGMA synchronous=FULL") + with db: + yield db + finally: + db.close() + + def start(self) -> None: + self.worker.start() + + def close(self) -> None: + self.stop.set() + self.command_wake.set() + self.worker.join(timeout=35) + + @staticmethod + def public(value: Document) -> Document: + return { + k: v for k, v in value.items() if k not in ("token", "secret", "fingerprint", "cursor") + } + + def rows(self) -> list[Document]: + with self.db() as db: + return [json.loads(r[0]) for r in db.execute("SELECT body FROM hosts ORDER BY rowid")] + + def listing(self) -> list[Document]: + return [self.public(row) for row in self.rows() if row["state"] != "replaced"] + + def save(self, row: Document) -> None: + with self.db() as db: + db.execute("INSERT OR REPLACE INTO hosts VALUES(?,?)", (row["id"], json.dumps(row))) + + def pair( + self, + code: str, + name: str, + vehicles: list[str], + network_interface: str | None = None, + replaces_id: str | None = None, + ) -> Document: + validate_interface(network_interface) + value = invitation(code.strip()) + with self.lock: + replaced = None + if replaces_id: + replaced = next((h for h in self.rows() if h["id"] == replaces_id), None) + if ( + not replaced + or replaced["state"] != "paired" + or replaced["endpoint"] != value["endpoint"] + or replaces_id == value["host_id"] + ): + raise PairingError("Выберите прежнюю запись этого же VPS для замены.") + elif any( + h["state"] == "paired" + and h["endpoint"] == value["endpoint"] + and h["id"] != value["host_id"] + for h in self.rows() + ): + raise PairingError( + "Этот адрес уже зарегистрирован. Выберите VPS, который переустановлен." + ) + row = next((h for h in self.rows() if h["id"] == value["host_id"]), None) + if row and row["state"] != "pending": + raise PairingError("Этот VPS уже добавлен. Откройте его настройки.") + if row is None: + row = { + **value, + "id": value["host_id"], + "name": name.strip(), + "vehicle_ids": sorted(set(vehicles)), + "revision": 1, + "token": secrets.token_urlsafe(32), + "cursor": 0, + "state": "pending", + "last_sync_at": None, + "status": None, + } + self.save(row) # Persist retry credential BEFORE the single-use exchange. + row["network_interface"] = network_interface + self.save(row) + status = request( + row, + "POST", + "/v1/pair", + {"core_id": self.core_id, "token": row["token"], "secret": row["secret"]}, + ) + if ( + status.get("host_id") != row["id"] + or status.get("schema") != "missioncore.vps-host/v1" + ): + raise PairingError("VPS вернул несовместимое подтверждение.") + row.update(state="paired", status=status, last_sync_at=time.time()) + row.pop("secret", None) + with self.db() as db: + db.execute("BEGIN IMMEDIATE") + db.execute("UPDATE hosts SET body=? WHERE id=?", (json.dumps(row), row["id"])) + if replaced: + replaced.update( + state="replaced", replaced_by=row["id"], revision=replaced["revision"] + 1 + ) + db.execute( + "UPDATE hosts SET body=? WHERE id=?", (json.dumps(replaced), replaced["id"]) + ) + return self.public(row) + + def update( + self, + identifier: str, + revision: int, + name: str, + vehicles: list[str], + network_interface: str | None = None, + ) -> Document: + validate_interface(network_interface) + with self.lock: + row = next((r for r in self.rows() if r["id"] == identifier), None) + if row is None or row["revision"] != revision: + raise PairingError("Настройки VPS изменились. Откройте их повторно.") + row.update( + name=name.strip(), + vehicle_ids=sorted(set(vehicles)), + revision=revision + 1, + network_interface=network_interface, + ) + self.save(row) + return self.public(row) + + def devices(self, row: Document) -> list[Document]: + endpoint = row["status"]["tracker"] + with self.equipment.db() as db: + devices = [json.loads(r[0]) for r in db.execute("SELECT body FROM instances")] + return [ + r + for r in devices + if r["vehicle_id"] in row["vehicle_ids"] + and r["model_id"] == "arnavi-b2" + and any( + s and s.get("host") == endpoint["host"] and s.get("port") == endpoint["port"] + for s in [ + r["settings"].get("endpoint"), + r.get("network_server1"), + *r.get("observed", {}).get("configuration", {}).get("servers", []), + ] + ) + ] + + def ingest(self, host: Document, items: list[Document], devices: list[Document]) -> int: + admitted = {d["id"]: d for d in devices} + cursor: int = int(host["cursor"]) + with self.db() as db: + for item in items: + if type(item["id"]) is not int or item["id"] <= cursor: + raise ValueError("non-monotonic journal") + raw = base64.b64decode(item["raw"], validate=True) + parsed = parse_package(raw) + if parsed is None or parsed[0] != len(raw): + raise ValueError("incomplete journal packet") + instance, received = item["instance_id"], float(item["received_at"]) + db.execute( + "INSERT OR IGNORE INTO packets VALUES(?,?,?,?,?)", + (host["id"], item["id"], instance, received, raw), + ) + if instance in admitted: + db.execute( + "INSERT INTO links VALUES(?,?,?) ON CONFLICT(instance) DO UPDATE SET " + "host=excluded.host,received=MAX(received,excluded.received)", + (instance, host["id"], received), + ) + for packet in parsed[1]: + measured = packet["measured_at"] + previous_sim = db.execute( + "SELECT body FROM b2_sim_identity WHERE instance=?", (instance,) + ).fetchone() + sim = merge_sim_identity( + json.loads(previous_sim[0]) if previous_sim else None, + packet, + host_id=host["id"], + sequence=item["id"], + received=received, + tracker=admitted[instance].get("identity_key"), + ) + if sim is not None: + db.execute( + "INSERT OR REPLACE INTO b2_sim_identity VALUES(?,?)", + (instance, json.dumps(sim)), + ) + if "cellular" in packet and 946684800 < measured <= received + 300: + previous = db.execute( + "SELECT body FROM cellular WHERE instance=?", (instance,) + ).fetchone() + cell = json.loads(previous[0]) if previous else {} + if cell.get("host_id") != host["id"]: + cell = {"host_id": host["id"], "networks": {}} + observation = packet["cellular"] + stamp = {"measured_at": measured, "received_at": received} + if "status" in observation and measured > cell.get("status", {}).get( + "measured_at", 0 + ): + previous_states = cell.get("status", {}).get("sim_states", {}) + for slot, state in observation["status"]["sim_states"].items(): + if state == 0 or ( + previous_states.get(slot) != state + and (previous_states.get(slot) == 0 or state == 2) + ): + # Removal / fresh search invalidates the previous + # card's network, even if it was measured recently. + cell["networks"].pop(slot, None) + cell.setdefault("network_invalidated_at", {})[slot] = ( + measured + ) + cell["status"] = {**observation["status"], **stamp} + for slot, network in observation.get("networks", {}).items(): + if measured < cell.get("network_invalidated_at", {}).get(slot, 0): + continue + current_status = cell.get("status", {}) + if current_status.get("sim_states", {}).get( + slot + ) == 0 and measured <= current_status.get("measured_at", 0): + continue + if measured > cell["networks"].get(slot, {}).get("measured_at", 0): + cell["networks"][slot] = {**network, **stamp} + db.execute( + "INSERT OR REPLACE INTO cellular VALUES(?,?)", + (instance, json.dumps(cell)), + ) + if "outputs" in packet and 946684800 < measured <= received + 300: + previous = db.execute( + "SELECT body FROM outputs WHERE instance=?", (instance,) + ).fetchone() + if not previous or json.loads(previous[0])["measured_at"] < measured: + outputs = { + "pins": packet["outputs"], + "host_id": host["id"], + "received_at": received, + "measured_at": measured, + } + db.execute( + "INSERT OR REPLACE INTO outputs VALUES(?,?)", + (instance, json.dumps(outputs)), + ) + if packet["position"] and 946684800 < measured <= received + 300: + previous = db.execute( + "SELECT body FROM positions WHERE instance=?", (instance,) + ).fetchone() + if previous and json.loads(previous[0])["measured_at"] >= measured: + continue + position = { + **packet["position"], + "instance_id": instance, + "host_id": host["id"], + "received_at": received, + "measured_at": measured, + } + db.execute( + "INSERT OR REPLACE INTO positions VALUES(?,?)", + (instance, json.dumps(position)), + ) + cursor = item["id"] + host["cursor"] = cursor + db.execute("UPDATE hosts SET body=? WHERE id=?", (json.dumps(host), host["id"])) + return cursor + + def sync(self, row: Document) -> None: + devices = self.devices(row) + admission = [] + for device in devices: + value = {"imei": device["identity_key"], "instance_id": device["id"]} + number = device.get("observed", {}).get("device_id") + if ( + isinstance(number, str) + and number.isascii() + and number.isdigit() + and 1 <= int(number) <= 0xFFFFFFFF + ): + value["device_id"] = int(number) + admission.append(value) + request( + row, + "PUT", + "/v1/devices", + {"items": admission}, + ) + batch = request(row, "GET", "/v1/packets?after=" + str(row["cursor"])) + cursor = self.ingest(row, batch["items"], devices) + if cursor: + request(row, "POST", "/v1/ack", {"through": cursor}) + row.update( + status=request(row, "GET", "/v1/status"), last_sync_at=time.time(), state="paired" + ) + self.save(row) + + def run(self) -> None: + next_sync: dict[str, float] = {} + while not self.stop.is_set(): + self.command_wake.clear() + pending = False + try: + pending = self._runtime_tick(next_sync) + except (OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException) as exc: + # A transient local database failure must not kill the durable sender. + logging.getLogger(__name__).warning( + "VPS runtime tick failed: %s", type(exc).__name__ + ) + if not self.stop.is_set(): + self.command_wake.wait(1 if pending else 5) + + def _runtime_tick(self, next_sync: dict[str, float]) -> bool: + from .equipment_command_runtime import pump + from .equipment_network import refresh + + with self.lock: + for row in self.rows(): + if self.stop.is_set(): + break + if row["state"] != "paired": + with suppress(OSError, ValueError, KeyError, sqlite3.Error): + refresh(self, row) + continue + # Preserve durable cursors and age the status on any failed exchange. + if time.monotonic() >= next_sync.get(row["id"], 0): + with suppress( + OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException + ): + self.sync(row) + next_sync[row["id"]] = time.monotonic() + 5 + # Reconcile durable command results even if telemetry synchronization fails. + with suppress( + OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException + ): + refresh(self, row) + with suppress(OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException): + pump(self) + with self.equipment.db() as db: + pending = db.execute( + "SELECT 1 FROM command_journal WHERE state IN " + "('waiting','submitting','queued','dispatched') LIMIT 1" + ).fetchone() + return bool(pending) + + def telemetry(self, vehicle: str | None = None) -> list[Document]: + devices = self.equipment.listing(vehicle) + hosts = {r["id"]: r for r in self.rows()} + with self.db() as db: + positions = { + r[0]: json.loads(r[1]) for r in db.execute("SELECT instance,body FROM positions") + } + links = { + r[0]: (r[1], r[2]) for r in db.execute("SELECT instance,host,received FROM links") + } + outputs = { + r[0]: json.loads(r[1]) for r in db.execute("SELECT instance,body FROM outputs") + } + cellular = { + r[0]: json.loads(r[1]) for r in db.execute("SELECT instance,body FROM cellular") + } + identities = { + r[0]: json.loads(r[1]) + for r in db.execute("SELECT instance,body FROM b2_sim_identity") + } + sim_store = SimObservationStore(self.root.parent / "independent-equipment" / "evidence") + result = [] + for device in devices: + link = links.get(device["id"]) + position = positions.get(device["id"]) + output = outputs.get(device["id"]) + cell = cellular.get(device["id"]) + sim = identities.get(device["id"]) + host = hosts.get(link[0]) if link else None + relevant = bool( + host and host["state"] == "paired" and device["vehicle_id"] in host["vehicle_ids"] + ) + if not relevant: + link, position, output, cell = None, None, None, None + elif output and link and output["host_id"] != link[0]: + output = None + if cell and (not link or cell["host_id"] != link[0]): + cell = None + if sim and (not relevant or not link or sim["host_id"] != link[0]): + sim = None + result.append( + { + "instance_id": device["id"], + "name": device["name"], + "vehicle_id": device["vehicle_id"], + "position": position, + "outputs": output, + "cellular": cell, + "internet_access": { + slot: sim_access.public( + sim_access.resolve(sim, sim_store, slot, now=time.time()) + ) + for slot in ("1", "2") + } + if sim + else None, + "sim_identity": public_sim_identity(sim, sim_store, now=time.time()) + if sim + else None, + "outputs_fresh": bool(output and 0 <= time.time() - output["measured_at"] < 90), + "last_packet_at": link[1] if link else None, + "online": bool( + link + and host + and host["last_sync_at"] + and time.time() - host["last_sync_at"] < 30 + and time.time() - link[1] < 90 + ), + "position_fresh": bool(position and time.time() - position["measured_at"] < 90), + } + ) + return result diff --git a/src/k1link/fleet/vps_transport.py b/src/k1link/fleet/vps_transport.py new file mode 100644 index 00000000..a82221f0 --- /dev/null +++ b/src/k1link/fleet/vps_transport.py @@ -0,0 +1,150 @@ +"""Public VPS transport, separate from the private-LAN Node pairing contract.""" + +import base64 +import hashlib +import http.client +import ipaddress +import json +import re +import socket +import ssl +import subprocess +import sys +import time +from typing import Any, cast +from urllib.parse import urlsplit + +from .trust import PairingError + + +def destination(endpoint: str) -> tuple[str, int, str]: + url = urlsplit(endpoint) + if ( + url.scheme != "https" + or url.username + or url.password + or url.path + or url.query + or url.fragment + or not url.hostname + or not url.port + or not 1024 <= url.port <= 65535 + ): + raise PairingError("Некорректный адрес VPS.") + addresses = { + str(item[4][0]) + for item in socket.getaddrinfo(url.hostname, url.port, socket.AF_INET, socket.SOCK_STREAM) + } + if not addresses or any(not ipaddress.ip_address(ip).is_global for ip in addresses): + raise PairingError("VPS должен иметь публичный IPv4 или DNS-имя.") + return url.hostname, url.port, sorted(addresses)[0] + + +def invitation(code: str) -> dict[str, Any]: + try: + if len(code) > 4096 or not code.startswith("MCV1."): + raise ValueError + encoded = code[5:] + value = json.loads( + base64.b64decode(encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True) + ) + if set(value) != {"schema", "host_id", "endpoint", "fingerprint", "secret", "expires_at"}: + raise ValueError + if ( + value["schema"] != "missioncore.vps-pairing/v1" + or not re.fullmatch("[0-9a-f]{64}", value["fingerprint"]) + or value["host_id"] != "vps_" + value["fingerprint"] + or not re.fullmatch("[A-Za-z0-9_-]{43}", value["secret"]) + ): + raise ValueError + if not time.time() < value["expires_at"] <= time.time() + 86500: + raise PairingError("Ключ VPS просрочен. Создайте новый ключ на сервере.") + destination(value["endpoint"]) + return cast(dict[str, Any], value) + except (ValueError, TypeError, KeyError) as error: + if isinstance(error, PairingError): + raise + raise PairingError("Ключ VPS повреждён или имеет неподдерживаемую версию.") from None + + +def interfaces() -> list[dict[str, str]]: + if sys.platform != "darwin": + return [] + labels: dict[str, str] = {} + try: + output = subprocess.run( + ["/usr/sbin/networksetup", "-listallhardwareports"], + capture_output=True, + text=True, + timeout=3, + check=True, + ).stdout + for block in output.split("\n\n"): + parts = dict(line.split(": ", 1) for line in block.splitlines() if ": " in line) + if "Device" in parts and "Hardware Port" in parts: + labels[parts["Device"]] = parts["Hardware Port"] + except (OSError, subprocess.SubprocessError): + pass + return [ + {"id": name, "label": labels.get(name, "Сетевой адаптер " + name)} + for _, name in socket.if_nameindex() + if re.fullmatch(r"en[0-9]+", name) + ] + + +def validate_interface(name: str | None) -> None: + if name and name not in {item["id"] for item in interfaces()}: + raise PairingError("Сетевой интерфейс недоступен на этом компьютере.") + + +def connect(address: str, port: int, interface: str | None) -> socket.socket: + validate_interface(interface) + if not interface: + return socket.create_connection((address, port), 8) + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + sock.settimeout(8) + # Darwin IP_BOUND_IF applies to this one socket, not global routing. + sock.setsockopt(socket.IPPROTO_IP, 25, socket.if_nametoindex(interface)) + sock.connect((address, port)) + return sock + except Exception: + sock.close() + raise + + +def request( + host: dict[str, Any], method: str, path: str, body: dict[str, Any] | None = None +) -> dict[str, Any]: + name, port, address = destination(host["endpoint"]) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + context.minimum_version = ssl.TLSVersion.TLSv1_3 + connection = http.client.HTTPConnection(name, port, timeout=8) + try: + raw = connect(address, port, host.get("network_interface")) + try: + secure = context.wrap_socket(raw, server_hostname=name) + except Exception: + raw.close() + raise + connection.sock = secure + if ( + hashlib.sha256(secure.getpeercert(binary_form=True) or b"").hexdigest() + != host["fingerprint"] + ): + raise PairingError("Идентичность VPS изменилась. Секреты не отправлены.") + headers = {"Content-Type": "application/json"} + if host.get("token"): + headers["Authorization"] = "Bearer " + host["token"] + connection.request( + method, path, json.dumps(body).encode() if body is not None else None, headers + ) + response = connection.getresponse() + data = response.read(4 * 1024 * 1024 + 1) + if response.status != 200 or len(data) > 4 * 1024 * 1024: + raise PairingError("VPS не подтвердил запрос. Проверьте ключ и состояние сервера.") + return cast(dict[str, Any], json.loads(data)) + finally: + connection.close() diff --git a/src/k1link/web/app.py b/src/k1link/web/app.py index e4963799..4ae544dd 100644 --- a/src/k1link/web/app.py +++ b/src/k1link/web/app.py @@ -112,6 +112,10 @@ from k1link.web.advanced_laboratory_api import build_advanced_laboratory_router from k1link.web.artifact_health_api import build_artifact_health_router from k1link.web.compute_contour_api import build_compute_contour_router from k1link.web.fleet_api import router as fleet_router +from k1link.web.independent_equipment_api import router as equipment_router +from k1link.web.equipment_firmware_api import router as equipment_firmware_router +from k1link.web.installer_api import router as installer_router +from k1link.web.vps_host_api import router as vps_host_router, start as start_vps_hosts from k1link.web.rover_api import router as rover_router from k1link.web.device_plugin_composition import load_installed_device_plugins from k1link.web.e30_engineering_api import build_e30_engineering_router @@ -939,6 +943,7 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]: try: fleet = FleetRegistry(session_store.data_dir / "fleet") fleet.start() + start_vps_hosts(fleet) application.state.fleet = fleet except (OSError, ValueError, sqlite3.Error): # Fail closed for pairing without taking down unrelated operator work. @@ -1005,6 +1010,10 @@ app.add_middleware(ResponseCompressionMiddleware, minimum_size=1_024, compressle app.include_router(fleet_router) +app.include_router(equipment_router) +app.include_router(equipment_firmware_router) +app.include_router(vps_host_router) +app.include_router(installer_router) app.include_router(rover_router) diff --git a/src/k1link/web/equipment_firmware_api.py b/src/k1link/web/equipment_firmware_api.py new file mode 100644 index 00000000..b32678b3 --- /dev/null +++ b/src/k1link/web/equipment_firmware_api.py @@ -0,0 +1,74 @@ +"""Local firmware files only: no USB, VPS, or manufacturer requests.""" + +import sqlite3 +from typing import Annotated, Any +from urllib.parse import quote + +from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response +from starlette.concurrency import run_in_threadpool + +from k1link.fleet.equipment_firmware import MAX_FIRMWARE_BYTES, FirmwareError +from k1link.fleet.registry import FleetRegistry +from k1link.web.fleet_api import local_operator +from k1link.web.independent_equipment_composition import firmware_archive + +router = APIRouter(prefix="/api/v1/fleet/equipment/firmware", tags=["equipment-firmware"]) +Fleet = Annotated[FleetRegistry, Depends(local_operator)] + + +@router.get("/{model}") +def catalog(model: str, response: Response, fleet: Fleet) -> dict[str, Any]: + response.headers["Cache-Control"] = "no-store" + try: + return {"items": firmware_archive(fleet).listing(model), "update_available": False} + except FirmwareError as exc: + raise HTTPException(409, str(exc)) from None + except (OSError, sqlite3.Error): + raise HTTPException(503, "Архив прошивок недоступен.") from None + + +@router.post("/{model}") +async def upload( + model: str, + request: Request, + fleet: Fleet, + filename: str = Query(min_length=1, max_length=120), +) -> dict[str, Any]: + if request.headers.get("content-type", "").split(";")[0] != "application/octet-stream": + raise HTTPException(415, "Передайте файл .dfw.") + data = bytearray() + async for chunk in request.stream(): + if len(data) + len(chunk) > MAX_FIRMWARE_BYTES: + raise HTTPException(413, "Размер файла не должен превышать 4 МБ.") + data.extend(chunk) + + def save() -> dict[str, Any]: + return firmware_archive(fleet).add(model, filename, bytes(data)) + + try: + return await run_in_threadpool(save) + except FirmwareError as exc: + raise HTTPException(422, str(exc)) from None + except (OSError, sqlite3.Error): + raise HTTPException(503, "Не удалось сохранить файл прошивки.") from None + + +@router.get("/{model}/{digest}/download") +def download(model: str, digest: str, fleet: Fleet) -> Response: + try: + item, data = firmware_archive(fleet).download(model, digest) + except FirmwareError as exc: + raise HTTPException(404, str(exc)) from None + except (OSError, sqlite3.Error): + raise HTTPException(503, "Файл прошивки недоступен.") from None + return Response( + data, + media_type="application/octet-stream", + headers={ + "Content-Disposition": "attachment; filename*=UTF-8''" + + quote(item["filename"], safe=""), + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + "X-Content-SHA256": item["sha256"], + }, + ) diff --git a/src/k1link/web/independent_equipment_api.py b/src/k1link/web/independent_equipment_api.py new file mode 100644 index 00000000..dc0d4bc2 --- /dev/null +++ b/src/k1link/web/independent_equipment_api.py @@ -0,0 +1,258 @@ +"""Local operator API for independent equipment, profiles and assignments.""" + +from collections.abc import Callable +from typing import Annotated, Literal + +from fastapi import APIRouter, Depends, HTTPException, Query, Response +from pydantic import BaseModel, ConfigDict, Field, ValidationError + +from k1link.fleet.independent_equipment import Document, EquipmentError +from k1link.fleet.registry import FleetRegistry +from k1link.fleet.trust import PairingError +from k1link.web.fleet_api import local_operator +from k1link.web.independent_equipment_composition import equipment_store + +router = APIRouter(prefix="/api/v1/fleet/equipment", tags=["independent-equipment"]) +Fleet = Annotated[FleetRegistry, Depends(local_operator)] + + +class ModelRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + model_id: str = Field(min_length=1, max_length=60) + + +class ProfileRequest(ModelRequest): + name: str = Field(min_length=1, max_length=80) + settings: Document + + +class AddRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + candidate_id: str = Field(min_length=43, max_length=43) + name: str = Field(min_length=1, max_length=80) + vehicle_id: str = Field(min_length=1, max_length=80) + profile_id: str | None = Field(default=None, min_length=32, max_length=32) + + +class UpdateRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + expected_revision: int = Field(ge=1, strict=True) + name: str = Field(min_length=1, max_length=80) + vehicle_id: str = Field(min_length=1, max_length=80) + settings: Document + + +def action(response: Response, callback: Callable[[], Document]) -> Document: + response.headers["Cache-Control"] = "no-store" + try: + return callback() + except (EquipmentError, PairingError) as exc: + raise HTTPException(409, str(exc)) from None + except ValidationError: + raise HTTPException( + 422, "Проверьте значения профиля. Уникальные данные и пароли в профиль не входят." + ) from None + except ValueError: + raise HTTPException( + 422, + "Не удалось проверить настройки или прочитать устройство. " + "Проверьте USB и совместимость профиля.", + ) from None + except OSError: + raise HTTPException(503, "Хранилище или USB недоступны. Повторите действие.") from None + + +@router.get("/catalog") +def catalog(response: Response, fleet: Fleet) -> Document: + return action(response, lambda: equipment_store(fleet).catalog()) + + +@router.get("/profiles") +def profiles(response: Response, fleet: Fleet) -> Document: + return action(response, lambda: {"items": equipment_store(fleet).profiles()}) + + +@router.post("/profiles") +def save_profile(body: ProfileRequest, response: Response, fleet: Fleet) -> Document: + return action( + response, + lambda: equipment_store(fleet).save_profile(body.name, body.model_id, body.settings), + ) + + +@router.post("/inspect") +def inspect(body: ModelRequest, response: Response, fleet: Fleet) -> Document: + return action(response, lambda: equipment_store(fleet).inspect(body.model_id)) + + +@router.get("/instances") +def instances(response: Response, fleet: Fleet, vehicle_id: str | None = None) -> Document: + return action(response, lambda: {"items": equipment_store(fleet).listing(vehicle_id)}) + + +@router.post("/instances") +def add(body: AddRequest, response: Response, fleet: Fleet) -> Document: + def run() -> Document: + with fleet.lock: + fleet.find(body.vehicle_id) # type: ignore[no-untyped-call] # legacy fleet boundary + result = equipment_store(fleet).add(**body.model_dump()) + fleet.events.notify() # type: ignore[no-untyped-call] # legacy fleet boundary + return result + + return action(response, run) + + +@router.put("/instances/{identifier}") +def update(identifier: str, body: UpdateRequest, response: Response, fleet: Fleet) -> Document: + def run() -> Document: + with fleet.lock: + fleet.find(body.vehicle_id) # type: ignore[no-untyped-call] # legacy fleet boundary + result = equipment_store(fleet).update( + identifier, body.expected_revision, body.name, body.vehicle_id, body.settings + ) + fleet.events.notify() # type: ignore[no-untyped-call] # legacy fleet boundary + return result + + return action(response, run) + + +class ReadRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + expected_revision: int = Field(ge=1, strict=True) + + +class NetworkApplyRequest(ReadRequest): + select_sim: bool = Field(default=False, strict=True) + + +class CommandRequest(ReadRequest): + kind: Literal["request-position", "pulse-output", "set-output", "restart"] + pin: int | None = Field(default=None, ge=4, le=6, strict=True) + seconds: int | None = Field(default=None, ge=1, le=5, strict=True) + enabled: bool | None = Field(default=None, strict=True) + + +@router.post("/instances/{identifier}/command") +def send_command( + identifier: str, body: CommandRequest, response: Response, fleet: Fleet +) -> Document: + from k1link.fleet.equipment_network import start + from k1link.web.vps_host_api import store + + command = body.model_dump(exclude={"expected_revision"}, exclude_none=True) + return action( + response, lambda: start(store(fleet), identifier, body.expected_revision, command=command) + ) + + +@router.post("/instances/{identifier}/inspect") +def read_existing(identifier: str, body: ReadRequest, response: Response, fleet: Fleet) -> Document: + return action( + response, + lambda: equipment_store(fleet).refresh_observation(identifier, body.expected_revision), + ) + + +@router.post("/instances/{identifier}/apply") +def apply_existing( + identifier: str, body: ReadRequest, response: Response, fleet: Fleet +) -> Document: + from k1link.fleet.equipment_bootstrap import apply + from k1link.web.vps_host_api import store + + return action(response, lambda: apply(store(fleet), identifier, body.expected_revision)) + + +@router.post("/instances/{identifier}/apply-network") +def apply_network( + identifier: str, body: NetworkApplyRequest, response: Response, fleet: Fleet +) -> Document: + from k1link.fleet.equipment_network import start + from k1link.web.vps_host_api import store + + return action( + response, + lambda: start(store(fleet), identifier, body.expected_revision, select_sim=body.select_sim), + ) + + +@router.post("/instances/{identifier}/inspect-network") +def inspect_network( + identifier: str, body: ReadRequest, response: Response, fleet: Fleet +) -> Document: + from k1link.fleet.equipment_network import start + from k1link.web.vps_host_api import store + + return action(response, lambda: start(store(fleet), identifier, body.expected_revision, True)) + + +class QueuedCommandRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + request_id: str = Field(pattern=r"^[a-f0-9]{32}$") + preset_id: str = Field(min_length=1, max_length=40) + + +@router.get("/instances/{identifier}/commands") +def command_runtime( + identifier: str, + response: Response, + fleet: Fleet, + before: int | None = Query(default=None, ge=1), + tracked: Annotated[list[str] | None, Query(max_length=32)] = None, +) -> Document: + from k1link.fleet.equipment_command_catalog import catalog + from k1link.fleet.equipment_command_journal import listing + from k1link.fleet.equipment_command_runtime import source + from k1link.fleet.equipment_operations import KINDS, supported + from k1link.web.vps_host_api import store + + def run() -> Document: + equipment = equipment_store(fleet) + with equipment.db() as db: + row = equipment._find(db, "instances", identifier) + host = source(store(fleet), row) + return { + **listing(equipment, identifier, before, tracked=tracked or ()), + "device": equipment.public(row), + "catalog": catalog(equipment, row), + "capacity": 32, + "durable_kinds": sorted(k for k in KINDS if supported(host or {}, k)), + } + + return action(response, run) + + +@router.post("/instances/{identifier}/commands") +def enqueue_command( + identifier: str, body: QueuedCommandRequest, response: Response, fleet: Fleet +) -> Document: + from k1link.fleet.equipment_command_runtime import enqueue + from k1link.web.vps_host_api import store + + return action( + response, lambda: enqueue(store(fleet), identifier, body.request_id, body.preset_id) + ) + + +@router.post("/instances/{identifier}/commands/{request_id}/cancel") +def cancel_command(identifier: str, request_id: str, response: Response, fleet: Fleet) -> Document: + from k1link.fleet.equipment_command_runtime import cancel + from k1link.web.vps_host_api import store + + return action( + response, lambda: cancel(equipment_store(fleet), identifier, request_id, store(fleet)) + ) + + +@router.get("/instances/{identifier}/commands/{request_id}/attempts") +def command_attempts( + identifier: str, + request_id: str, + response: Response, + fleet: Fleet, + before: int | None = Query(default=None, ge=1), +) -> Document: + from k1link.fleet.equipment_operations import attempts + from k1link.web.vps_host_api import store + + return action(response, lambda: attempts(store(fleet), identifier, request_id, before)) diff --git a/src/k1link/web/independent_equipment_composition.py b/src/k1link/web/independent_equipment_composition.py new file mode 100644 index 00000000..53c6cd15 --- /dev/null +++ b/src/k1link/web/independent_equipment_composition.py @@ -0,0 +1,19 @@ +"""Reviewed operator-host enrollment adapters; no onboard plugin dependency.""" + +from k1link.device_plugins.arnavi_b2.enrollment import B2Enrollment +from k1link.device_plugins.arnavi_b2.firmware import KNOWN_IMAGES +from k1link.fleet.equipment_firmware import FirmwareArchive +from k1link.fleet.independent_equipment import EquipmentStore +from k1link.fleet.registry import FleetRegistry + + +def equipment_store(fleet: FleetRegistry) -> EquipmentStore: + with fleet.lock: + if fleet.independent_equipment is None: + adapter = B2Enrollment() + fleet.independent_equipment = EquipmentStore(fleet.root, {adapter.model_id: adapter}) + return fleet.independent_equipment + + +def firmware_archive(fleet: FleetRegistry) -> FirmwareArchive: + return FirmwareArchive(fleet.root, {B2Enrollment.model_id: KNOWN_IMAGES}) diff --git a/src/k1link/web/installer_api.py b/src/k1link/web/installer_api.py new file mode 100644 index 00000000..75b99b0b --- /dev/null +++ b/src/k1link/web/installer_api.py @@ -0,0 +1,69 @@ +"""Verified, locally published installers. Never expose arbitrary filesystem paths.""" + +import hashlib +import json +import re +from pathlib import Path +from typing import Annotated, Any + +from fastapi import APIRouter, Depends, HTTPException, Response +from fastapi.responses import FileResponse + +from k1link.fleet.registry import FleetRegistry +from k1link.web.fleet_api import local_operator + +router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"]) +Fleet = Annotated[FleetRegistry, Depends(local_operator)] +KINDS = {"node", "vps-arnavi"} +DOWNLOAD_NAMES = { + "node": "mission-core-node-install.pyz", + "vps-arnavi": "mission-core-vps-install.pyz", +} + + +def verified(root: Path, kind: str) -> tuple[dict[str, Any], Path]: + if kind not in KINDS: + raise ValueError("unknown installer") + directory = root / "installers" + item = json.loads((directory / (kind + ".json")).read_text()) + if item["id"] != kind or not re.fullmatch(r"[a-zA-Z0-9_.-]+\.pyz", item["filename"]): + raise ValueError("invalid installer manifest") + file = directory / item["filename"] + if file.is_symlink() or file.stat().st_size != item["bytes"]: + raise ValueError("installer changed") + with file.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + if digest != item["sha256"]: + raise ValueError("installer changed") + return { + **item, + "filename": DOWNLOAD_NAMES[kind], + "download_url": f"/api/v1/fleet/installers/{kind}/download", + }, file + + +@router.get("") +def catalog(response: Response, fleet: Fleet) -> dict[str, Any]: + response.headers["Cache-Control"] = "no-store" + items = [] + for kind in sorted(KINDS): + try: + item, _ = verified(fleet.root, kind) + items.append(item) + except (OSError, ValueError, KeyError, TypeError): + continue + return {"items": items} + + +@router.get("/{kind}/download") +def download(kind: str, fleet: Fleet) -> FileResponse: + try: + item, path = verified(fleet.root, kind) + except (OSError, ValueError, KeyError, TypeError): + raise HTTPException(404, "Проверенный установщик недоступен.") from None + return FileResponse( + path, + filename=item["filename"], + media_type="application/octet-stream", + headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"}, + ) diff --git a/src/k1link/web/vps_host_api.py b/src/k1link/web/vps_host_api.py new file mode 100644 index 00000000..14ce88a1 --- /dev/null +++ b/src/k1link/web/vps_host_api.py @@ -0,0 +1,108 @@ +"""Local-operator VPS enrollment and shared vehicle assignment.""" + +import logging +import sqlite3 +from collections.abc import Callable +from typing import Annotated + +from fastapi import APIRouter, Depends, HTTPException, Response +from pydantic import BaseModel, ConfigDict, Field + +from k1link.fleet.independent_equipment import Document +from k1link.fleet.registry import FleetRegistry +from k1link.fleet.trust import PairingError +from k1link.fleet.vps_hosts import VPSHosts +from k1link.fleet.vps_transport import interfaces +from k1link.web.fleet_api import local_operator +from k1link.web.independent_equipment_composition import equipment_store + +router = APIRouter(prefix="/api/v1/fleet/vps-hosts", tags=["vps-hosts"]) +Fleet = Annotated[FleetRegistry, Depends(local_operator)] + + +def start(fleet: FleetRegistry) -> None: + try: + fleet.vps_hosts = VPSHosts(fleet.root, fleet.trust.core_id, equipment_store(fleet)) + fleet.vps_hosts.start() + except (OSError, ValueError, sqlite3.Error): + fleet.vps_hosts = None + logging.getLogger(__name__).error("VPS storage unavailable; independent host API disabled") + + +def store(fleet: FleetRegistry) -> VPSHosts: + if fleet.vps_hosts is None: + raise HTTPException(503, "Хранилище VPS недоступно.") + return fleet.vps_hosts + + +class Details(BaseModel): + model_config = ConfigDict(extra="forbid") + name: str = Field(min_length=1, max_length=80) + vehicle_ids: list[str] = Field(max_length=10000) + network_interface: str | None = Field(default=None, max_length=20) + + +class PairRequest(Details): + code: str = Field(min_length=1, max_length=4096) + replaces_id: str | None = Field(default=None, max_length=80) + + +class UpdateRequest(Details): + expected_revision: int = Field(ge=1) + + +def operation(fleet: FleetRegistry, body: Details, callback: Callable[[], Document]) -> Document: + try: + if not body.name.strip(): + raise PairingError("Укажите название VPS.") + with fleet.lock: + for vehicle in body.vehicle_ids: + fleet.find(vehicle) # type: ignore[no-untyped-call] # legacy fleet boundary + return callback() + except PairingError as error: + raise HTTPException(409, str(error)) from None + except (OSError, ValueError): + raise HTTPException( + 503, "Не удалось связаться с VPS. Проверьте адрес и доступность сервера." + ) from None + + +@router.get("") +def listing(response: Response, fleet: Fleet) -> Document: + response.headers["Cache-Control"] = "no-store" + return {"items": store(fleet).listing()} + + +@router.get("/interfaces") +def network_interfaces(fleet: Fleet) -> Document: + return {"items": interfaces()} + + +@router.get("/telemetry") +def telemetry(response: Response, fleet: Fleet, vehicle_id: str | None = None) -> Document: + response.headers["Cache-Control"] = "no-store" + return {"items": store(fleet).telemetry(vehicle_id)} + + +@router.post("") +def pair(body: PairRequest, response: Response, fleet: Fleet) -> Document: + response.headers["Cache-Control"] = "no-store" + return operation( + fleet, + body, + lambda: store(fleet).pair( + body.code, body.name, body.vehicle_ids, body.network_interface, body.replaces_id + ), + ) + + +@router.put("/{identifier}") +def update(identifier: str, body: UpdateRequest, response: Response, fleet: Fleet) -> Document: + response.headers["Cache-Control"] = "no-store" + return operation( + fleet, + body, + lambda: store(fleet).update( + identifier, body.expected_revision, body.name, body.vehicle_ids, body.network_interface + ), + ) diff --git a/tests/test_b2_automatic_connectivity.py b/tests/test_b2_automatic_connectivity.py new file mode 100644 index 00000000..f4dafa9f --- /dev/null +++ b/tests/test_b2_automatic_connectivity.py @@ -0,0 +1,160 @@ +"""Card identity, three-field APN overlay and the last network write boundary.""" + +import json +import time + +import pytest +from test_b2_cellular_telemetry import package, status +from test_b2_sim_identity import CARD_A, CARD_B, IMEI, capture, exchange +from test_b2_sim_network import AT, tags, update +from test_vps_host import full_context, reach_sim_restart, sim_context, store # noqa: F401 + +from k1link.device_plugins.arnavi_b2 import profiles, sim_access +from k1link.device_plugins.arnavi_b2.sim_network import binding +from k1link.device_plugins.arnavi_b2.sim_observation_store import SimObservationStore +from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, ProtocolError, Setting + + +def test_identity_survives_normal_telemetry_but_not_removal_search_or_archived_startup(): + value = update(raw=tags(1, CARD_A[1]) + status()) + value = update(value, at=AT + 1000, raw=status()) + assert binding(value, "1", now=AT + 1000) == CARD_A[1] + assert binding(value, "1", now=AT + 1100) is None + changed = update(value, at=AT + 1001, raw=status(first=2)) + assert binding(update(changed, at=AT + 1002, raw=status()), "1", now=AT + 1002) is None + archived = update(raw=tags(1, CARD_A[1]) + status(), received=AT + 1000) + assert binding(update(archived, at=AT + 1001, raw=status()), "1", now=AT + 1001) is None + + +def test_verified_access_follows_card_across_slots_and_survives_restart(tmp_path): + cache = SimObservationStore(tmp_path) + cache.record(capture(exchange(1, CARD_A) + exchange(2, CARD_B))) + value = update(raw=tags(1, CARD_A[1]) + tags(2, CARD_B[1]) + status()) + first = sim_access.resolve(value, cache, "1", now=AT) + assert first["source"] == "carrier_candidate" and first["access"] == ( + "internet.mts.ru", + "mts", + "mts", + ) + cache.remember_access( + IMEI, + first["card_ref"], + ("private.apn", "private-user", "private-pass"), + operation="a" * 32, + verified_at=AT, + configuration_sha256="b" * 64, + ) + swapped = update(value, at=AT + 1, raw=tags(1, CARD_B[1]) + tags(2, CARD_A[1]) + status()) + result = sim_access.resolve(swapped, SimObservationStore(tmp_path), "2", now=AT + 1) + assert result["source"] == "verified_card" and result["access"][0] == "private.apn" + assert sim_access.resolve(swapped, cache, "1", now=AT + 1)["source"] == "carrier_candidate" + assert "private-pass" not in json.dumps(sim_access.public(result)) + assert CARD_A[1] not in json.dumps(sim_access.public(result)) + assert cache.verified_access("other", first["card_ref"]) is None + cache.remember_access( + IMEI, + first["card_ref"], + ("old", "", ""), + operation="c" * 32, + verified_at=AT - 1, + configuration_sha256="d" * 64, + ) + assert cache.verified_access(IMEI, first["card_ref"])["access"][0] == "private.apn" + + +def test_unknown_card_cannot_be_guessed_from_serving_network_or_apn(tmp_path): + value = update(raw=tags(1, CARD_A[1]) + status()) + assert sim_access.resolve(value, SimObservationStore(tmp_path), "1", now=AT) == { + "state": "unknown_card" + } + + +def test_automatic_overlay_replaces_apn_and_credentials_only_for_selected_sim(): + config = Configuration( + tuple( + Setting(n, v) + for n, v in ( + (67, b"one"), + (68, b"user1"), + (69, b"pass1"), + (89, b"two"), + (90, b"user2"), + (91, b"pass2"), + (72, bytes(4)), + (222, b"unknown\xff"), + ) + ) + ) + policy = profiles.Policy( + connectivity={"strategy": "sim", "activate": True, "sim_slot": 2, "automatic": True} + ).model_dump() + with pytest.raises(ProtocolError, match="sim_access_not_resolved"): + profiles.prepare(config, policy) + desired = profiles.prepare(config, policy, automatic_access=("internet", "gdata", "gdata")) + assert [desired.text(n) for n in (89, 90, 91)] == ["internet", "gdata", "gdata"] + assert all(desired.value(n) == config.value(n) for n in (67, 68, 69, 222)) + assert desired.integer(72, 4) == 1 << 10 + assert not profiles.portable(desired)["connectivity"]["automatic"] + + +def guarded(context): + command, body, _, _, _, now = context + body["sim_guard"] = {"slot": 2, "sid": CARD_A[1]} + command.sim_guard.observe(body["imei"], package(int(now[0]), tags(2, CARD_A[1]) + status())) + return command, body, now + + +def test_card_swap_after_dispatch_prevents_http_configuration_write(sim_context): # noqa: F811 + command, body, now = guarded(sim_context) + _, _, before, _, wire, _ = sim_context + command.submit(body) + command.session_activity[body["imei"], "live"] = time.monotonic() + assert command.take(body["imei"], "live") + command.web_receive(wire(5, before.encode()), "192.0.2.1") + now[0] += 16 + command.session_activity[body["imei"], "live"] = time.monotonic() + assert command.take(body["imei"], "live") + command.sim_guard.observe(body["imei"], package(int(now[0]), tags(2, CARD_B[1]) + status())) + assert command.web_receive(wire(2), "192.0.2.1") is None + result = command.get(body["id"]) + assert result["state"] == "rejected" and result["reason"] == "sim_card_changed" + assert "write_reply_sent_at" not in result and "sim_guard" not in result + + +def test_gprs_without_new_card_identity_cannot_confirm_automatic_access(sim_context): # noqa: F811 + command, body, now = guarded(sim_context) + reach_sim_restart(sim_context) + assert command.take(body["imei"], "live") + now[0] += 2 + command.session_started[body["imei"], "new"] = time.monotonic() + now[0] += 1 + command.receive(body["imei"], package(int(now[0]), status()), "new") + assert command.get(body["id"])["state"] == "dispatched" + now[0] += 1 + command.receive(body["imei"], package(int(now[0]), tags(2, CARD_A[1]) + status()), "new") + result = command.get(body["id"]) + assert result["state"] == "sim_selected" and result["sim_guard_verified"] is True + + +def test_guard_and_waiting_intent_survive_vps_restart(sim_context): # noqa: F811 + from ndc_vps.commands import Commands + from ndc_vps.operations import Operations + + command, body, now = guarded(sim_context) + runtime = Operations(command.store, command) + runtime.submit(body) + command.sim_guard.observe(body["imei"], package(int(now[0] + 1), status(second=0))) + now[0] += 2 + command.session_activity[body["imei"], "live"] = time.monotonic() + runtime.advance(body["imei"]) + assert runtime.get(body["id"])["runtime_phase"] == "waiting-identity" + assert runtime.get(body["id"])["attempt_count"] == 0 + restored = Operations(command.store, Commands(command.store)) + restored.commands.sessions[body["imei"]] = {"new"} + restored.commands.session_activity[body["imei"], "new"] = time.monotonic() + restored.commands.sim_guard.observe( + body["imei"], package(int(now[0]), tags(2, CARD_B[1]) + status()) + ) + assert restored.get(body["id"])["state"] == "rejected" + assert restored.get(body["id"])["reason"] == "sim_card_changed" + assert restored.get(body["id"])["attempt_count"] == 0 diff --git a/tests/test_b2_cellular_telemetry.py b/tests/test_b2_cellular_telemetry.py new file mode 100644 index 00000000..c85e1212 --- /dev/null +++ b/tests/test_b2_cellular_telemetry.py @@ -0,0 +1,161 @@ +"""SIM observations are independent, time-scoped and never choose an APN.""" + +import base64 +import struct +import time + +import pytest + +from k1link.device_plugins.arnavi_b2.cellular import parse_telemetry_package +from k1link.fleet.vps_hosts import VPSHosts + + +def package(at, tags): + payload = struct.pack("SID{slot - 1}={sid}\r\n" + f"AT+CIMI\r\r\n{imsi}\r\n\r\nOK\r\nHC{slot - 1}={home}\r\n" + ).encode() + + +def sample(raw=b"", reports=(SHORT, CARD_B[1]), second=0, tracker=IMEI): + start = datetime(2026, 1, 1, tzinfo=UTC) + timedelta(seconds=second) + identity = Identity(231, "1", tracker, "0.01", *reports) + raw += ( + f">DI=231;0;1\r\n>DN=1\r\n>MN={tracker}\r\n" + f">SID0={reports[0] or ''}\r\n>SID1={reports[1] or ''}\r\n" + ).encode() + receipt = { + "session_id": "arnavi-read-" + uuid.uuid4().hex, + "started_at_utc": start.isoformat(), + "completed_at_utc": (start + timedelta(seconds=1)).isoformat(), + "usb_before": {"path": "/dev/cu.synthetic", "session": str(second)}, + "usb_after": {"path": "/dev/cu.synthetic", "session": str(second)}, + "status": "settings_read", + "raw_sha256": hashlib.sha256(raw).hexdigest(), + } + return identity, raw, receipt + + +def capture(*args, **kwargs): + return capture_from_read(*sample(*args, **kwargs)) + + +def snapshot(evidence, source): + identity, raw, receipt = source + directory = evidence / receipt["session_id"] + directory.mkdir(mode=0o700, parents=True) + (directory / "identity.json").write_text(json.dumps(asdict(identity))) + (directory / "response.bin").write_bytes(raw) + (directory / "receipt.json").write_text(json.dumps(receipt)) + (directory / "configuration.bin").write_bytes( + Configuration((Setting(25, b"\x00\x0f"), Setting(20, b"\x01"))).encode() + ) + return directory + + +@pytest.mark.parametrize( + "value,state", + [ + (None, "not_reported"), + (SHORT, "incomplete"), + (CARD_B[1], "unverified"), + (CARD_A[0], "unverified"), + ], +) +def test_i7_length_never_confirms_canonical_iccid(value, state): + assert reported_state(value) == state + + +def test_modem_sources_remain_distinct_and_private(): + value = modem_observations(exchange(2, CARD_B))[0] + assert value.slot == 2 and value.qualified + assert value.raw_ccid == CARD_B[0] and value.firmware_sid == CARD_B[1] + assert value.public()["ccid_format"] == "vendor_ff" + assert value.public()["ccid_equals_sid"] is False + for secret in CARD_B[:3]: + assert secret not in repr(value) and secret not in json.dumps(value.public()) + assert modem_observations(exchange(1, CARD_A))[0].public()["ccid_equals_sid"] is True + + +@pytest.mark.parametrize( + "raw", + [ + exchange(1, CARD_A).replace(b"HC0=", b"HC1="), + exchange(1, CARD_A).replace(b"AT+CIMI", b"ERROR\r\nAT+CIMI"), + exchange(1, CARD_A).replace(b"AT+CIMI", b"AT+CDSDS=2,0\r\nAT+CIMI"), + exchange(1, CARD_A)[:-1], + exchange(1, CARD_A).replace(b"OK", b"ERROR", 1), + ], +) +def test_incomplete_interleaved_or_failed_exchange_cannot_bind_card(raw): + assert modem_observations(raw) == () + + +def test_inconsistent_home_code_and_unknown_ccid_format_are_not_qualified(): + for card in [ + (CARD_A[0], CARD_A[1], CARD_A[2], "25002"), + ("a" * 20, CARD_A[1], CARD_A[2], CARD_A[3]), + ]: + value = capture(exchange(1, card)) + assert value.unique_for_slot(1) is None + slot = value.public()["slots"][0] + assert slot["modem_state"] == "unresolved" + assert slot["modem_observations"][0]["home_network"] is None + + +def test_repetition_is_ok_but_different_cards_in_one_slot_are_ambiguous(): + assert capture(exchange(1, CARD_A) * 2).unique_for_slot(1) is not None + assert capture(exchange(1, CARD_A) + exchange(1, CARD_B)).unique_for_slot(1) is None + duplicate = capture(exchange(1, CARD_A) + exchange(2, CARD_A)) + assert all(s["modem_state"] == "unresolved" for s in duplicate.public()["slots"]) + + +def test_swap_retains_card_refs_and_short_reads_do_not_replace_history(tmp_path): + journal = SimObservationStore(tmp_path) + first = capture(exchange(1, CARD_B) + exchange(2, CARD_A), reports=(SHORT, CARD_A[1])) + a = journal.record(first)["slots"] + swapped = capture(exchange(1, CARD_A) + exchange(2, CARD_B), second=10) + b = journal.record(swapped)["slots"] + assert a[0]["captured_card_ref"] == b[1]["captured_card_ref"] + assert a[1]["captured_card_ref"] == b[0]["captured_card_ref"] + assert b[0]["reported"]["state"] == "incomplete" + assert b[0]["readback_matches_modem_sid"] is False + assert b[1]["readback_matches_modem_sid"] is True + # Reopen, then arbitrarily many incomplete observations: no last-value overwrite. + journal = SimObservationStore(tmp_path) + for i in range(40): + latest = journal.record(capture(reports=(SHORT, None), second=20 + i * 2)) + for slot in latest["slots"]: + previous = slot["previous_modem_observation"] + assert previous["capture_id"] == swapped.capture_id + assert previous["historical"] is True and previous["current_slot_binding"] is False + assert slot["captured_card_ref"] is None and slot["modem_state"] == "not_observed" + assert latest["automatic_write_authorized"] is False + assert journal.record(first)["slots"] == a # Retry idempotence + no future history leakage. + assert journal.path.stat().st_mode & 0o077 == 0 + assert journal.path.parent.stat().st_mode & 0o077 == 0 + public = json.dumps(latest) + json.dumps(a) + json.dumps(b) + for secret in (*CARD_A[:3], *CARD_B[:3], SHORT, IMEI): + assert secret not in public + + +def test_conflicting_capture_id_cannot_mutate_or_leak_evidence(tmp_path): + journal = SimObservationStore(tmp_path) + value = capture(exchange(1, CARD_A)) + original = journal.record(value) + with pytest.raises(ProtocolError, match="^sim_capture_id_conflict$"): + journal.record(replace(value, reported=(CARD_B[1], None))) + with pytest.raises(ProtocolError, match="^sim_capture_id_conflict$"): + journal.public(replace(value, reported=(CARD_B[1], None))) + assert journal.public(value) == original + + +def test_same_card_on_different_tracker_has_no_shared_reference_or_history(tmp_path): + journal = SimObservationStore(tmp_path) + first = journal.record(capture(exchange(1, CARD_A)))["slots"][0] + second = journal.record(capture(exchange(1, CARD_A), tracker="000000000000002", second=10)) + assert second["slots"][0]["captured_card_ref"] != first["captured_card_ref"] + assert second["slots"][0]["previous_modem_observation"] is None + + +@pytest.mark.parametrize( + "change", + [ + {"raw_sha256": "0" * 64}, + {"status": "failed"}, + {"usb_after": {"session": "other"}}, + {"started_at_utc": "2026-01-01T00:00:00"}, + {"completed_at_utc": "2025-12-31T00:00:00+00:00"}, + ], +) +def test_failed_changed_or_unattributable_capture_is_rejected(change): + identity, raw, receipt = sample() + with pytest.raises(ProtocolError, match="^sim_capture_unqualified$"): + capture_from_read(identity, raw, {**receipt, **change}) + + +def test_unqualified_firmware_does_not_inherit_modem_parser_qualification(): + identity, raw, receipt = sample(exchange(1, CARD_A)) + result = capture_from_read(replace(identity, firmware="0.02"), raw, receipt) + assert result.exchanges == () and result.reported == (SHORT, CARD_B[1]) + + +def test_missing_or_tampered_evidence_is_unavailable_not_empty_sim(tmp_path): + directory = snapshot(tmp_path, sample(exchange(1, CARD_A))) + assert load_capture(directory).for_slot(1) + (directory / "response.bin").write_bytes(b"tampered") + public = snapshot_details(directory, record=True) + assert public == {"sim_identity": {"state": "unavailable", "automatic_write_authorized": False}} + assert not SimObservationStore(tmp_path).path.exists() + + +def test_symlink_store_is_rejected_without_touching_target(tmp_path): + target = tmp_path / "foreign" + target.mkdir() + (tmp_path / "sim-identity").symlink_to(target, target_is_directory=True) + with pytest.raises(ProtocolError, match="sim_store_unavailable"): + SimObservationStore(tmp_path).record(capture()) + assert list(target.iterdir()) == [] + + +def test_product_refresh_keeps_identity_history_out_of_profiles(tmp_path, monkeypatch): + from k1link.device_plugins.arnavi_b2 import enrollment + + sources = iter( + [ + sample(exchange(1, CARD_A), reports=(CARD_A[1], None)), + sample(reports=(SHORT, None), second=10), + ] + ) + + def reader(evidence): + directory = snapshot(evidence, next(sources)) + return {"evidence_directory": str(directory), **snapshot_details(directory, record=True)} + + monkeypatch.setattr(enrollment, "read_snapshot", reader) + store = EquipmentStore(tmp_path, {"arnavi-b2": B2Enrollment()}) + item = store.add(store.inspect("arnavi-b2")["id"], "Test B2", "rover-a") + original = item["observed"]["sim_identity"]["slots"][0] + current = store.refresh_observation(item["id"], item["revision"]) + reopened = EquipmentStore(tmp_path, {"arnavi-b2": B2Enrollment()}).listing()[0] + assert reopened == current + slot = current["observed"]["sim_identity"]["slots"][0] + assert slot["reported"]["state"] == "incomplete" + assert slot["previous_modem_observation"]["card_ref"] == original["captured_card_ref"] + assert current["settings"] == item["settings"] + assert ( + "sim_identity" not in store.save_profile("Test", "arnavi-b2", item["settings"])["settings"] + ) + for secret in (*CARD_A[:3], SHORT, IMEI): + assert secret not in json.dumps(current) diff --git a/tests/test_b2_sim_network.py b/tests/test_b2_sim_network.py new file mode 100644 index 00000000..76795829 --- /dev/null +++ b/tests/test_b2_sim_network.py @@ -0,0 +1,218 @@ +"""Synthetic wire SID pairs; no live SIM identifiers in fixtures.""" + +import base64 +import json +import struct +import time + +import pytest +from test_b2_cellular_telemetry import package, status +from test_b2_sim_identity import CARD_A, CARD_B, IMEI, capture, exchange + +from k1link.device_plugins.arnavi_b2.cellular import parse_telemetry_package +from k1link.device_plugins.arnavi_b2.sim_network import merge, public +from k1link.device_plugins.arnavi_b2.sim_observation_store import SimObservationStore +from k1link.fleet.vps_hosts import VPSHosts + +AT = 1790000000 + + +def tags(slot, sid): + first, second = (253, 254) if slot == 1 else (202, 203) + return ( + bytes([first]) + + struct.pack(" 10 + assert result["settings"] == row["settings"] + assert "unknown-secret" not in json.dumps(result) + with equipment.db() as db: + stored = json.loads( + db.execute("SELECT body FROM instances WHERE id=?", (row["id"],)).fetchone()[0] + ) + path = equipment.root / "evidence" / stored["evidence_id"] / "configuration.bin" + assert path.read_bytes() == config.encode() and path.stat().st_mode & 0o777 == 0o600 + + +def test_full_network_false_verified_receipt_is_not_accepted(full_core_context, monkeypatch): + equipment, hosts, row, config = full_core_context + + def send(host, method, path, body=None): + return { + "id": body["id"], + "kind": body["kind"], + "state": "verified", + "configuration": config.encode().hex(), + "configuration_sha256": hashlib.sha256(config.encode()).hexdigest(), + "configuration_received_at": time.time(), + } + + monkeypatch.setattr(network, "request", send) + result = network.start(hosts, row["id"], 1) + assert result["network_operation"]["state"] == "uncertain" + assert result["policy_state"] == "uncertain" + + +@pytest.fixture +def context(tmp_path): + equipment = EquipmentStore(tmp_path, {}) + hosts = VPSHosts(tmp_path, "core-synthetic", equipment) + config = Configuration( + tuple( + Setting(n, v) + for n, v in [ + (1, b"old.example"), + (2, (9922).to_bytes(2, "big")), + (9, b"\0"), + (3, b"current.example"), + (4, (9922).to_bytes(2, "big")), + (8, b"\0"), + (5, b"123456"), + (20, b"\x01"), + (21, b"\x01"), + (22, b"\x00"), + (25, b"\0\x0f"), + (67, b"apn"), + (89, b"apn"), + ] + ) + ) + evidence = equipment.root / "evidence" / "synthetic" + evidence.mkdir(parents=True) + (evidence / "configuration.bin").write_bytes(config.encode()) + row = { + "id": "c" * 32, + "identity_key": "123456789012345", + "model_id": "arnavi-b2", + "revision": 1, + "vehicle_id": "rover-a", + "name": "Synthetic B2", + "policy_state": "saved", + "evidence_id": "synthetic", + "observed": { + "firmware": "0.01", + "configuration": {"servers": [{"host": "current.example", "port": 9922, "slot": 2}]}, + }, + "settings": Policy( + endpoint={"host": "new.example", "port": 9922, "slot": 1}, parameters={"25": 15} + ).model_dump(), + } + with equipment.db() as db: + db.execute( + "INSERT INTO instances VALUES(?,?,?)", (row["id"], row["identity_key"], json.dumps(row)) + ) + for name in ("current", "new"): + hosts.save( + { + "id": name, + "state": "paired", + "last_sync_at": time.time(), + "vehicle_ids": ["rover-a"], + "status": { + "version": "0.1.6", + "tracker": {"host": name + ".example", "port": 9922}, + }, + } + ) + hosts.sync = Mock() + return equipment, hosts, row + + +def test_saved_destination_does_not_revoke_surviving_old_channel(context): + _, hosts, _ = context + assert all(len(hosts.devices(h)) == 1 for h in hosts.rows()) + + +def test_unsupported_mixed_profile_sends_nothing(context, monkeypatch): + equipment, hosts, row = context + row["settings"]["parameters"]["25"] = 30 + with equipment.db() as db: + db.execute("UPDATE instances SET body=?", (json.dumps(row),)) + sent = Mock() + monkeypatch.setattr(network, "request", sent) + with pytest.raises(EquipmentError, match="только адрес"): + network.start(hosts, row["id"], 1) + assert not sent.called + assert equipment.listing()[0]["revision"] == 1 + + +def test_durable_operation_before_post_retry_and_result_projection(context, monkeypatch): + equipment, hosts, row = context + calls = [] + + def send(host, method, path, body=None): + calls.append(body) + persisted = equipment.listing()[0] + assert persisted["network_operation"]["id"] == body["id"] + assert persisted["revision"] == 2 + return {"id": body["id"], "kind": body["kind"], "state": "queued", "password": "forbidden"} + + monkeypatch.setattr(network, "request", send) + result = network.start(hosts, row["id"], 1) + assert network.start(hosts, row["id"], 1) == result + assert len(calls) == 1 and "password" not in json.dumps(result) + with pytest.raises(EquipmentError, match="Дождитесь"): + equipment.update(row["id"], 2, "Changed", "rover-b", row["settings"]) + op = result["network_operation"] + network.record( + hosts, + row["id"], + op["id"], + { + "id": op["id"], + "kind": "configure-server1", + "state": "verified", + "verified_at": time.time(), + "server1": {"host": "new.example", "port": 9922}, + "replies": ["private"], + "password": "secret", + }, + ) + after = equipment.listing()[0] + assert after["network_server1"] == {"host": "new.example", "port": 9922} + assert after["policy_state"] == "saved" # endpoint scope is not the whole profile + assert "private" not in json.dumps(after) and "secret" not in json.dumps(after) + with equipment.db() as db: + private = equipment._find(db, "instances", row["id"]) + assert network.plan(equipment, private)["expected"] == after["network_server1"] + + +def test_ambiguous_post_is_polled_never_resubmitted_and_survives_restart(context, monkeypatch): + equipment, hosts, row = context + post = Mock(side_effect=OSError("connection lost")) + monkeypatch.setattr(network, "request", post) + result = network.start(hosts, row["id"], 1) + assert result["network_operation"]["state"] == "submitting" + host = hosts.rows()[0] + recreated = VPSHosts( + equipment.root.parent, "core-synthetic", EquipmentStore(equipment.root.parent, {}) + ) + network.refresh(recreated, host) + assert post.call_count == 2 and post.call_args.args[1] == "GET" + assert recreated.equipment.listing()[0]["network_operation"]["state"] == "submitting" + with equipment.db() as db: + saved = equipment._find(db, "instances", row["id"]) + saved["network_operation"]["expires_at"] = 0 + db.execute("UPDATE instances SET body=?", (json.dumps(saved),)) + network.refresh(recreated, host) + assert recreated.equipment.listing()[0]["network_operation"]["state"] == "uncertain" + assert sum(c.args[1] == "POST" for c in post.call_args_list) == 1 + + +def test_network_read_recovers_endpoint_without_leaking_getp(context, monkeypatch): + equipment, hosts, row = context + + def send(host, method, path, body=None): + return { + "id": body["id"], + "kind": "read-settings", + "state": "reply_received", + "replies": [ + "#1=other.example,9922,0,0,#2=private-apn,user,password#26=current.example,9922,0,0," + ], + } + + monkeypatch.setattr(network, "request", send) + result = network.start(hosts, row["id"], 1, True) + assert result["network_operation"]["state"] == "observed" + assert result["network_server1"] == {"host": "other.example", "port": 9922} + assert "password" not in json.dumps(result) and "private-apn" not in json.dumps(result) + + +def test_text_output_is_durable_idempotent_and_never_applies_profile(context, monkeypatch): + equipment, hosts, row = context + for host in hosts.rows(): + host["status"]["version"] = "0.1.10" + hosts.save(host) + sent = [] + + def send(host, method, path, body=None): + sent.append(body) + assert equipment.listing()[0]["network_operation"]["id"] == body["id"] + assert body["encoding"] == "text" and body["password"] == "123456" + return { + "id": body["id"], + "kind": body["kind"], + "state": "dispatched", + "created_at": 100, + "dispatched_at": 100.25, + "password": "secret", + } + + monkeypatch.setattr(network, "request", send) + command = {"kind": "set-output", "pin": 5, "enabled": True} + result = network.start(hosts, row["id"], 1, command=command) + assert network.start(hosts, row["id"], 1, command=command) == result + assert len(sent) == 1 + op = result["network_operation"] + assert op["queue_seconds"] == 0.25 and op["scope"] == "command" + assert result["policy_state"] == "saved" and "network_server1" not in result + assert all(s not in json.dumps(result) for s in ("123456", "secret", "encoding")) + with pytest.raises(EquipmentError, match="Дождитесь"): + network.start(hosts, row["id"], 2, command=command) + network.record( + hosts, + row["id"], + op["id"], + {"id": op["id"], "kind": "set-output", "state": "unconfirmed", "replies": ["SERV OK"]}, + ) + after = equipment.listing()[0] + assert after["network_operation"]["state"] == "unconfirmed" + assert "SERV OK" not in json.dumps(after) and after["policy_state"] == "saved" + assert len(sent) == 1 + + +@pytest.mark.parametrize( + "command", + [ + {"kind": "set-output", "pin": 5, "enabled": 1}, + {"kind": "set-output", "pin": True, "enabled": True}, + {"kind": "set-output", "pin": 6, "enabled": True}, + {"kind": "set-output", "pin": 5, "enabled": True, "seconds": 5}, + {"kind": "pulse-output", "pin": 5, "seconds": 6}, + {"kind": "pulse-output", "pin": 5, "seconds": True}, + {"kind": "request-position", "pin": 5}, + ], +) +def test_invalid_or_nonmanual_output_never_dispatches(context, monkeypatch, command): + equipment, hosts, row = context + sent = Mock() + monkeypatch.setattr(network, "request", sent) + with pytest.raises(EquipmentError): + network.start(hosts, row["id"], 1, command=command) + assert not sent.called and equipment.listing()[0]["revision"] == 1 + + +def test_output_requires_qualified_vps_and_online_host(context, monkeypatch): + _, hosts, row = context + sent = Mock() + monkeypatch.setattr(network, "request", sent) + command = {"kind": "set-output", "pin": 5, "enabled": False} + with pytest.raises(EquipmentError, match="версию VPS"): + network.start(hosts, row["id"], 1, command=command) + for host in hosts.rows(): + host["status"]["version"] = "0.1.10" + host["last_sync_at"] = 0 + hosts.save(host) + with pytest.raises(EquipmentError, match="связь с VPS"): + network.start(hosts, row["id"], 1, command=command) + assert not sent.called + + +def test_existing_enrollment_exposes_modes_without_usb_or_private_fields(context): + from k1link.device_plugins.arnavi_b2.enrollment import B2Enrollment + + equipment, _, row = context + adapter = B2Enrollment() + adapter.inspect = Mock(side_effect=AssertionError("must not access USB")) + equipment.adapters["arnavi-b2"] = adapter + public = equipment.listing()[0] + assert public["observed"]["output_modes"] == {"4": 1, "5": 1, "6": 0} + assert public["revision"] == row["revision"] and public["settings"] == row["settings"] + assert all(key not in public for key in ("identity_key", "evidence_id", "password")) + assert "123456" not in json.dumps(public) + (equipment.root / "evidence/synthetic/configuration.bin").write_bytes(b"corrupt") + assert equipment.listing()[0]["observed"]["output_modes"] == {} + + +def test_restart_version_gate_and_reconnected_projection(context, monkeypatch): + equipment, hosts, row = context + sent = [] + + def send(host, method, path, body=None): + sent.append(body) + return {"id": body["id"], "kind": body["kind"], "state": "queued"} + + monkeypatch.setattr(network, "request", send) + command = {"kind": "restart"} + with pytest.raises(EquipmentError, match="актуальную версию"): + network.start(hosts, row["id"], 1, command=command) + assert not sent + for host in hosts.rows(): + host["status"]["version"] = "0.1.17" + hosts.save(host) + result = network.start(hosts, row["id"], 1, command=command) + op = result["network_operation"] + assert op["expires_at"] - op["created_at"] > 200 + assert "password" not in sent[0] and "encoding" not in sent[0] + assert network.start(hosts, row["id"], 1, command=command) == result + assert len(sent) == 1 + with pytest.raises(ValueError, match="receipt is not reconnection"): + network.record( + hosts, + row["id"], + op["id"], + {"id": op["id"], "kind": "restart", "state": "device_confirmed"}, + ) + network.record( + hosts, + row["id"], + op["id"], + { + "id": op["id"], + "kind": "restart", + "state": "reconnected", + "reconnect_seconds": 27.5, + "reconnected_at": time.time(), + "binary": "private-wire", + "restart_sessions": ["private-session"], + }, + ) + final = equipment.listing()[0] + assert final["network_operation"]["state"] == "reconnected" + assert final["network_operation"]["reconnect_seconds"] == 27.5 + assert "private-" not in json.dumps(final) + assert final["policy_state"] == "saved" + + +def test_restart_http_contract_and_extra_fields(): + from pydantic import ValidationError + + from k1link.web.independent_equipment_api import CommandRequest + + assert CommandRequest.model_validate({"expected_revision": 2, "kind": "restart"}).model_dump( + exclude_none=True + ) == {"expected_revision": 2, "kind": "restart"} + with pytest.raises(ValidationError): + CommandRequest.model_validate( + {"expected_revision": 2, "kind": "restart", "raw_command": "1.6"} + ) + + +@pytest.mark.parametrize( + "stage,state,expected", + [ + ("preflight", "unconfirmed", "not_started"), + ("preflight", "expired", "not_started"), + ("preflight", "uncertain", "uncertain"), + ("write", "unconfirmed", "uncertain"), + ("verify", "uncertain", "uncertain"), + ], +) +def test_configuration_timeout_distinguishes_no_write_from_unknown_result( + full_core_context, monkeypatch, stage, state, expected +): + equipment, hosts, row, _ = full_core_context + monkeypatch.setattr( + network, + "request", + lambda h, m, p, body=None: { + "id": body["id"], + "kind": body["kind"], + "state": "dispatched", + "stage": "preflight", + "expires_at": time.time() + 180, + }, + ) + result = network.start(hosts, row["id"], 1) + op = result["network_operation"] + assert 175 < op["expires_at"] - time.time() <= 180 + network.record( + hosts, + row["id"], + op["id"], + { + "id": op["id"], + "kind": "configure-all", + "state": state, + "stage": stage, + }, + ) + final = equipment.listing()[0] + assert final["policy_state"] == expected + assert final["network_operation"]["state"] == state + + +def test_reachable_vps_cannot_extend_or_leave_expired_operation_pending(context, monkeypatch): + equipment, hosts, row = context + monkeypatch.setattr( + network, + "request", + lambda h, m, p, body=None: { + "id": body["id"], + "kind": body["kind"], + "state": "queued", + "expires_at": time.time() + 99999, + }, + ) + result = network.start(hosts, row["id"], 1) + op = result["network_operation"] + assert op["expires_at"] < time.time() + 241 + with equipment.db() as db: + saved = equipment._find(db, "instances", row["id"]) + saved["network_operation"]["expires_at"] = 1 + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"])) + requests = [] + + def stuck(h, method, path, body=None): + requests.append(method) + return {"id": op["id"], "kind": op["kind"], "state": "dispatched"} + + monkeypatch.setattr(network, "request", stuck) + network.refresh(hosts, hosts.rows()[0]) + assert equipment.listing()[0]["network_operation"]["state"] == "uncertain" + assert requests == ["GET"] # No automatic retry or second write. + + +@pytest.mark.parametrize( + "online,age,state", [(False, 1, 1), (True, 91, 1), (True, 1, 0), (True, -1, 1)] +) +def test_single_sim_write_requires_current_presence_before_dispatch( + full_core_context, monkeypatch, online, age, state +): + equipment, hosts, row, _ = full_core_context + with equipment.db() as db: + saved = equipment._find(db, "instances", row["id"]) + saved["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "apn": "new.apn"} + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"])) + monkeypatch.setattr( + hosts, + "telemetry", + lambda: [ + { + "instance_id": row["id"], + "online": online, + "cellular": { + "host_id": hosts.rows()[0]["id"], + "status": {"measured_at": time.time() - age, "sim_states": {"2": state}}, + }, + } + ], + ) + send = Mock() + monkeypatch.setattr(network, "request", send) + with pytest.raises(EquipmentError, match="SIM 2"): + network.start(hosts, row["id"], 1) + send.assert_not_called() + assert equipment.listing()[0]["revision"] == 1 + + +def test_single_sim_write_with_current_presence_targets_only_its_apn( + full_core_context, monkeypatch +): + from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration + + equipment, hosts, row, config = full_core_context + with equipment.db() as db: + saved = equipment._find(db, "instances", row["id"]) + saved["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "apn": "new.apn"} + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"])) + monkeypatch.setattr( + hosts, + "telemetry", + lambda: [ + { + "instance_id": row["id"], + "online": True, + "cellular": { + "host_id": "current", + "status": {"measured_at": time.time(), "sim_states": {"2": 1}}, + }, + } + ], + ) + sent = [] + + def send(host, method, path, body=None): + sent.append(body) + return {"id": body["id"], "kind": body["kind"], "state": "queued"} + + monkeypatch.setattr(network, "request", send) + result = network.start(hosts, row["id"], 1) + target = decode_configuration(bytes.fromhex(sent[0]["target_configuration"])) + assert target.text(89) == "new.apn" + assert target.value(67) == config.value(67) + assert result["settings"]["connectivity"]["strategy"] == "sim" + + +def test_sim_selection_is_one_durable_operation_and_settings_alone_cannot_complete_it( + full_core_context, monkeypatch +): + from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration + + equipment, hosts, row, config = full_core_context + row["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "activate": True} + with equipment.db() as db: + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"])) + for host in hosts.rows(): + host["status"]["version"] = "0.1.24" + hosts.save(host) + monkeypatch.setattr( + hosts, + "telemetry", + lambda: [ + { + "instance_id": row["id"], + "online": True, + "cellular": { + "host_id": "current", + "status": {"measured_at": time.time(), "sim_states": {"2": 1}}, + }, + } + ], + ) + sent = [] + + def send(host, method, path, body=None): + sent.append(body) + return {"id": body["id"], "kind": body["kind"], "state": "queued", "stage": "preflight"} + + monkeypatch.setattr(network, "request", send) + result = network.start(hosts, row["id"], 1) + op = result["network_operation"] + assert op["scope"] == "sim-selection" and op["sim_slot"] == 2 + assert sent[0]["kind"] == "select-sim" + target = decode_configuration(bytes.fromhex(sent[0]["target_configuration"])) + assert target.integer(72, 4) == config.integer(72, 4) | (1 << 10) + assert target.value(89) == config.value(89) + receipt = {"id": op["id"], "kind": "select-sim", "state": "verified"} + with pytest.raises(ValueError, match="not SIM selection"): + network.record(hosts, row["id"], op["id"], receipt) + with pytest.raises(ValueError, match="mismatch"): + network.record( + hosts, row["id"], op["id"], {**receipt, "state": "sim_selected", "active_sim": 1} + ) + receipt.update( + state="sim_selected", + active_sim=2, + configuration=target.encode().hex(), + configuration_sha256=hashlib.sha256(target.encode()).hexdigest(), + configuration_received_at=time.time(), + ) + network.record(hosts, row["id"], op["id"], receipt) + assert equipment.listing()[0]["policy_state"] == "applied" + assert equipment.listing()[0]["network_operation"]["active_sim"] == 2 + + +@pytest.mark.parametrize("lost_after_commit", [False, True]) +def test_outbox_survives_core_restart_preserves_wire_body_and_does_not_extend_deadline( + context, monkeypatch, lost_after_commit +): + equipment, hosts, row = context + now = [time.time()] + monkeypatch.setattr(network.time, "time", lambda: now[0]) + for host in hosts.rows(): + host["status"]["version"] = "0.1.26" + hosts.save(host) + accepted = {} + posts = [] + fail = [True] + + def send(host, method, path, body=None): + if method == "GET": + if not accepted: + raise OSError("not received yet") + return next(iter(accepted.values())) + posts.append(dict(body)) + if not fail[0] or lost_after_commit: + accepted.setdefault( + body["id"], + { + "id": body["id"], + "kind": body["kind"], + "state": "queued", + "expires_at": body["not_after"], + }, + ) + if fail[0]: + raise OSError("lost request or response") + return accepted[body["id"]] + + monkeypatch.setattr(network, "request", send) + result = network.start(hosts, row["id"], 1, command={"kind": "request-position"}) + assert result["network_operation"]["state"] == "submitting" + with equipment.db() as db: + assert db.execute("SELECT COUNT(*) FROM network_outbox").fetchone()[0] == 1 + assert "not_after" not in json.dumps(result) + fail[0] = False + now[0] += 6 + restored = VPSHosts( + equipment.root.parent, "core-synthetic", EquipmentStore(equipment.root.parent, {}) + ) + restored.sync = Mock() + host = next(h for h in restored.rows() if h["id"] == result["network_operation"]["host_id"]) + network.refresh(restored, host) + assert restored.equipment.listing()[0]["network_operation"]["state"] == "queued" + assert len(posts) == (1 if lost_after_commit else 2) + assert all(post == posts[0] for post in posts) + with equipment.db() as db: + assert db.execute("SELECT COUNT(*) FROM network_outbox").fetchone()[0] == 0 + + +def test_outbox_backoff_expiry_and_credentials_never_enter_public_history(context, monkeypatch): + equipment, hosts, row = context + now = [time.time()] + monkeypatch.setattr(network.time, "time", lambda: now[0]) + for host in hosts.rows(): + host["status"]["version"] = "0.1.26" + hosts.save(host) + calls = Mock(side_effect=OSError("offline")) + monkeypatch.setattr(network, "request", calls) + result = network.start( + hosts, row["id"], 1, command={"kind": "set-output", "pin": 5, "enabled": True} + ) + assert "123456" not in json.dumps(result) + host = next(h for h in hosts.rows() if h["id"] == result["network_operation"]["host_id"]) + with equipment.db() as db: + wire = json.loads(db.execute("SELECT body FROM network_outbox").fetchone()[0]) + assert wire["password"] == "123456" + assert '"password"' not in "".join(r[0] for r in db.execute("SELECT body FROM history")) + network.refresh(hosts, host) + assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1 + now[0] += 31 + network.refresh(hosts, host) + assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1 + now[0] += 40 + network.refresh(hosts, host) + assert equipment.listing()[0]["network_operation"]["state"] == "uncertain" + with equipment.db() as db: + assert db.execute("SELECT COUNT(*) FROM network_outbox").fetchone()[0] == 0 + + +def test_full_configuration_journal_preserves_each_dispatch_timestamp( + full_core_context, monkeypatch +): + from k1link.fleet import equipment_command_journal as journal + + equipment, hosts, row, _ = full_core_context + monkeypatch.setattr( + network, + "request", + lambda host, method, path, body=None: { + "id": body["id"], + "kind": body["kind"], + "state": "queued", + }, + ) + saved = network.start(hosts, row["id"], 1) + identifier = saved["network_operation"]["id"] + for stage, stamp in (("preflight", 100.5), ("write", 120.0), ("verify", 140.0)): + result = { + "id": identifier, + "kind": "configure-all", + "state": "dispatched", + "stage": stage, + "created_at": 100, + "dispatched_at": stamp, + "password": "private-secret", + "configuration_received_at": float("nan"), + } + network.record(hosts, row["id"], identifier, result) + network.record(hosts, row["id"], identifier, result) + value = journal.listing(equipment, row["id"])["items"][0] + assert value["dispatched_at"] == 140.0 and value["vps_created_at"] == 100 + assert [e["occurred_at"] for e in value["events"] if e.get("evidence") == "dispatched_at"] == [ + 100.5, + 120.0, + 140.0, + ] + assert "configuration_received_at" not in value and "private-secret" not in json.dumps(value) + recovered = { + **result, + "state": "queued", + "stage": "verify", + "recovery_at": 150.0, + "recovery_count": 1, + "recovery_verification": True, + } + network.record(hosts, row["id"], identifier, recovered) + network.record(hosts, row["id"], identifier, recovered) + value = journal.listing(equipment, row["id"])["items"][0] + assert value["recovery_count"] == 1 and value["recovery_verification"] + assert [e["occurred_at"] for e in value["events"] if e.get("evidence") == "recovery_at"] == [ + 150.0 + ] + + +def test_saved_sim_target_is_not_a_restart_for_unrelated_edit(full_core_context, monkeypatch): + from k1link.device_plugins.arnavi_b2.profiles import prepare + + equipment, hosts, row, config = full_core_context + row["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "activate": True} + baseline = prepare(config, {"connectivity": row["settings"]["connectivity"]}) + (equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").write_bytes( + baseline.encode() + ) + with equipment.db() as db: + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"])) + monkeypatch.setattr(hosts, "telemetry", lambda: []) + sent = [] + + def send(host, method, path, body=None): + sent.append(body) + return {"id": body["id"], "kind": body["kind"], "state": "queued"} + + monkeypatch.setattr(network, "request", send) + result = network.start(hosts, row["id"], 1) + assert result["network_operation"]["kind"] == "configure-all" + assert "sim_slot" not in sent[0] + assert sent[0]["target_configuration"] != baseline.encode().hex() # interval edit remains + + +def test_explicit_sim_action_runs_with_unchanged_bits_and_retries_same_job( + full_core_context, monkeypatch +): + from k1link.device_plugins.arnavi_b2.profiles import prepare + + equipment, hosts, row, config = full_core_context + row["settings"]["connectivity"] = {"strategy": "sim", "sim_slot": 2, "activate": True} + baseline = prepare(config, row["settings"]) + (equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").write_bytes( + baseline.encode() + ) + with equipment.db() as db: + db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"])) + for host in hosts.rows(): + host["status"]["version"] = "0.1.24" + hosts.save(host) + monkeypatch.setattr( + hosts, + "telemetry", + lambda: [ + { + "instance_id": row["id"], + "online": True, + "cellular": { + "host_id": "current", + "status": {"measured_at": time.time(), "sim_states": {"2": 1}}, + }, + } + ], + ) + sent = [] + + def send(host, method, path, body=None): + sent.append(body) + return {"id": body["id"], "kind": body["kind"], "state": "queued"} + + monkeypatch.setattr(network, "request", send) + first = network.start(hosts, row["id"], 1, select_sim=True) + retry = network.start(hosts, row["id"], 1, select_sim=True) + assert first["network_operation"]["kind"] == "select-sim" + assert first["network_operation"]["id"] == retry["network_operation"]["id"] + assert len(sent) == 1 and sent[0]["target_configuration"] == baseline.encode().hex() + with pytest.raises(EquipmentError, match="изменились"): + network.start(hosts, row["id"], 1, select_sim=False) diff --git a/tests/test_equipment_operations.py b/tests/test_equipment_operations.py new file mode 100644 index 00000000..85d8cb3f --- /dev/null +++ b/tests/test_equipment_operations.py @@ -0,0 +1,161 @@ +"""Core/VPS ownership survives lost HTTP, restarts and per-attempt timeouts.""" + +import ast +import json +import time +from pathlib import Path + +import pytest +from test_equipment_command_runtime import ready # noqa: F401 +from test_equipment_network import context # noqa: F401 + +from k1link.fleet import equipment_command_journal as journal +from k1link.fleet import equipment_command_runtime as runtime +from k1link.fleet import equipment_network as network +from k1link.fleet.independent_equipment import EquipmentStore + + +def shipped_version(): + source = Path(__file__).resolve().parents[1] / "apps/vps-host/ndc_vps/__init__.py" + module = ast.parse(source.read_text()) + return next( + ast.literal_eval(n.value) + for n in module.body + if isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == "VERSION" for t in n.targets) + ) + + +@pytest.fixture(params=sorted({"0.1.32", shipped_version()})) +def durable(ready, request): # noqa: F811 + equipment, hosts, row = ready + for host in hosts.rows(): + host["status"]["version"] = request.param + host["status"]["capabilities"] = ["arnavi-b2-durable-operations-v1"] + hosts.save(host) + return equipment, hosts, row + + +def test_lost_post_recovers_after_core_restart_without_job_deadline(durable, monkeypatch): + equipment, hosts, row = durable + calls = [] + + def lost(host, method, path, body=None): + calls.append((method, path, body)) + raise OSError("lost HTTP") + + monkeypatch.setattr(network, "request", lost) + job = runtime.enqueue(hosts, row["id"], "1" * 32, "position") + assert job["durable"] and "expires_at" not in job + runtime.pump(hosts) + assert calls[0][1] == "/v1/operations" and "not_after" not in calls[0][2] + original = calls[0][2] + now = time.time() + 86400 + monkeypatch.setattr(time, "time", lambda: now) + hosts.equipment = EquipmentStore(equipment.root.parent, {}) + source = next(h for h in hosts.rows() if h["id"] == "current") + network.refresh(hosts, source) + entry = journal.listing(hosts.equipment, row["id"])["items"][0] + assert entry["state"] == "submitting" and entry["reconcile_pending"] + assert calls[1][0] == "GET" and calls[-1][0] == "POST" and calls[-1][2] == original + + def restored(host, method, path, body=None): + calls.append((method, path, body)) + return { + "id": job["id"], + "kind": "request-position", + "durable": True, + "state": "device_confirmed", + "runtime_phase": "complete", + "attempt_count": 2, + "device_code": 0, + "received_at": now, + } + + monkeypatch.setattr(network, "request", restored) + network.refresh(hosts, source) + entry = journal.listing(hosts.equipment, row["id"])["items"][0] + assert entry["state"] == "device_confirmed" and not entry["reconcile_pending"] + assert calls[-1][0] == "GET" and entry["attempt_count"] == 2 + with hosts.equipment.db() as db: + assert db.execute("SELECT count(*) FROM network_outbox").fetchone()[0] == 0 + + +def test_attempt_facts_are_replaced_and_history_keeps_acceptance(durable, monkeypatch): + equipment, hosts, row = durable + + def queued(host, method, path, body=None): + return { + "id": body["id"], + "kind": body["kind"], + "durable": True, + "state": "queued", + "runtime_phase": "waiting-link", + "attempt_count": 0, + } + + monkeypatch.setattr(network, "request", queued) + job = runtime.enqueue(hosts, row["id"], "2" * 32, "position") + runtime.pump(hosts) + accepted = { + "id": job["id"], + "kind": "request-position", + "durable": True, + "state": "dispatched", + "runtime_phase": "executing", + "attempt_count": 1, + "device_code": 6, + "device_accepted_at": time.time(), + "dispatched_at": time.time(), + } + network.record(hosts, row["id"], job["id"], accepted) + network.record( + hosts, + row["id"], + job["id"], + { + "id": job["id"], + "kind": "request-position", + "durable": True, + "state": "queued", + "runtime_phase": "executing", + "attempt_count": 2, + }, + ) + entry = journal.listing(equipment, row["id"])["items"][0] + assert entry["attempt_count"] == 2 and "device_code" not in entry + assert "device_accepted_at" not in entry and "dispatched_at" not in entry + assert any(e["state"] == "device_accepted" for e in entry["events"]) + assert [e["attempt"] for e in entry["events"] if e["state"] == "attempt_started"] == [1, 2] + + +def test_stop_is_persisted_before_vps_contact_and_not_reposted(durable, monkeypatch): + equipment, hosts, row = durable + + def lost(*args): + raise OSError("lost") + + monkeypatch.setattr(network, "request", lost) + job = runtime.enqueue(hosts, row["id"], "3" * 32, "position") + runtime.pump(hosts) + runtime.cancel(equipment, row["id"], job["id"], hosts) + hosts.equipment = EquipmentStore(equipment.root.parent, {}) + calls = [] + + def stop(host, method, path, body=None): + calls.append((method, path, body)) + return { + "id": job["id"], + "kind": "request-position", + "durable": True, + "state": "stopped", + "runtime_phase": "stopped", + "stop_requested": True, + "attempt_count": 0, + } + + monkeypatch.setattr(network, "request", stop) + network.refresh(hosts, next(h for h in hosts.rows() if h["id"] == "current")) + assert calls == [("POST", f"/v1/operations/{job['id']}/cancel", {"kind": "request-position"})] + assert journal.listing(hosts.equipment, row["id"])["items"][0]["state"] == "stopped" + assert "password" not in json.dumps(journal.listing(hosts.equipment, row["id"])) diff --git a/tests/test_fleet_installers.py b/tests/test_fleet_installers.py new file mode 100644 index 00000000..e3be7d2f --- /dev/null +++ b/tests/test_fleet_installers.py @@ -0,0 +1,33 @@ +import hashlib +import json + +import pytest + +from k1link.web.installer_api import verified + + +def test_installer_catalog_refuses_tamper_and_path_escape(tmp_path): + root = tmp_path / "installers" + root.mkdir() + binary = root / "vps-0.1.2.pyz" + binary.write_bytes(b"synthetic qualified installer") + metadata = { + "id": "vps-arnavi", + "filename": binary.name, + "bytes": binary.stat().st_size, + "sha256": hashlib.sha256(binary.read_bytes()).hexdigest(), + } + manifest = root / "vps-arnavi.json" + manifest.write_text(json.dumps(metadata)) + item, path = verified(tmp_path, "vps-arnavi") + assert path == binary + assert item["download_url"].endswith("/vps-arnavi/download") + assert item["filename"] == "mission-core-vps-install.pyz" + binary.write_bytes(b"x" * metadata["bytes"]) + with pytest.raises(ValueError, match="changed"): + verified(tmp_path, "vps-arnavi") + manifest.write_text(json.dumps({**metadata, "filename": "../private.pyz"})) + with pytest.raises(ValueError, match="manifest"): + verified(tmp_path, "vps-arnavi") + with pytest.raises(ValueError): + verified(tmp_path, "../private") diff --git a/tests/test_independent_equipment.py b/tests/test_independent_equipment.py new file mode 100644 index 00000000..ffe59116 --- /dev/null +++ b/tests/test_independent_equipment.py @@ -0,0 +1,365 @@ +"""Synthetic identity only. No USB, vendor service or actual vehicle access.""" + +import json +import threading +import time +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import ValidationError + +from k1link.device_plugins.arnavi_b2.profiles import Policy, portable, prepare +from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, ProtocolError, Setting +from k1link.fleet.independent_equipment import EquipmentError, EquipmentStore +from k1link.web.independent_equipment_api import CommandRequest, router + + +@pytest.mark.parametrize( + "body", + [ + {"kind": "set-output", "pin": 5, "enabled": "false"}, + {"kind": "set-output", "pin": 5, "enabled": 1}, + {"kind": "pulse-output", "pin": "5", "seconds": 2}, + {"kind": "pulse-output", "pin": 5, "seconds": 6}, + {"kind": "request-position", "password": "123456"}, + ], +) +def test_command_api_rejects_coercion_and_private_credentials(body): + with pytest.raises(ValidationError): + CommandRequest(expected_revision=1, **body) + + +def config(): + return Configuration( + ( + Setting(25, b"\x00\x0f"), + Setting(63, b"\x0a"), + Setting(1, b"example.test\x00"), + Setting(2, b"\x50\x8f"), + Setting(9, b"\x00"), + Setting(67, b"old.apn\x00"), + Setting(89, b""), + Setting(68, b"private-login"), + Setting(5, b"123456"), + Setting(135, b"unknown"), + Setting(243, (-100).to_bytes(2, "big", signed=True)), + ) + ) + + +class Adapter: + model_id = "arnavi-b2" + identity = "000000000000001" + + def catalog(self): + return {"id": self.model_id} + + def validate_policy(self, value): + return Policy.model_validate(value).model_dump() + + def inspect(self, evidence): + return { + "identity_key": self.identity, + "model_id": self.model_id, + "observed": {"imei_suffix": self.identity[-5:]}, + "evidence_id": "synthetic", + "settings": portable(config()), + } + + def check_policy(self, candidate, evidence, settings): + prepare(config(), settings) + + def apply(self, instance, evidence): + return {"policy_state": "applied", "operation": {"state": "applied"}} + + +@pytest.fixture +def store(tmp_path): + return EquipmentStore(tmp_path, {"arnavi-b2": Adapter()}) + + +def test_apply_serializes_saved_policy_and_stale_revision_cannot_repeat_it(store): + candidate = store.inspect("arnavi-b2") + item = store.add(candidate["id"], "Tracker", "vehicle-a") + applied = store.apply(item["id"], item["revision"]) + assert applied["policy_state"] == "applied" + assert applied["revision"] == item["revision"] + 1 + assert applied["vehicle_id"] == "vehicle-a" + with pytest.raises(EquipmentError): + store.apply(item["id"], item["revision"]) + changed = store.update(applied["id"], applied["revision"], "Tracker", "vehicle-a", {}) + assert changed["policy_state"] == "saved" + + +@pytest.mark.parametrize( + "extra", ["imei", "sim", "operator", "vehicle_id", "password", "raw_configuration"] +) +def test_unique_data_and_unknown_fields_are_rejected(extra): + with pytest.raises(ValidationError): + Policy.model_validate({extra: "secret"}) + + +@pytest.mark.parametrize( + "params", + [ + {"5": 123456}, + {"68": 1}, + {"25": True}, + {"25": "15"}, + {"25": 65536}, + {"243": -10001}, + {"243": 100, "244": 0}, + ], +) +def test_secret_fields_invalid_types_ranges_and_relations_rejected(params): + with pytest.raises(ValidationError): + Policy.model_validate({"parameters": params}) + + +def test_portable_profile_is_not_config_clone(): + value = portable(config()) + assert value["parameters"] == {"25": 15, "63": 10, "243": -100} + text = json.dumps(value) + for secret in ["123456", "private-login", "old.apn", "unknown"]: + assert secret not in text + assert value["endpoint"] is None + assert value["connectivity"]["strategy"] == "preserve" + + +def test_overlay_preserves_unknown_identity_secrets_and_handles_explicit_zero(): + before = config() + policy = { + "parameters": {"25": 0}, + "endpoint": {"host": "track.example.test", "port": 9023, "slot": 1}, + } + result = prepare(before, policy) + assert result.integer(25, 2) == 0 + assert result.text(1) == "track.example.test" + for number in [5, 63, 67, 68, 135, 243]: + assert result.value(number) == before.value(number) + assert result.records[-1].number == 243 + with pytest.raises(ProtocolError): + prepare(before, {"parameters": {"246": 70}}) + + +def test_explicit_apn_only_and_no_carrier_guess(): + with pytest.raises(ValidationError): + Policy.model_validate({"connectivity": {"strategy": "auto"}}) + with pytest.raises(ValidationError): + Policy.model_validate({"connectivity": {"strategy": "manual"}}) + after = prepare(config(), {"connectivity": {"strategy": "manual", "apn1": "iot.example"}}) + assert after.text(67) == "iot.example" + assert after.text(68) == "private-login" + + +def test_operator_preset_replaces_complete_access_only_for_selected_sim(): + before = Configuration( + config().records + + ( + Setting(69, b"private-password"), + Setting(90, b"other-login"), + Setting(91, b"other-password"), + ) + ) + policy = { + "connectivity": { + "strategy": "operator", + "preset_id": "ru-mts-public-v1", + "sim_slot": 2, + } + } + after = prepare(before, policy) + assert [after.text(n) for n in (89, 90, 91)] == ["internet.mts.ru", "mts", "mts"] + assert {r.number for r in before.records if r.value != after.value(r.number)} == {89, 90, 91} + # Portable policy carries a public preset reference, never old private access strings. + saved = json.dumps(Policy.model_validate(policy).model_dump()) + assert "private-password" not in saved and "other-password" not in saved + assert portable(after)["connectivity"]["strategy"] == "preserve" + with pytest.raises(ProtocolError): + prepare(config(), policy) # Missing second-SIM credential fields fails before writing. + + +@pytest.mark.parametrize( + "connection", + [ + {"strategy": "operator"}, + {"strategy": "operator", "preset_id": "guessed-carrier"}, + {"strategy": "operator", "preset_id": "ru-mts-public-v1", "sim_slot": True}, + {"strategy": "operator", "preset_id": "ru-mts-public-v1", "sim_slot": 3}, + {"strategy": "operator", "preset_id": "ru-mts-public-v1", "apn1": "other.apn"}, + {"strategy": "preserve", "preset_id": "ru-mts-public-v1"}, + {"strategy": "operator", "preset_id": "ru-mts-public-v1", "phone": "+10000000000"}, + {"strategy": "operator", "preset_id": "ru-mts-public-v1", "password": "secret"}, + ], +) +def test_carrier_preset_rejects_ambiguous_or_unique_settings(connection): + with pytest.raises(ValidationError): + Policy.model_validate({"connectivity": connection}) + + +def test_profiles_are_immutable_copies_and_private_fields_do_not_escape(store): + candidate = store.inspect("arnavi-b2") + assert "identity_key" not in candidate and "evidence_id" not in candidate + profile = store.save_profile("Road", "arnavi-b2", {"parameters": {"25": 5}}) + device = store.add(candidate["id"], "Tracker", "rover-a", profile["id"]) + changed = store.update(device["id"], 1, "Tracker", "rover-a", {"parameters": {"25": 8}}) + assert changed["settings"]["parameters"]["25"] == 8 + assert store.profiles()[0]["settings"]["parameters"]["25"] == 5 + assert changed["profile_id"] is None + assert changed["policy_state"] == "saved" + assert "identity_key" not in changed + reopened = EquipmentStore(store.root.parent, store.adapters) + assert reopened.listing() == store.listing() + + +def test_reassignment_many_per_vehicle_identity_dedup_and_stale_revision(store): + first = store.add(store.inspect("arnavi-b2")["id"], "First", "rover-a") + duplicate = store.inspect("arnavi-b2") + with pytest.raises(EquipmentError, match="уже добавлен"): + store.add(duplicate["id"], "Duplicate", "rover-b") + store.adapters["arnavi-b2"].identity = "000000000000002" + second = store.add(store.inspect("arnavi-b2")["id"], "Second", "rover-a") + assert len(store.listing("rover-a")) == 2 + moved = store.update(first["id"], 1, "Moved", "rover-b", first["settings"]) + assert moved["id"] == first["id"] + assert store.listing("rover-a")[0]["id"] == second["id"] + with pytest.raises(EquipmentError, match="другом окне"): + store.update(first["id"], 1, "Stale", "rover-a", first["settings"]) + with store.db() as db: + old = json.loads(db.execute("SELECT body FROM history").fetchone()[0]) + assert old["vehicle_id"] == "rover-a" + + +def test_expired_candidate_and_concurrent_usb_reader_rejected(store): + candidate = store.inspect("arnavi-b2") + with store.db() as db: + row = store._find(db, "candidates", candidate["id"]) + row["expires_at"] = time.time() - 1 + db.execute("UPDATE candidates SET body=? WHERE id=?", (json.dumps(row), candidate["id"])) + with pytest.raises(EquipmentError, match="устарела"): + store.add(candidate["id"], "Tracker", "rover-a") + with store.read_lock, pytest.raises(EquipmentError, match="уже выполняется"): + store.inspect("arnavi-b2") + + +def test_api_local_origin_policy_and_real_vehicle_check(store): + app = FastAPI() + app.include_router(router) + known = {"rover-a"} + + def find(identifier): + if identifier not in known: + raise EquipmentError("Аппарат не найден.") + + app.state.fleet = SimpleNamespace( + lock=threading.RLock(), + independent_equipment=store, + find=find, + events=SimpleNamespace(notify=lambda: None), + ) + with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 12345)) as client: + base = "/api/v1/fleet/equipment" + assert client.get(base + "/catalog").status_code == 200 + assert ( + client.post( + base + "/inspect", + json={"model_id": "arnavi-b2"}, + headers={"Origin": "https://bad.example"}, + ).status_code + == 403 + ) + assert client.get(base + "/catalog", headers={"Host": "bad.example"}).status_code == 403 + invalid = client.post( + base + "/profiles", + json={"name": "Bad", "model_id": "arnavi-b2", "settings": {"imei": "secret"}}, + ) + assert invalid.status_code == 422 and "secret" not in invalid.text + candidate = client.post(base + "/inspect", json={"model_id": "arnavi-b2"}).json() + response = client.post( + base + "/instances", + json={"candidate_id": candidate["id"], "name": "Unit", "vehicle_id": "invented"}, + ) + assert response.status_code == 409 + response = client.post( + base + "/instances", + json={"candidate_id": candidate["id"], "name": "Unit", "vehicle_id": "rover-a"}, + ) + assert response.status_code == 200 + assert response.headers["cache-control"] == "no-store" + assert "identity_key" not in response.json() + + +def test_usb_reread_preserves_policy_and_rejects_wrong_tracker(store): + item = store.add(store.inspect("arnavi-b2")["id"], "Tracker", "rover-a") + same = store.refresh_observation(item["id"], 1) + assert same["revision"] == 2 and same["settings"] == item["settings"] + store.adapters["arnavi-b2"].identity = "000000000000003" + with pytest.raises(EquipmentError, match="другой трекер"): + store.refresh_observation(item["id"], 2) + assert store.listing()[0] == same + + +def test_single_sim_apn_edit_preserves_other_slot_and_credentials(): + from k1link.device_plugins.arnavi_b2.profiles import prepare + from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting + + source = Configuration( + tuple( + Setting(n, v) + for n, v in [ + (67, b"first.apn"), + (68, b"first-user"), + (69, b"first-secret"), + (89, b"second.apn"), + (90, b"second-user"), + (91, b"second-secret"), + ] + ) + ) + for slot, field in [(1, 67), (2, 89)]: + policy = {"connectivity": {"strategy": "sim", "sim_slot": slot, "apn": "new.apn"}} + target = prepare(source, policy) + assert target.text(field) == "new.apn" + assert all(r.value == source.value(r.number) for r in target.records if r.number != field) + with pytest.raises(ValueError): + prepare(source, {"connectivity": {"strategy": "sim", "sim_slot": 2}}) + + +@pytest.mark.parametrize("slot", [1, 2]) +def test_sim_selection_preserves_apns_credentials_and_unrelated_flags(slot): + from k1link.device_plugins.arnavi_b2.profiles import prepare + from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting + + source = Configuration( + tuple( + Setting(n, v) + for n, v in [ + (72, (0x81000818).to_bytes(4, "big")), + (67, b"internet"), + (89, b"internet.mts.ru"), + (90, b"private-user"), + (91, b"private-secret"), + ] + ) + ) + target = prepare( + source, {"connectivity": {"strategy": "sim", "sim_slot": slot, "activate": True}} + ) + expected = (0x81000818 & ~((1 << 10) | (1 << 20))) | (1 << (20 if slot == 1 else 10)) + assert target.integer(72, 4) == expected + assert all(target.value(n) == source.value(n) for n in (67, 89, 90, 91)) + edited = prepare( + source, + { + "connectivity": { + "strategy": "sim", + "sim_slot": slot, + "activate": True, + "apn": "custom.apn", + } + }, + ) + assert edited.text(67 if slot == 1 else 89) == "custom.apn" + assert edited.integer(72, 4) == expected diff --git a/tests/test_vps_command_receipts.py b/tests/test_vps_command_receipts.py new file mode 100644 index 00000000..ed801d7b --- /dev/null +++ b/tests/test_vps_command_receipts.py @@ -0,0 +1,93 @@ +"""B2 token receipts can return through either admitted monitoring connection.""" + +import struct +import time + +import pytest +from test_vps_host import store # noqa: F401 + + +def receipt(token, code=0): + data = struct.pack(" 0 + commands.receive(imei, receipt(token, 6), "primary") + assert commands.get(body["id"])["device_accepted_at"] == accepted["device_accepted_at"] + commands.receive(imei, receipt(token, 5), "secondary") + assert commands.get(body["id"])["state"] == "device_rejected" + + +@pytest.mark.parametrize("source", ["unknown-session", "wrong-token", "other-tracker", "closed"]) +def test_unrelated_receipt_never_completes_command(pending, source): + commands, imei, other, body, token = pending + session = "secondary" + if source == "unknown-session": + session = "unadmitted" + elif source == "wrong-token": + token = bytes(value ^ 255 for value in token) + elif source == "other-tracker": + imei, session = other, "another-tracker" + else: + commands.sessions[imei].remove(session) + commands.receive(imei, receipt(token), session) + assert commands.get(body["id"])["state"] == "dispatched" + + +def test_new_connection_can_deliver_exact_receipt_without_replay(pending): + commands, imei, _, body, token = pending + commands.sessions[imei] = {"reconnected"} + commands.receive(imei, receipt(token), "reconnected") + assert commands.get(body["id"])["state"] == "device_confirmed" + assert commands.take(imei, "reconnected") is None + + +def test_revoked_device_receipt_is_not_accepted(pending): + commands, imei, _, body, token = pending + commands.store.set_devices([]) + commands.receive(imei, receipt(token), "secondary") + assert commands.get(body["id"])["state"] == "dispatched" diff --git a/tests/test_vps_host.py b/tests/test_vps_host.py new file mode 100644 index 00000000..e21682d2 --- /dev/null +++ b/tests/test_vps_host.py @@ -0,0 +1,2303 @@ +"""Durability, identity admission, decoder and shared VPS assignment acceptance.""" + +import asyncio +import base64 +import hashlib +import importlib +import json +import shutil +import struct +import sys +import time +from pathlib import Path + +import pytest + +from k1link.device_plugins.arnavi_b2 import internal +from k1link.fleet.vps_hosts import VPSHosts + +ROOT = Path(__file__).resolve().parents[1] + + +def test_transport_ack_prefix_and_abort_are_observations_only(store, monkeypatch): + from ndc_vps import delivery + + class Writer: + kernel = 0 + closed = False + buffer = 0 + + def __init__(self): + self.transport = self + + def get_extra_info(self, _): + return self + + def setsockopt(self, *args): + pass + + def is_closing(self): + return self.closed + + def write(self, data): + self.kernel += len(data) + + def get_write_buffer_size(self): + return self.buffer + + def abort(self): + self.closed = True + self.kernel = self.buffer = 0 + + async def exercise(): + writer, first, second = Writer(), [], [] + monkeypatch.setattr(delivery, "queued_bytes", lambda _: writer.kernel) + guard = delivery.Delivery(writer) + guard.write(b"header") + guard.write(b"one", time.monotonic() + 1, lambda *x: first.append(x)) + guard.write(b"two", time.monotonic() + 1, lambda *x: second.append(x)) + writer.kernel = 3 # Only the later command is still unacknowledged. + guard.check() + assert [x[0] for x in first] == ["written", "tcp_acknowledged"] + assert [x[0] for x in second] == ["written"] + guard.abort() + guard.abort() + assert [x[0] for x in second] == ["written", "unconfirmed"] + assert second[-1][3] == "connection_closed" + assert first[-1][2] >= 0 + + for queued in (None, 3): + writer, observed = Writer(), [] + monkeypatch.setattr(delivery, "queued_bytes", lambda _, q=queued: q) + guard = delivery.Delivery(writer) + guard.write(b"cmd", time.monotonic() + 0.01, lambda *x, log=observed: log.append(x)) + await asyncio.sleep(0.03) + assert [x[0] for x in observed] == ["written", "unconfirmed"] + assert observed[-1][3] == "delivery_deadline" + + writer, observed = Writer(), [] + guard = delivery.Delivery(writer) + with pytest.raises(TimeoutError): + guard.write(b"cmd", time.monotonic() - 1, lambda *x: observed.append(x)) + assert [x[0] for x in observed] == ["unconfirmed"] + assert observed[0][3] == "expired_before_write" + + asyncio.run(exercise()) + + +def test_transport_journal_survives_crash_without_promoting_command(store): + from ndc_vps.commands import Commands + + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + commands = Commands(store) + commands.sessions[imei] = {"private-session"} + request = dict(id="a" * 32, imei=imei, kind="request-position", model=231, firmware="0.01") + commands.submit(request) + _, _, ticket = commands.take_delivery(imei, "private-session", with_receipt=True) + assert commands.get(request["id"])["transport"][0]["state"] == "prepared" + now = time.time() + commands.transport.record([(ticket, "written", now, 0, None)]) + assert commands.get(request["id"])["state"] == "dispatched" + commands.transport.record([(ticket, "tcp_acknowledged", now + .5, .5, None)]) + value = commands.get(request["id"]) + assert value["state"] == "dispatched" # Not proof of B2 execution. + assert value["transport"][0]["tcp_ack_seconds"] == .5 + assert commands.submit(request) == value # Lost API response reuses the same facts. + assert "private-session" not in json.dumps(value["transport"]) + # A late close cannot erase an observed ACK; restart preserves it. + commands.transport.record([(ticket, "unconfirmed", now + 1, 1, "connection_closed")]) + commands = Commands(store) + assert commands.get(request["id"])["transport"][0]["state"] == "tcp_acknowledged" + assert commands.get(request["id"])["state"] == "uncertain" + + request["id"] = "b" * 32 + commands.sessions[imei] = {"new-session"} + commands.submit(request) + _, _, ticket = commands.take_delivery(imei, "new-session", with_receipt=True) + commands.transport.record([(ticket, "written", now + 2, 0, None)]) + commands = Commands(store) + value = commands.get(request["id"]) + assert value["transport"][0]["state"] == "unconfirmed" + assert value["transport"][0]["reason"] == "host_restarted" + assert commands.take_delivery(imei, "new-session", with_receipt=True) is None + + +def test_transport_observations_commit_when_socket_cancels_sender(store, monkeypatch): + from ndc_vps.service import Service + + async def exercise(): + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + service = Service(store) + service.commands.sessions[imei] = {"live"} + service.commands.session_activity[imei, "live"] = time.monotonic() + request = dict(id="a" * 32, imei=imei, kind="request-position", model=231, firmware="0.01") + service.commands.submit(request) + entered, resume = asyncio.Event(), asyncio.Event() + original = asyncio.to_thread + + async def controlled(function, *args, **kwargs): + if function == service.commands.transport.record: + entered.set() + await resume.wait() + return await original(function, *args, **kwargs) + + monkeypatch.setattr(asyncio, "to_thread", controlled) + + class Writer: + def is_closing(self): + return False + + async def drain(self): + pass + + class Delivery: + observer = None + + def ready(self): + return True + + def write(self, data, deadline, observe): + self.observer = observe + observe("written", time.time(), 0, None) + + def abort(self): + if self.observer: + self.observer("unconfirmed", time.time(), .1, "connection_closed") + self.observer = None + + sender = asyncio.create_task(service.send_commands(imei, Writer(), "live", Delivery())) + await asyncio.wait_for(entered.wait(), 2) + sender.cancel() + await asyncio.sleep(0) + resume.set() + await asyncio.gather(sender, return_exceptions=True) + observed = service.commands.get(request["id"])["transport"] + assert len(observed) == 1 + assert observed[0]["written_at"] <= observed[0]["closed_at"] + assert observed[0]["state"] == "unconfirmed" + assert observed[0]["reason"] == "connection_closed" + + asyncio.run(exercise()) + + +def test_diagnostic_probe_needs_live_exclusive_observation_and_never_replays(store): + from ndc_vps import actions + from ndc_vps.commands import Commands + from ndc_vps.observation import Observation + + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + commands = Commands(store) + commands.sessions[imei] = {"original"} + request = { + "id": "a" * 32, "imei": imei, "model": 231, "firmware": "0.01", + "kind": "probe-diagnostic-mode", "observation_id": "b" * 32, + } + with pytest.raises(ValueError, match="observation"): + actions.prepare({k: v for k, v in request.items() if k != "observation_id"}) + with pytest.raises(ValueError, match="unknown action fields"): + actions.prepare({**request, "binary": "0107"}) + with pytest.raises(ValueError, match="observation unavailable"): + commands.submit(request) + observation = Observation(store) + observation.arm({"id": request["observation_id"]}) + commands.submit(request) + # Closing an armed window before dispatch prevents any device command. + observation.close(request["observation_id"]) + assert commands.take(imei, "original") is None + assert commands.get(request["id"])["state"] == "expired" + + request = {**request, "id": "d" * 32, "observation_id": "e" * 32} + observation.arm({"id": request["observation_id"]}) + commands.submit(request) + wire = commands.take(imei, "original") + assert wire[:3] == bytes.fromhex("7b07ff") + assert wire[4] == 0xff and wire[9:] == bytes.fromhex("01007d") + assert wire[3] == sum(wire[4:-1]) % 256 + assert commands.take(imei, "original") is None + assert "diagnostic_imei" not in observation.get(request["observation_id"]) + # Same request ID is a lookup, even after a restart; no second toggle. + commands = Commands(store) + commands.sessions[imei] = {"reconnected"} + assert commands.submit(request)["state"] == "uncertain" + assert commands.take(imei, "reconnected") is None + with pytest.raises(ValueError, match="observation already used"): + commands.submit({**request, "id": "f" * 32}) + + +def test_diagnostic_probe_expired_lease_and_changed_request_are_rejected(store, monkeypatch): + from ndc_vps import observation as module + from ndc_vps.commands import Commands + + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + commands = Commands(store) + commands.sessions[imei] = {"original"} + observer = module.Observation(store) + request = { + "id": "a" * 32, "imei": imei, "model": 231, "firmware": "0.01", + "kind": "probe-diagnostic-mode", "observation_id": "b" * 32, + } + lease = observer.arm({"id": request["observation_id"]}) + monkeypatch.setattr(module.time, "time", lambda: lease["expires_at"] + 1) + with pytest.raises(ValueError, match="observation unavailable"): + commands.submit(request) + + +def test_delivery_deadline_covers_kernel_and_asyncio_buffers(store, monkeypatch): + from ndc_vps import delivery + + class Socket: + def setsockopt(self, *args): + pass + + class Writer: + def __init__(self): + self.transport = self + self.data = [] + self.kernel = 0 + self.buffer = 0 + self.closed = False + + def get_extra_info(self, name): + return Socket() + + def write(self, data): + self.data.append(data) + self.kernel += len(data) + + def get_write_buffer_size(self): + return self.buffer + + def is_closing(self): + return self.closed + + def abort(self): + self.closed = True + self.buffer = self.kernel = 0 + + async def exercise(): + for kernel, buffer in ((12, 0), (0, 12), (5, 7)): + writer = Writer() + monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel) + guard = delivery.Delivery(writer) + guard.write(b"c" * 12, time.monotonic() + 0.03) + writer.kernel, writer.buffer = kernel, buffer + await asyncio.sleep(0.06) + assert writer.closed and writer.kernel == writer.buffer == 0 + + # An ACK for the command releases its deadline even with a newer ACK + # or command queued behind it. Later writes cannot extend its lifetime. + writer = Writer() + monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel) + guard = delivery.Delivery(writer) + guard.write(b"header") + guard.write(b"first", time.monotonic() + 0.03) + guard.write(b"second", time.monotonic() + 1) + writer.kernel = len(b"second") + guard.check() + await asyncio.sleep(0.06) + assert not writer.closed + guard.abort() + assert guard.timer is None + + writer = Writer() + monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel) + guard = delivery.Delivery(writer) + guard.write(b"first", time.monotonic() + 0.03) + guard.write(b"second", time.monotonic() + 1) + await asyncio.sleep(0.06) + assert writer.closed + + writer = Writer() + guard = delivery.Delivery(writer) + monkeypatch.setattr(delivery, "queued_bytes", lambda sock: writer.kernel) + assert guard.ready() + writer.buffer = 1 + assert not guard.ready() + writer.buffer, writer.kernel = 0, 1 + assert not guard.ready() + writer.kernel = 0 + assert guard.ready() + with pytest.raises(TimeoutError): + guard.write(b"expired", time.monotonic() - 1) + assert not writer.data and writer.closed + + asyncio.run(exercise()) + + +def test_transport_expiry_never_replays_or_claims_device_confirmation(store, monkeypatch): + from ndc_vps.commands import Commands + + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + commands = Commands(store) + commands.sessions[imei] = {"old"} + body = { + "id": "a" * 32, + "imei": imei, + "kind": "request-position", + "model": 231, + "firmware": "0.01", + } + queued = commands.submit(body) + data, deadline = commands.take_delivery(imei, "old") + assert data and 0 < deadline - time.monotonic() <= 30 + assert commands.get(body["id"])["state"] == "dispatched" + commands.sessions[imei] = {"new"} + assert commands.take_delivery(imei, "new") is None + monkeypatch.setattr(time, "time", lambda: queued["expires_at"] + 1) + assert commands.get(body["id"])["state"] == "unconfirmed" + assert commands.take_delivery(imei, "new") is None + assert commands.submit(body)["state"] == "unconfirmed" + recovered = Commands(store) + recovered.sessions[imei] = {"new"} + assert recovered.get(body["id"])["state"] == "unconfirmed" + assert recovered.take_delivery(imei, "new") is None + + +def package(timestamp=None, lat=55.1, lon=37.2): + tags = ( + b"\x03" + + struct.pack(" 0 + command.submit(body) + command.take(body["imei"], "live") + command.web_receive(wire(5, before.encode()), "192.0.2.1") + before_clock = command.get(body["id"]) + assert before_clock["stage"] == "write" and before_clock["state"] == "queued" + now[0] += 1 + assert command.web_receive(wire(7), "192.0.2.1") == time_reply(int(now[0])) != first + assert command.get(body["id"]) == before_clock + command.store.set_devices([]) + assert command.web_receive(wire(7), "192.0.2.1") is None + + +def test_core_admits_only_independently_observed_numeric_id(tmp_path, monkeypatch): + from k1link.fleet import vps_hosts + + hosts = VPSHosts(tmp_path, "core", None) + devices = [ + {"id": "a" * 32, "identity_key": "123456789012345", "observed": {"device_id": "74565"}}, + {"id": "b" * 32, "identity_key": "223456789012345", "observed": {}}, + ] + monkeypatch.setattr(hosts, "devices", lambda row: devices) + monkeypatch.setattr(hosts, "ingest", lambda *args: 0) + monkeypatch.setattr(hosts, "save", lambda row: None) + calls = [] + + def call(host, method, path, body=None): + calls.append((path, body)) + return {"items": []} + + monkeypatch.setattr(vps_hosts, "request", call) + hosts.sync({"cursor": 0}) + items = calls[0][1]["items"] + assert items[0]["device_id"] == 74565 + assert "device_id" not in items[1] + assert set(items[0]) == {"imei", "instance_id", "device_id"} + + +@pytest.mark.parametrize( + "readback_kind, expected_state", [("unchanged", "not_applied"), ("partial", "uncertain")] +) +def test_full_configuration_ignored_or_partial_write_is_never_success_or_replayed( + full_context, readback_kind, expected_state +): + """A delivered image and SERV OK are insufficient when readback disagrees. + + The bench accepted the trajectory control but returned the old image for + polling-interval changes. Preserve this failure contract without a real + configuration, identity, credential or invented device reply fixture. + """ + from ndc_vps.commands import Commands + from ndc_vps.usb_protocol import Configuration, Setting + + command, body, before, target, wire, now = full_context + command.submit(body) + command.take(body["imei"], "live") + command.web_receive(wire(5, before.encode()), "192.0.2.1") + now[0] += 16 + command.take(body["imei"], "live") + delivered = command.web_receive(wire(2), "192.0.2.1") + assert delivered is not None + command.receive(body["imei"], text_package("SERV OK", now[0]), "live") + assert command.get(body["id"])["state"] == "queued" + # Even a matching unsolicited upload before the independent read must not + # complete the write or turn its ACK into settings verification. + command.web_receive(wire(5, target.encode()), "192.0.2.1") + assert command.get(body["id"])["state"] == "queued" + now[0] += 16 + command.take(body["imei"], "live") + readback = before + if readback_kind == "partial": + readback = Configuration( + tuple( + Setting(r.number, b"different-unknown" if r.number == 222 else r.value) + for r in target.records + ) + ) + command.web_receive(wire(5, readback.encode()), "192.0.2.1") + receipt = command.get(body["id"]) + assert receipt["state"] == expected_state + assert receipt["configuration"] == readback.encode().hex() + assert receipt["configuration_sha256"] == hashlib.sha256(readback.encode()).hexdigest() + assert command.submit(body) == receipt # a lost-response retry is a read + assert command.web_receive(wire(2), "192.0.2.1") is None + assert command.take(body["imei"], "live") is None + # Neither a later uncorrelated upload nor a service restart changes the + # recorded outcome, and neither can replay the original settings image. + command.web_receive(wire(5, target.encode()), "192.0.2.1") + assert command.get(body["id"]) == receipt + restarted = Commands(command.store) + assert restarted.get(body["id"]) == receipt + assert restarted.take(body["imei"], "live") is None + + +@pytest.fixture +def sim_context(full_context, monkeypatch): + from ndc_vps.usb_protocol import Configuration, Setting + + command, body, before, _, wire, now = full_context + monkeypatch.setattr("ndc_vps.commands.time.monotonic", lambda: now[0] - 1700000000) + before = Configuration(before.records + (Setting(72, (2072).to_bytes(4, "big")),)) + target = Configuration( + tuple( + Setting(r.number, (2072 | (1 << 10)).to_bytes(4, "big") if r.number == 72 else r.value) + for r in before.records + ) + ) + body.update( + kind="select-sim", + sim_slot=2, + expected_sha256=hashlib.sha256(before.encode()).hexdigest(), + target_configuration=target.encode().hex(), + ) + return command, body, before, target, wire, now + + +def reach_sim_restart(context, unchanged=False): + command, body, before, target, wire, now = context + if unchanged: + body["expected_sha256"] = hashlib.sha256(target.encode()).hexdigest() + before = target + command.submit(body) + command.session_activity[body["imei"], "live"] = time.monotonic() + command.take(body["imei"], "live") + command.web_receive(wire(5, before.encode()), "192.0.2.1") + if not unchanged: + now[0] += 16 + command.session_activity[body["imei"], "live"] = time.monotonic() + command.take(body["imei"], "live") + assert command.web_receive(wire(2), "192.0.2.1") + now[0] += 16 + command.session_activity[body["imei"], "live"] = time.monotonic() + command.take(body["imei"], "live") + command.web_receive(wire(5, target.encode()), "192.0.2.1") + assert command.get(body["id"])["state"] == "queued" + assert command.get(body["id"])["stage"] == "restart" + + +def sim_packet(timestamp, slot=2, gsm=4): + tags = bytes([99]) + ((gsm << 2) | ((slot - 1) << 5) | (1 << 6) | (1 << 9)).to_bytes( + 4, "little" + ) + data = int(timestamp).to_bytes(4, "little") + tags + return b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]" + + +@pytest.mark.parametrize("unchanged", [False, True]) +def test_sim_switch_only_completes_after_new_session_target_sim_gprs(sim_context, unchanged): + command, body, _, target, wire, now = sim_context + reach_sim_restart(sim_context, unchanged) + raw = command.take(body["imei"], "live") + assert raw[-3:-1] == b"\x01\x07" + assert command.take(body["imei"], "live") is None + command.web_receive(wire(5, target.encode()), "192.0.2.1") + assert command.get(body["id"])["state"] == "dispatched" + now[0] += 2 + command.session_started[body["imei"], "new"] = now[0] - 1700000000 + now[0] += 50 + command.receive(body["imei"], sim_packet(now[0]), "new") + result = command.get(body["id"]) + assert result["state"] == "sim_selected" and result["active_sim"] == 2 + assert result["reconnect_seconds"] == 52 + assert command.submit(body) == result + assert not {"binary", "token", "password", "restart_sessions"} & result.keys() + + +@pytest.mark.parametrize( + "mode", + [ + "old-session", + "early-session", + "no-session", + "archive", + "future", + "wrong-sim", + "no-gprs", + "no-ds2", + "late", + ], +) +def test_sim_switch_rejects_insufficient_telemetry(sim_context, mode): + command, body, _, _, _, now = sim_context + reach_sim_restart(sim_context) + command.take(body["imei"], "live") + dispatched = now[0] + now[0] += 20 + session = "live" if mode == "old-session" else "new" + if mode != "no-session": + command.session_started[body["imei"], session] = ( + dispatched - 1700000000 + (-1 if mode == "early-session" else 1) + ) + stamp = dispatched - 30 if mode == "archive" else now[0] + 60 if mode == "future" else now[0] + raw = sim_packet(stamp, slot=1 if mode == "wrong-sim" else 2, gsm=3 if mode == "no-gprs" else 4) + if mode == "no-ds2": + raw = package(timestamp=now[0]) + if mode == "late": + now[0] += 400 + command.receive(body["imei"], raw, session) + assert command.get(body["id"])["state"] == ("uncertain" if mode == "late" else "dispatched") + + +@pytest.mark.parametrize("dispatch", [False, True]) +def test_sim_switch_service_restart_never_replays_modem_restart(sim_context, dispatch): + from ndc_vps.commands import Commands + + command, body, _, _, _, _ = sim_context + reach_sim_restart(sim_context) + if dispatch: + command.take(body["imei"], "live") + restored = Commands(command.store) + assert restored.get(body["id"])["state"] == "uncertain" + assert restored.take(body["imei"], "live") is None + + +@pytest.mark.parametrize("slot", [True, 0, 3, "2", 1]) +def test_sim_selection_rejects_invalid_slot_and_disagreeing_flags(sim_context, slot): + command, body, *_ = sim_context + with pytest.raises(ValueError): + command.submit({**body, "sim_slot": slot}) + + +def test_offline_read_waits_across_host_restart_but_never_replays_after_dispatch( + store, monkeypatch +): + from ndc_vps.commands import Commands + + now = [1800000000.0] + monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0]) + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + body = { + "id": "e" * 32, + "imei": imei, + "kind": "request-position", + "model": 231, + "firmware": "0.01", + "not_after": now[0] + 25, + } + command = Commands(store) + accepted = command.submit(body) + assert accepted["state"] == "queued" + assert command.take(imei, "unregistered") is None + now[0] += 6 + command = Commands(store) + assert command.get(body["id"])["state"] == "queued" + command.sessions[imei] = {"reconnected"} + assert command.submit(body)["expires_at"] == accepted["expires_at"] + assert command.take(imei, "reconnected") is not None + command = Commands(store) + command.sessions[imei] = {"again"} + assert command.submit(body)["state"] == "uncertain" + assert command.take(imei, "again") is None + assert command.wait_delay(imei) is None + + +def test_original_deadline_and_terminal_history_survive_duplicate_post(store, monkeypatch): + from ndc_vps.commands import Commands + + now = [1800000000.0] + monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0]) + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + command = Commands(store) + body = { + "id": "e" * 32, + "imei": imei, + "kind": "request-position", + "model": 231, + "firmware": "0.01", + "not_after": now[0] + 10, + } + command.submit(body) + now[0] += 11 + command.sessions[imei] = {"late"} + assert command.submit(body)["state"] == "expired" + assert command.take(imei, "late") is None + assert Commands(store).get(body["id"])["state"] == "expired" + with pytest.raises(ValueError, match="idempotency"): + command.submit({**body, "not_after": now[0] + 10}) + # A request whose initial HTTP delivery itself was delayed is recorded, + # but must never execute even if the tracker is online on arrival. + assert command.submit({**body, "id": "f" * 32})["state"] == "expired" + assert command.take(imei, "late") is None + assert command.wait_delay(imei) is None + + +def test_effectful_action_cannot_cross_its_original_request_deadline(store, monkeypatch): + from ndc_vps.commands import Commands + + now = [1800000000.0] + monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0]) + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + command = Commands(store) + command.sessions[imei] = {"present"} + body = { + "id": "e" * 32, + "imei": imei, + "kind": "pulse-output", + "model": 231, + "firmware": "0.01", + "pin": 4, + "seconds": 1, + "not_after": now[0] + 1, + } + command.submit(body) + now[0] += 2 + assert command.take(imei, "present") is None + assert command.submit(body)["state"] == "expired" + with pytest.raises(ValueError): + command.submit({**body, "id": "f" * 32, "not_after": float("nan")}) + + +def test_idle_sender_wakes_on_command_without_periodic_history_poll(store, monkeypatch): + from ndc_vps.service import Service + + imei = "123456789012345" + store.set_devices([{"imei": imei, "instance_id": "c" * 32}]) + + async def exercise(): + service = Service(store) + service.commands.sessions[imei] = {"present"} + service.commands.session_activity[imei, "present"] = time.monotonic() - 20 + original = service.commands.take_delivery + checks = [] + writes = [] + written = asyncio.Event() + available = [False] + + def take(*args, **kwargs): + checks.append(time.monotonic()) + return original(*args, **kwargs) + + monkeypatch.setattr(service.commands, "take_delivery", take) + + class Writer: + def is_closing(self): + return False + + async def drain(self): + pass + + class Delivery: + def ready(self): + return available[0] + + def write(self, data, deadline, observe=None): + writes.append(data) + written.set() + + def abort(self): + pass + + task = asyncio.create_task(service.send_commands(imei, Writer(), "present", Delivery())) + try: + await asyncio.sleep(1.1) + assert len(checks) == 1 + service.commands.submit( + { + "id": "a" * 32, + "imei": imei, + "kind": "request-position", + "model": 231, + "firmware": "0.01", + } + ) + service.notify(imei) + await asyncio.sleep(0.03) + assert not written.is_set() + available[0] = True + service.notify(imei) + await asyncio.sleep(0.03) + assert not written.is_set() # A drained stale stream is insufficient. + service.commands.session_activity[imei, "present"] = time.monotonic() + service.notify(imei) + await asyncio.wait_for(written.wait(), 1) + assert len(writes) == 1 + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert not service.wake + + asyncio.run(exercise()) diff --git a/tests/test_vps_installer_permissions.py b/tests/test_vps_installer_permissions.py new file mode 100644 index 00000000..5a3b8290 --- /dev/null +++ b/tests/test_vps_installer_permissions.py @@ -0,0 +1,60 @@ +"""The service account must traverse installer code under a restrictive umask.""" + +import importlib.util +import json +import os +import sys +from pathlib import Path +from types import SimpleNamespace + + +def test_clean_install_under_private_umask_keeps_code_accessible(tmp_path, monkeypatch): + source = Path(__file__).resolve().parents[1] / "apps/vps-host" + monkeypatch.syspath_prepend(str(source)) + spec = importlib.util.spec_from_file_location("vps_install_permissions", source / "install.py") + installer = importlib.util.module_from_spec(spec) + spec.loader.exec_module(installer) + root, state, unit = tmp_path / "product", tmp_path / "state", tmp_path / "service" + payload = tmp_path / "payload" + payload.mkdir() + (payload / "entry.py").write_text("# synthetic service payload\n") + for name, value in (("ROOT", root), ("STATE", state), ("UNIT", unit), ("SOURCE", payload)): + monkeypatch.setattr(installer, name, value) + # A clean install's credential generation is not relevant to access modes. + monkeypatch.setattr(installer.pwd, "getpwnam", lambda _: SimpleNamespace(pw_uid=1, pw_gid=1)) + monkeypatch.setattr(installer.os, "chown", lambda *args: None) + monkeypatch.setattr(installer.ssl, "PEM_cert_to_DER_cert", lambda _: b"test cert") + monkeypatch.setattr(installer.firewall, "apply", lambda *args: False) + monkeypatch.setattr(installer, "healthy", lambda: None) + + def run(*args, **kwargs): + if args[0] == "openssl": + (state / "tls.key").write_text("private test key") + (state / "tls.crt").write_text("test certificate") + if args[0] == "runuser": + for directory in (root, root / "releases", kwargs["cwd"]): + assert directory.stat().st_mode & 0o777 == 0o755 + assert state.stat().st_mode & 0o777 == 0o700 + assert (state / "tls.key").stat().st_mode & 0o777 == 0o600 + (state / "connect.key").write_text("test invitation") + + monkeypatch.setattr(installer, "run", run) + monkeypatch.setattr(installer.os, "geteuid", lambda: 0) + proposal = { + "previous": None, + "plan_sha256": "plan", + "artifact": "release", + "configuration": {"public_host": "test.example", "api_port": 19443}, + "firewall": {"mode": "external"}, + } + previous = os.umask(0o077) + try: + installer.apply( + SimpleNamespace(expect="plan", host="test.example", api_port=19443, tracker_port=9922), + proposal, + ) + finally: + os.umask(previous) + sys.modules.pop("firewall", None) + assert json.loads((root / "installed.json").read_text())["status"] == "healthy" + assert (root / "installed.json").stat().st_mode & 0o777 == 0o600 diff --git a/tests/test_vps_operations.py b/tests/test_vps_operations.py new file mode 100644 index 00000000..da3772fd --- /dev/null +++ b/tests/test_vps_operations.py @@ -0,0 +1,379 @@ +"""Persistent maintenance intent recovery, isolated per tracker, no output actions.""" + +import json +import struct +import time + +import pytest +from test_vps_host import full_context, store # noqa: F401 + + +@pytest.fixture +def runtime(store, monkeypatch): # noqa: F811 + from ndc_vps.commands import Commands + from ndc_vps.operations import Operations + + now = [1800000000.0] + monkeypatch.setattr(time, "time", lambda: now[0]) + monkeypatch.setattr(time, "monotonic", lambda: now[0] - 1700000000) + body = { + "id": "a" * 32, + "imei": "123456789012345", + "kind": "request-position", + "model": 231, + "firmware": "0.01", + } + store.set_devices([{"imei": body["imei"], "instance_id": "c" * 32}]) + return Operations(store, Commands(store)), body, now + + +def connect(ops, body, session="live"): + ops.commands.sessions[body["imei"]] = {session} + ops.commands.session_activity[body["imei"], session] = time.monotonic() + ops.commands.session_started[body["imei"], session] = time.monotonic() + + +def reply(ops, body, raw, code=0): + payload = struct.pack("