feat(fleet): integrate independent trackers, VPS pairing and recoverable commands

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:44:12 +03:00
parent d684eb7e05
commit f3a7592d90
45 changed files with 10006 additions and 0 deletions
+23
View File
@@ -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()
+65
View File
@@ -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()
+46
View File
@@ -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)},
}
+65
View File
@@ -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)
@@ -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
@@ -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<? "
"ORDER BY seq DESC LIMIT ?",
(identifier, before or 2**63 - 1, limit + 1),
).fetchall()
counts = dict(
db.execute(
"SELECT state,count(*) FROM command_journal WHERE instance=? GROUP BY state",
(identifier,),
)
)
# Keep every in-flight row visible even outside the current history page.
# Also return final outcomes for IDs that the caller last saw in flight.
tracked = tuple(tracked[:32])
placeholders = ",".join("?" for _ in tracked) or "NULL"
tracked_rows = db.execute(
"SELECT seq,body FROM command_journal WHERE instance=? AND "
"(state IN ('waiting','submitting','queued','dispatched') "
"OR id IN (SELECT id FROM command_result_probes WHERE instance=? "
"ORDER BY rowid DESC LIMIT 32) "
f"OR id IN ({placeholders})) ORDER BY seq DESC",
(identifier, identifier, *tracked),
).fetchall()
return {
"items": [{**public(json.loads(body)), "sequence": seq} for seq, body in rows[:limit]],
"tracked_items": [
{**public(json.loads(body)), "sequence": seq} for seq, body in tracked_rows
],
"next_before": rows[limit - 1][0] if len(rows) > limit else None,
"counts": counts,
}
@@ -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
@@ -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
@@ -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
@@ -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
+132
View File
@@ -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()
+902
View File
@@ -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)
+107
View File
@@ -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"),
}
+51
View File
@@ -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)
+285
View File
@@ -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()
+9
View File
@@ -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:
+467
View File
@@ -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
+150
View File
@@ -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()
+9
View File
@@ -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)
+74
View File
@@ -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"],
},
)
+258
View File
@@ -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))
@@ -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})
+69
View File
@@ -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"},
)
+108
View File
@@ -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
),
)
+160
View File
@@ -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
+161
View File
@@ -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("<I", at) + tags
return (
b"[\x01\x01" + struct.pack("<H", len(tags)) + payload + bytes([sum(payload) % 256]) + b"]"
)
def status(active=2, first=1, second=5):
return b"\x63" + struct.pack("<I", 3 | 4 << 2 | (active - 1) << 5 | first << 6 | second << 9)
def network(tag=8, mcc=250, mnc=2, signal=20):
return bytes([tag, mnc]) + struct.pack("<H", mcc) + bytes([signal])
def test_decode_two_sims_active_channel_and_unknown_network_without_gnss():
raw = package(1790000000, status() + network() + network(201, 0, 1, 99))
consumed, packets = parse_telemetry_package(raw)
assert consumed == len(raw) and packets[0]["position"] is None
cell = packets[0]["cellular"]
assert cell["status"] == {"gsm_state": 4, "active_sim": 2, "sim_states": {"1": 1, "2": 5}}
assert cell["networks"] == {
"1": {"mcc": 250, "mnc": 2, "signal": 20},
"2": {"mcc": None, "mnc": 1, "signal": None},
}
assert "apn" not in str(cell) and "iccid" not in str(cell)
for cut in range(len(raw)):
assert parse_telemetry_package(raw[:cut]) is None
with pytest.raises(ValueError, match="checksum"):
parse_telemetry_package(raw[:-2] + bytes([raw[-2] ^ 1]) + raw[-1:])
def test_conflicting_scalars_absence_and_legitimate_zero_are_distinct():
raw = package(1790000000, status() + status(active=1) + network(signal=0) * 2)
cell = parse_telemetry_package(raw)[1][0]["cellular"]
assert "status" not in cell and cell["networks"]["1"]["signal"] == 0
packet = parse_telemetry_package(package(1790000000, network() + network(mnc=1)))[1][0]
assert "cellular" not in packet
assert "cellular" not in parse_telemetry_package(package(1790000000, b"\x01\0\0\0\0"))[1][0]
def test_component_order_missing_tags_host_scope_and_cursor_rollback(tmp_path):
now = int(time.time())
class Equipment:
vehicle = "rover-a"
def listing(self, vehicle=None):
return [{"id": "b2", "name": "Synthetic", "vehicle_id": self.vehicle}]
eq = Equipment()
hosts = VPSHosts(tmp_path, "core", eq)
host = {
"id": "host",
"cursor": 0,
"state": "paired",
"last_sync_at": now,
"vehicle_ids": ["rover-a", "rover-b"],
}
hosts.save(host)
def item(seq, measured, tags, instance="b2"):
return {
"id": seq,
"received_at": now,
"instance_id": instance,
"raw": base64.b64encode(package(measured, tags)).decode(),
}
hosts.ingest(
host,
[
item(1, now - 20, status() + network() + network(201, mnc=1)),
item(2, now, network(signal=25)),
item(3, now - 100, status(active=1) + network(signal=0)),
item(4, now + 400, status(active=1)),
item(5, now, status(active=1), "other"),
],
[{"id": "b2"}],
)
cell = hosts.telemetry()[0]["cellular"]
assert cell["status"]["active_sim"] == 2
assert cell["status"]["measured_at"] == now - 20
assert cell["networks"]["1"]["signal"] == 25
assert cell["networks"]["2"]["measured_at"] == now - 20
with pytest.raises(ValueError):
hosts.ingest(
host,
[item(6, now + 1, status(active=1)), {**item(7, now, status()), "raw": "!!"}],
[{"id": "b2"}],
)
assert hosts.rows()[0]["cursor"] == 5
assert hosts.telemetry()[0]["cellular"] == cell
eq.vehicle = "rover-b"
assert hosts.telemetry()[0]["cellular"] == cell
eq.vehicle = "outside"
assert hosts.telemetry()[0]["cellular"] is None
eq.vehicle = "rover-a"
host["state"] = "replaced"
hosts.save(host)
assert hosts.telemetry()[0]["cellular"] is None
# A newly assigned host never borrows a previous host's modem/SIM report.
replacement = {**host, "id": "new-host", "state": "paired", "cursor": 0}
hosts.save(replacement)
hosts.ingest(replacement, [item(1, now, network(201, mnc=99))], [{"id": "b2"}])
cell = hosts.telemetry()[0]["cellular"]
assert cell["host_id"] == "new-host" and "status" not in cell
assert set(cell["networks"]) == {"2"}
def test_removal_and_reinsertion_invalidate_prior_operator_even_when_old_packets_arrive(tmp_path):
now = int(time.time())
class Equipment:
def listing(self, vehicle=None):
return [{"id": "b2", "name": "Synthetic", "vehicle_id": "rover"}]
hosts = VPSHosts(tmp_path, "core", Equipment())
host = {
"id": "host",
"cursor": 0,
"state": "paired",
"last_sync_at": now,
"vehicle_ids": ["rover"],
}
hosts.save(host)
def ingest(seq, at, tags):
hosts.ingest(
host,
[
{
"id": seq,
"received_at": now,
"instance_id": "b2",
"raw": base64.b64encode(package(at, tags)).decode(),
}
],
[{"id": "b2"}],
)
return hosts.telemetry()[0]["cellular"]
assert ingest(1, now - 4, status(second=1) + network(201, mnc=1))["networks"]["2"]["mnc"] == 1
assert "2" not in ingest(2, now - 3, status(second=0) + network(201, mnc=1))["networks"]
assert "2" not in ingest(3, now - 2, status(second=1))["networks"]
assert "2" not in ingest(4, now - 4, network(201, mnc=1))["networks"]
assert ingest(5, now - 1, network(201, mnc=99))["networks"]["2"]["mnc"] == 99
assert "2" not in ingest(6, now, status(second=2))["networks"]
+131
View File
@@ -0,0 +1,131 @@
"""Both-SIM permission is not a promise of priority or automatic failover."""
import hashlib
import json
import pytest
from test_equipment_network import context, full_core_context # noqa: F401
from test_vps_host import ( # noqa: F401
full_context,
reach_sim_restart,
sim_context,
sim_packet,
store,
)
from k1link.device_plugins.arnavi_b2 import profiles
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
from k1link.fleet import equipment_network as network
from k1link.fleet.independent_equipment import EquipmentError
@pytest.mark.parametrize("flags", [0, 1 << 10, 1 << 20, (1 << 10) | (1 << 20)])
def test_both_permission_preserves_apns_passwords_and_other_flags(flags):
before = Configuration(
(
Setting(72, (flags | 2072).to_bytes(4, "big")),
Setting(67, b"private.one"),
Setting(89, b"private.two"),
Setting(90, b"user"),
Setting(91, b"synthetic"),
)
)
after = profiles.prepare(before, {"connectivity": {"strategy": "both"}})
assert after.integer(72, 4) == 2072
assert after.records[1:] == before.records[1:]
with pytest.raises(ValueError):
profiles.Policy(connectivity={"strategy": "both", "apn": "conflict"})
def both_context(source):
command, body, before, target, wire, now = source
# Existing exclusive target becomes the predecessor; remove its prohibition.
body.pop("sim_slot")
body.update(
sim_policy="both",
expected_sha256=hashlib.sha256(target.encode()).hexdigest(),
target_configuration=before.encode().hex(),
)
return command, body, target, before, wire, now
@pytest.mark.parametrize("slot", [1, 2])
def test_both_requires_readback_then_fresh_gprs_on_new_session(sim_context, slot): # noqa: F811
command, body, before, target, wire, now = both_context(sim_context)
reach_sim_restart((command, body, before, target, wire, now))
assert command.take(body["imei"], "live")[-3:-1] == b"\x01\x07"
now[0] += 10
command.receive(body["imei"], sim_packet(now[0], slot=slot), "live")
assert command.get(body["id"])["state"] == "dispatched"
command.session_started[body["imei"], "new"] = now[0] - 1700000000
now[0] += 1
command.receive(body["imei"], sim_packet(now[0], slot=slot, gsm=3), "new")
assert command.get(body["id"])["state"] == "dispatched"
command.receive(body["imei"], sim_packet(now[0], slot=slot), "new")
result = command.get(body["id"])
assert result["state"] == "sim_selected" and result["active_sim"] == slot
assert result["sim_policy"] == "both"
@pytest.mark.parametrize("bad", ["slot", "flags", "policy"])
def test_vps_rejects_contradictory_both_request(sim_context, bad): # noqa: F811
command, body, before, _, _, _ = both_context(sim_context)
if bad == "slot":
body["sim_slot"] = 1
elif bad == "flags":
body["target_configuration"] = before.encode().hex()
else:
body["sim_policy"] = "preferred"
with pytest.raises(ValueError):
command.submit(body)
@pytest.mark.parametrize("slot", [1, 2])
def test_core_both_receipt_accepts_either_real_slot_and_no_configuration_only_success(
full_core_context, # noqa: F811
monkeypatch,
slot,
):
equipment, hosts, row, config = full_core_context
row["settings"]["connectivity"] = {"strategy": "both"}
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.37"
hosts.save(host)
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "queued", "durable": True}
monkeypatch.setattr(network, "request", send)
op = network.start(hosts, row["id"], 1, select_sim=True)["network_operation"]
assert op["sim_policy"] == sent[0]["sim_policy"] == "both"
assert "sim_slot" not in sent[0]
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)
for invalid in (0, 3, True):
with pytest.raises(ValueError, match="mismatch"):
network.record(
hosts,
row["id"],
op["id"],
{**receipt, "state": "sim_selected", "active_sim": invalid},
)
network.record(
hosts, row["id"], op["id"], {**receipt, "state": "sim_selected", "active_sim": slot}
)
assert equipment.listing()[0]["network_operation"]["active_sim"] == slot
def test_core_both_is_explicit_and_requires_compatible_vps(full_core_context): # noqa: F811
equipment, hosts, row, _ = full_core_context
row["settings"]["connectivity"] = {"strategy": "both"}
assert network.plan(equipment, row, full=True)["kind"] == "configure-all"
assert network.plan(equipment, row, full=True, select_sim=True)["kind"] == "select-sim"
with equipment.db() as db:
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"]))
with pytest.raises(EquipmentError, match="обеих SIM"):
network.start(hosts, row["id"], 1, select_sim=True)
+78
View File
@@ -0,0 +1,78 @@
"""The native access policy must not inherit slot-specific operator credentials."""
from pathlib import Path
import pytest
from test_equipment_network import context, full_core_context # noqa: F401
from k1link.device_plugins.arnavi_b2 import profiles
from k1link.device_plugins.arnavi_b2.connectivity import SIM_FIELDS
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, ProtocolError, Setting
from k1link.fleet import equipment_network
ACCESS = {n for numbers in SIM_FIELDS.values() for n in numbers}
def with_access(config, *, empty=False):
retained = tuple(r for r in config.records if r.number not in ACCESS)
return Configuration(
retained + tuple(Setting(n, b"" if empty else b"private-access") for n in sorted(ACCESS))
)
@pytest.mark.parametrize("flags", [0, 1 << 10, 1 << 20, (1 << 10) | (1 << 20)])
def test_native_clears_all_six_access_fields_and_only_gprs_bans(flags):
before = with_access(
Configuration(
(
Setting(72, (flags | 2072).to_bytes(4, "big")),
Setting(5, b"synthetic"),
Setting(222, b"unknown"),
)
)
)
policy = profiles.Policy(connectivity={"strategy": "native"}).model_dump()
after = profiles.prepare(before, policy)
assert after.integer(72, 4) == 2072
assert all(after.text(n) == "" for n in ACCESS)
assert {r.number: r.value for r in after.records if r.number not in ACCESS | {72}} == {
r.number: r.value for r in before.records if r.number not in ACCESS | {72}
}
assert profiles.prepare(after, policy).encode() == after.encode()
# Merely reading a device never opts future devices into clearing their APNs.
assert profiles.portable(after)["connectivity"]["strategy"] == "preserve"
def test_native_rejects_missing_fields_and_conflicting_operator_values():
with pytest.raises(ProtocolError, match="required_setting_missing"):
profiles.prepare(
Configuration((Setting(72, bytes(4)),)), {"connectivity": {"strategy": "native"}}
)
for extra in (
{"apn": "iot"},
{"activate": True},
{"automatic": True},
{"preset_id": "ru-mts-public-v1"},
{"apn1": "iot"},
):
with pytest.raises(ValueError):
profiles.Policy(connectivity={"strategy": "native", **extra})
@pytest.mark.parametrize("empty", [False, True])
def test_network_verifies_new_gprs_but_does_not_restart_for_unrelated_edits(
full_core_context, # noqa: F811
empty,
):
equipment, _, row, config = full_core_context
config = with_access(config, empty=empty)
path: Path = equipment.root / "evidence" / row["evidence_id"] / "configuration.bin"
path.write_bytes(config.encode())
row["settings"]["connectivity"] = {"strategy": "native"}
body = equipment_network.plan(equipment, row, full=True)
assert body["kind"] == ("configure-all" if empty else "select-sim")
if not empty:
assert body["sim_policy"] == "both"
explicit = equipment_network.plan(equipment, row, full=True, select_sim=True)
assert explicit["kind"] == "select-sim" and explicit["sim_policy"] == "both"
assert "sim_slot" not in explicit and "sim_guard" not in explicit
+86
View File
@@ -0,0 +1,86 @@
"""Output observations do not require GNSS and never imply a physical contact."""
import base64
import struct
import time
import pytest
from k1link.device_plugins.arnavi_b2.internal import parse_package
from k1link.fleet.vps_hosts import VPSHosts
def packet(measured, mask=0x0021, extra=b""):
tags = b"\x06\x01\x00" + struct.pack("<H", mask) + extra
data = struct.pack("<I", measured) + tags
return b"[\x01\x01" + struct.pack("<H", len(tags)) + data + bytes([sum(data) % 256]) + b"]"
def test_repeated_tag6_modes_do_not_hide_discrete_states():
data = packet(int(time.time()), extra=b"\x06\x08\x03\x55\x21")
observation = parse_package(data)[1][0]
assert observation["position"] is None
assert observation["outputs"] == {"4": False, "5": True, "6": False}
for offset in range(len(data)):
assert parse_package(data[:offset]) is None
with pytest.raises(ValueError, match="checksum"):
parse_package(data[:-2] + bytes([data[-2] ^ 1]) + data[-1:])
def test_output_order_freshness_authority_and_transaction(tmp_path, monkeypatch):
now = int(time.time())
class Equipment:
vehicle = "rover-a"
def listing(self, vehicle=None):
return [{"id": "b2", "name": "Synthetic", "vehicle_id": self.vehicle}]
eq = Equipment()
hosts = VPSHosts(tmp_path, "core", eq)
host = {
"id": "host",
"cursor": 0,
"state": "paired",
"last_sync_at": now,
"vehicle_ids": ["rover-a", "rover-b"],
}
hosts.save(host)
def item(seq, measured, mask=0x21, instance="b2"):
return {
"id": seq,
"received_at": now,
"instance_id": instance,
"raw": base64.b64encode(packet(measured, mask)).decode(),
}
hosts.ingest(
host,
[
item(1, now),
item(2, now - 1000, 0),
item(3, now + 400, 0),
item(4, now, 0, "unadmitted"),
],
[{"id": "b2"}],
)
status = hosts.telemetry()[0]
assert status["online"] and status["outputs_fresh"] and status["position"] is None
assert status["outputs"]["pins"]["5"] is True
assert status["outputs"]["measured_at"] == now
with hosts.db() as db:
assert db.execute("SELECT count(*) FROM outputs").fetchone()[0] == 1
with pytest.raises(ValueError):
hosts.ingest(host, [item(5, now + 1, 0), {**item(6, now), "raw": "!!"}], [{"id": "b2"}])
assert hosts.rows()[0]["cursor"] == 4 and hosts.telemetry()[0]["outputs"]["pins"]["5"]
monkeypatch.setattr("k1link.fleet.vps_hosts.time.time", lambda: now + 100)
assert not hosts.telemetry()[0]["outputs_fresh"]
eq.vehicle = "rover-b"
assert hosts.telemetry()[0]["outputs"] is not None
eq.vehicle = "rover-other"
assert hosts.telemetry()[0]["outputs"] is None
eq.vehicle = "rover-a"
host["state"] = "replaced"
hosts.save(host)
assert hosts.telemetry()[0]["outputs"] is None
+254
View File
@@ -0,0 +1,254 @@
"""Synthetic SIMs only; regression cases derived from qualified B2 0.01 reads."""
import hashlib
import json
import uuid
from dataclasses import asdict, replace
from datetime import UTC, datetime, timedelta
import pytest
from k1link.device_plugins.arnavi_b2.enrollment import B2Enrollment
from k1link.device_plugins.arnavi_b2.sim_identity import (
capture_from_read,
modem_observations,
reported_state,
)
from k1link.device_plugins.arnavi_b2.sim_observation_store import (
SimObservationStore,
load_capture,
snapshot_details,
)
from k1link.device_plugins.arnavi_b2.usb_protocol import (
Configuration,
Identity,
ProtocolError,
Setting,
)
from k1link.fleet.independent_equipment import EquipmentStore
CARD_A = ("89000000000000000010", "89000000000000000010", "250010000000001", "25001")
CARD_B = ("890000000000000002ff", "89000000000000000273", "250020000000002", "25002")
SHORT = "100000000007"
IMEI = "000000000000001"
def exchange(slot, card):
raw, sid, imsi, home = card
return (
f"AT+CCID\r\r\n{raw}\r\n\r\nOK\r\n>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)
+218
View File
@@ -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("<I", int(sid[2:11]))
+ bytes([second])
+ struct.pack("<I", int(sid[11:]))
)
def packet(at=AT, raw=None):
return parse_telemetry_package(package(at, tags(1, CARD_A[1]) if raw is None else raw))[1][0]
def update(previous=None, at=AT, raw=None, host="host", sequence=1, received=None):
return merge(
previous,
packet(at, raw),
host_id=host,
sequence=sequence,
received=at if received is None else received,
tracker=IMEI,
)
def test_two_full_pairs_same_packet_and_no_partial_join_across_packets():
parsed = packet(raw=tags(1, CARD_A[1]) + tags(2, CARD_B[1]))
assert parsed["sim_identifiers"] == {
"1": {"state": "observed", "firmware_sid": CARD_A[1]},
"2": {"state": "observed", "firmware_sid": CARD_B[1]},
}
assert "cellular" not in parsed
first = update(raw=tags(1, CARD_A[1])[:5])
second = update(first, at=AT + 1, raw=tags(1, CARD_A[1])[5:])
assert second["slots"]["1"]["observation"]["state"] == "unresolved"
assert "firmware_sid" not in json.dumps(second)
@pytest.mark.parametrize(
"raw,state",
[
(tags(1, CARD_A[1]) + b"\xfd" + struct.pack("<I", 3), "unresolved"),
(b"\xfd" + struct.pack("<I", 1_000_000_000) + b"\xfe\0\0\0\1", "unresolved"),
(b"\xfd\0\0\0\0\xfe\0\0\0\0", "not_reported"),
(tags(1, CARD_A[1]) * 2, "observed"),
],
)
def test_unambiguous_parts_decimal_range_and_zero_are_distinct(raw, state):
assert packet(raw=raw)["sim_identifiers"]["1"]["state"] == state
def test_same_sid_both_slots_is_ambiguous():
parsed = packet(raw=tags(1, CARD_A[1]) + tags(2, CARD_A[1]))
assert parsed["sim_identifiers"] == {s: {"state": "unresolved"} for s in ("1", "2")}
def test_framing_and_checksum_gate_identity_projection():
raw = package(AT, tags(1, CARD_A[1]) + tags(2, CARD_B[1]))
for cut in range(len(raw)):
assert parse_telemetry_package(raw[:cut]) is None
with pytest.raises(ValueError, match="checksum"):
parse_telemetry_package(raw[:-2] + bytes([raw[-2] ^ 1]) + raw[-1:])
def test_out_of_order_conflict_missing_and_replaced_host_do_not_preserve_false_certainty(tmp_path):
value = update()
assert update(value, at=AT - 1, raw=tags(1, CARD_B[1])) == value
conflict = update(value, raw=tags(1, CARD_B[1]))
assert conflict["slots"]["1"]["observation"]["state"] == "unresolved"
assert "firmware_sid" not in json.dumps(conflict)
assert update(conflict)["slots"]["1"]["observation"]["state"] == "unresolved"
repaired = update(conflict, at=AT + 1)
assert repaired["slots"]["1"]["observation"]["state"] == "observed"
assert (
update(repaired, at=AT + 2, raw=status())["slots"]["1"]["observation"]
== repaired["slots"]["1"]["observation"]
)
assert update(repaired, at=AT + 301, received=AT) == repaired
replaced = update(repaired, at=AT + 2, host="new", raw=status())
assert public(replaced, SimObservationStore(tmp_path), now=AT + 2)["slots"] == {}
def test_removal_search_and_reinsertion_invalidate_even_delayed_identifiers(tmp_path):
store = SimObservationStore(tmp_path)
value = update(raw=tags(1, CARD_A[1]) + status(first=1))
assert public(value, store, now=AT)["slots"]["1"]["observation_fresh"]
value = update(value, at=AT + 1, raw=status(first=0))
value = update(value, at=AT + 2, raw=status(first=1))
value = update(value, at=AT + 1, raw=tags(1, CARD_A[1]), received=AT + 3)
assert public(value, store, now=AT + 3)["slots"]["1"]["invalidated"]
value = update(value, at=AT + 4)
assert public(value, store, now=AT + 4)["slots"]["1"]["observation_fresh"]
value = update(value, at=AT + 5, raw=status(first=2))
assert public(value, store, now=AT + 5)["slots"]["1"]["invalidated"]
def test_alias_follows_card_not_slot_and_never_leaks_private_values(tmp_path):
store = SimObservationStore(tmp_path)
usb = store.record(capture(exchange(1, CARD_A) + exchange(2, CARD_B)))
swapped = update(raw=tags(1, CARD_B[1]) + tags(2, CARD_A[1]))
projected = public(swapped, store, now=AT)
first, second = projected["slots"]["1"], projected["slots"]["2"]
assert first["known_card"]["card_ref"] == usb["slots"][1]["captured_card_ref"]
assert first["known_card"]["home_network"] == "25002"
assert second["known_card"]["card_ref"] == usb["slots"][0]["captured_card_ref"]
assert second["known_card"]["home_network"] == "25001"
assert projected["automatic_write_authorized"] is False
assert store.resolve_firmware_sid("other", CARD_A[1]) is None
for secret in (*CARD_A[:3], *CARD_B[:3], IMEI):
assert secret not in json.dumps(projected)
# A new raw card using an existing firmware alias makes that alias ambiguous.
collision = ("89000000000000000099", CARD_A[1], "250020000000099", "25002")
store.record(capture(exchange(1, collision), second=10))
assert store.resolve_firmware_sid(IMEI, CARD_A[1]) is None
assert store.resolve_firmware_sid(IMEI, CARD_B[1]) is not None
def test_short_i7_and_unknown_alias_never_establish_home_operator(tmp_path):
store = SimObservationStore(tmp_path)
store.record(capture())
assert public(update(), store, now=AT)["slots"]["1"]["known_card"] is None
def test_cross_packet_duplicate_sid_cannot_assign_one_known_card_to_both_slots(tmp_path):
store = SimObservationStore(tmp_path)
store.record(capture(exchange(1, CARD_A) + exchange(2, CARD_B)))
value = update(raw=tags(1, CARD_A[1]) + tags(2, CARD_B[1]))
value = update(value, at=AT + 1, raw=tags(2, CARD_A[1]))
projected = public(value, store, now=AT + 1)
for slot in projected["slots"].values():
assert slot["ambiguous_slot_binding"]
assert slot["known_card"] is None and not slot["observation_fresh"]
# The other half of the swap completes the pair, resolving the ambiguity.
value = update(value, at=AT + 2, raw=tags(1, CARD_B[1]))
assert public(value, store, now=AT + 2)["slots"]["1"]["known_card"]["home_network"] == "25002"
def test_old_buffered_or_future_observation_is_never_promoted_by_receipt_or_restart(tmp_path):
store = SimObservationStore(tmp_path)
value = update(received=AT + 1000)
slot = public(json.loads(json.dumps(value)), store, now=AT + 1000)["slots"]["1"]
assert slot["measured_at"] == AT and not slot["observation_fresh"]
assert not public(update(received=AT - 10), store, now=AT)["slots"]["1"]["observation_fresh"]
assert not public(update(), store, now=AT + 100)["slots"]["1"]["observation_fresh"]
def test_durable_atomic_ingestion_host_affinity_and_api_privacy(tmp_path):
now = int(time.time())
class Equipment:
vehicle = "rover"
def listing(self, vehicle=None):
return [{"id": "b2", "name": "Synthetic", "vehicle_id": self.vehicle}]
eq = Equipment()
hosts = VPSHosts(tmp_path, "core", eq)
host = {
"id": "host",
"cursor": 0,
"state": "paired",
"vehicle_ids": ["rover"],
"last_sync_at": now,
}
hosts.save(host)
devices = [{"id": "b2", "identity_key": IMEI}]
def item(seq, at, raw):
return {
"id": seq,
"received_at": now,
"instance_id": "b2",
"raw": base64.b64encode(package(at, raw)).decode(),
}
hosts.ingest(host, [item(1, now - 1, tags(1, CARD_A[1]) + tags(2, CARD_B[1]))], devices)
initial = hosts.telemetry()[0]["sim_identity"]
assert initial["slots"]["1"]["observation_fresh"]
assert CARD_A[1] not in json.dumps(hosts.telemetry())
assert initial["slots"]["1"]["known_card"] is None
with pytest.raises(ValueError):
hosts.ingest(
host,
[item(2, now, tags(1, CARD_B[1])), {**item(3, now, status()), "raw": "!"}],
devices,
)
assert hosts.rows()[0]["cursor"] == 1
assert hosts.telemetry()[0]["sim_identity"] == initial
assert VPSHosts(tmp_path, "core", eq).telemetry()[0]["sim_identity"] == initial
eq.vehicle = "outside"
assert hosts.telemetry()[0]["sim_identity"] is None
eq.vehicle = "rover"
new = {**host, "id": "new", "cursor": 0}
hosts.save(new)
hosts.ingest(new, [item(1, now, status())], devices)
assert hosts.telemetry()[0]["sim_identity"]["slots"] == {}
new["state"] = "replaced"
hosts.save(new)
assert hosts.telemetry()[0]["sim_identity"] is None
+81
View File
@@ -0,0 +1,81 @@
import time
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from k1link.fleet.equipment_bootstrap import apply
from k1link.fleet.independent_equipment import EquipmentError
def context():
item = {
"id": "device",
"revision": 1,
"vehicle_id": "rover",
"settings": {"endpoint": {"slot": 1, "host": "owner.example", "port": 9922}},
}
host = {
"state": "paired",
"vehicle_ids": ["rover"],
"status": {"version": "0.1.15", "tracker": {"host": "owner.example", "port": 9922}},
"last_sync_at": time.time(),
}
import threading
equipment = SimpleNamespace(
listing=lambda: [item], require_idle=Mock(), apply=Mock(return_value={"ok": True})
)
hosts = SimpleNamespace(
equipment=equipment, lock=threading.RLock(), rows=lambda: [host], sync=Mock()
)
return hosts, item, host
def test_initial_usb_apply_admits_the_device_to_paired_vps_before_write():
hosts, item, host = context()
hosts.equipment.apply.side_effect = lambda *args: (
hosts.sync.assert_called_once_with(host) or {"ok": True}
)
assert apply(hosts, "device", 1) == {"ok": True}
@pytest.mark.parametrize(
"case", ["stale", "wrong_vehicle", "not_paired", "old_host", "unqualified_host", "no_endpoint"]
)
def test_initial_usb_apply_rejects_unowned_or_incompatible_destination(case):
hosts, item, host = context()
if case == "stale":
item["revision"] = 2
if case == "wrong_vehicle":
host["vehicle_ids"] = []
if case == "not_paired":
host["state"] = "offline"
if case == "old_host":
host["status"]["version"] = "0.1.14"
if case == "unqualified_host":
host["status"]["version"] = "0.1.999"
if case == "no_endpoint":
item["settings"]["endpoint"] = None
with pytest.raises(EquipmentError):
apply(hosts, "device", 1)
hosts.equipment.apply.assert_not_called()
def test_initial_usb_apply_accepts_current_shipped_host():
import ast
from pathlib import Path
# Read the shipped artifact's version without importing its hardware service.
source = Path(__file__).resolve().parents[1] / "apps/vps-host/ndc_vps/__init__.py"
module = ast.parse(source.read_text())
version = 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)
)
hosts, _, host = context()
host["status"]["version"] = version
assert apply(hosts, "device", 1) == {"ok": True}
hosts.equipment.apply.assert_called_once_with("device", 1)
@@ -0,0 +1,114 @@
"""Late results survive Core restart without reissuing physical commands."""
# ruff: noqa: F811 -- imported pytest fixtures
import json
import time
import pytest
from test_equipment_command_runtime import ready, sender # 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 defer(ready, monkeypatch):
equipment, hosts, row = ready
sent = sender(monkeypatch)
op = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
runtime.pump(hosts)
now = [op["expires_at"] + 1]
monkeypatch.setattr(time, "time", lambda: now[0])
network.record(
hosts,
row["id"],
op["id"],
{
"id": op["id"],
"kind": "request-position",
"state": "uncertain",
},
reconcile=True,
)
host = next(h for h in hosts.rows() if h["id"] == "current")
return equipment, hosts, row, op, now, host, sent
@pytest.mark.parametrize("response", ["unavailable", "queued", "wrong_id", "wrong_kind"])
def test_invalid_or_pending_late_result_keeps_unknown_and_persistent_backoff(
ready, monkeypatch, response
):
equipment, hosts, row, op, now, host, sent = defer(ready, monkeypatch)
calls = []
def get_result(source, method, path, body=None):
calls.append((source["id"], method))
if response == "unavailable":
raise OSError("unavailable")
return {
"id": "another" if response == "wrong_id" else op["id"],
"kind": "restart" if response == "wrong_kind" else "request-position",
"state": "queued" if response == "queued" else "device_confirmed",
}
monkeypatch.setattr(network, "request", get_result)
network.refresh(hosts, host)
hosts.equipment = EquipmentStore(equipment.root.parent, {})
network.refresh(hosts, host)
assert calls == [("current", "GET")] and len(sent) == 1
item = journal.listing(hosts.equipment, row["id"])["items"][0]
assert item["state"] == "uncertain" and item["reconcile_pending"]
now[0] += 5
network.refresh(hosts, {**host, "state": "replaced"})
network.refresh(hosts, {**host, "id": "different-host"})
assert len(calls) == 1
network.refresh(hosts, host)
assert calls == [("current", "GET")] * 2
def test_old_result_is_in_tracked_page_until_authoritative_outcome(ready, monkeypatch):
equipment, hosts, row, op, _, host, _ = defer(ready, monkeypatch)
with equipment.db() as db:
for n in range(40):
journal.put(db, row["id"], {"id": f"later-{n}", "state": "expired"})
page = journal.listing(equipment, row["id"])
assert op["id"] not in {i["id"] for i in page["items"]}
assert [i["id"] for i in page["tracked_items"]] == [op["id"]]
monkeypatch.setattr(
network,
"request",
lambda *args: {
"id": op["id"],
"kind": "request-position",
"state": "unconfirmed",
},
)
network.refresh(hosts, host)
page = journal.listing(equipment, row["id"], tracked=[op["id"]])
assert page["tracked_items"][0]["state"] == "unconfirmed"
assert not page["tracked_items"][0]["reconcile_pending"]
with equipment.db() as db:
assert db.execute("SELECT count(*) FROM command_result_probes").fetchone()[0] == 0
assert "password" not in json.dumps(page)
def test_vps_terminal_uncertainty_does_not_start_endless_reconciliation(ready, monkeypatch):
equipment, hosts, row = ready
sender(monkeypatch)
op = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
runtime.pump(hosts)
network.record(
hosts,
row["id"],
op["id"],
{
"id": op["id"],
"kind": "request-position",
"state": "uncertain",
},
)
with equipment.db() as db:
assert db.execute("SELECT count(*) FROM command_result_probes").fetchone()[0] == 0
+398
View File
@@ -0,0 +1,398 @@
"""Durable runtime queue, original deadlines and redacted operator history."""
import json
import sqlite3
import time
from concurrent.futures import ThreadPoolExecutor
import pytest
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.equipment_command_catalog import catalog
from k1link.fleet.independent_equipment import EquipmentError, EquipmentStore
@pytest.fixture
def ready(context): # noqa: F811 - imported pytest fixture
equipment, hosts, row = context
for host in hosts.rows():
host["status"]["version"] = "0.1.26"
hosts.save(host)
return equipment, hosts, row
def sender(monkeypatch):
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {
"id": body["id"],
"kind": body["kind"],
"state": "queued",
"expires_at": body["not_after"],
}
monkeypatch.setattr(network, "request", send)
return sent
@pytest.mark.parametrize("version", ["0.1.26", "0.1.27", "0.1.28", "0.1.29", "0.1.30", "0.1.31"])
def test_queue_survives_restart_and_idempotent_submit(ready, monkeypatch, version):
equipment, hosts, row = ready
for host in hosts.rows():
host["status"]["version"] = version
hosts.save(host)
first = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
assert first["state"] == "waiting"
assert runtime.enqueue(hosts, row["id"], "1" * 32, "position") == first
with pytest.raises(EquipmentError, match="другой"):
runtime.enqueue(hosts, row["id"], "1" * 32, "restart")
hosts.equipment = EquipmentStore(equipment.root.parent, {})
sent = sender(monkeypatch)
runtime.pump(hosts)
runtime.pump(hosts)
assert len(sent) == 1 and sent[0]["id"] == first["id"]
assert sent[0]["not_after"] == first["expires_at"]
entries = journal.listing(hosts.equipment, row["id"])["items"]
assert len(entries) == 1
assert [event["state"] for event in entries[0]["events"]] == ["waiting", "submitting", "queued"]
def test_worker_survives_transient_database_failure(ready, monkeypatch):
_, hosts, _ = ready
ticks, waits = [], []
def tick(next_sync):
ticks.append(1)
if len(ticks) == 1:
raise sqlite3.OperationalError("database temporarily locked")
hosts.stop.set()
return False
monkeypatch.setattr(hosts, "_runtime_tick", tick)
monkeypatch.setattr(hosts.command_wake, "wait", waits.append)
hosts.run()
assert ticks == [1, 1] and waits == [5]
@pytest.mark.parametrize("superseded", [False, True])
def test_confirmed_vps_result_is_reconciled_after_core_deadline_and_restart(
ready, monkeypatch, superseded
):
equipment, hosts, row = ready
sent = sender(monkeypatch)
queued = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
runtime.pump(hosts)
now = queued["expires_at"] + 1
monkeypatch.setattr(time, "time", lambda: now)
def unavailable(*args, **kwargs):
raise OSError("VPS reply unavailable")
monkeypatch.setattr(network, "request", unavailable)
source = next(h for h in hosts.rows() if h["id"] == "current")
network.refresh(hosts, source)
assert journal.listing(equipment, row["id"])["items"][0]["state"] == "uncertain"
hosts.equipment = EquipmentStore(equipment.root.parent, {})
if superseded:
with hosts.equipment.db() as db:
saved = hosts.equipment._find(db, "instances", row["id"])
saved["network_operation"] = {"id": "other-operation", "state": "verified"}
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(saved), row["id"]))
methods = []
def restored(host, method, path, body=None):
methods.append(method)
return {
"id": queued["id"],
"kind": "request-position",
"state": "device_confirmed",
"received_at": queued["created_at"] + 1,
"roundtrip_seconds": 0.5,
}
monkeypatch.setattr(network, "request", restored)
network.refresh(hosts, source)
item = next(
i for i in journal.listing(hosts.equipment, row["id"])["items"] if i["id"] == queued["id"]
)
assert item["state"] == "device_confirmed"
assert len(sent) == 1 and methods == ["GET"]
if superseded:
with hosts.equipment.db() as db:
assert (
hosts.equipment._find(db, "instances", row["id"])["network_operation"]["id"]
== "other-operation"
)
def test_fifo_one_operation_per_tracker_and_full_history(ready, monkeypatch):
equipment, hosts, row = ready
first = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
second = runtime.enqueue(hosts, row["id"], "2" * 32, "position")
sent = sender(monkeypatch)
runtime.pump(hosts)
assert len(sent) == 1
network.record(
hosts,
row["id"],
first["id"],
{
"id": first["id"],
"kind": "request-position",
"state": "device_confirmed",
"received_at": time.time(),
"roundtrip_seconds": 0.5,
},
)
runtime.pump(hosts)
assert len(sent) == 2 and sent[1]["id"] == second["id"]
items = journal.listing(equipment, row["id"])["items"]
assert [x["state"] for x in items] == ["queued", "device_confirmed"]
assert any(e.get("evidence") == "received_at" for e in items[1]["events"])
def test_expired_cancelled_and_changed_device_never_sent(ready, monkeypatch):
equipment, hosts, row = ready
sent = sender(monkeypatch)
one = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
runtime.cancel(equipment, row["id"], one["id"])
runtime.enqueue(hosts, row["id"], "2" * 32, "position")
with equipment.db() as db:
value = json.loads(
db.execute("SELECT body FROM command_journal WHERE id=?", ("2" * 32,)).fetchone()[0]
)
value["queue_deadline"] = time.time() - 1
journal.put(db, row["id"], value)
runtime.enqueue(hosts, row["id"], "3" * 32, "position")
row["vehicle_id"] = "changed"
with equipment.db() as db:
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), row["id"]))
runtime.pump(hosts)
assert sent == []
assert [v["state"] for v in journal.listing(equipment, row["id"])["items"]] == [
"rejected",
"expired",
"cancelled",
]
def test_lost_post_preserves_same_operation_after_restart(ready, monkeypatch):
equipment, hosts, row = ready
def lost(*args, **kwargs):
raise OSError("lost")
monkeypatch.setattr(network, "request", lost)
value = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
runtime.pump(hosts)
hosts.equipment = EquipmentStore(equipment.root.parent, {})
sent = sender(monkeypatch)
runtime.pump(hosts)
assert sent == []
assert journal.listing(hosts.equipment, row["id"])["items"][0]["state"] == "submitting"
with pytest.raises(EquipmentError, match="началась"):
runtime.cancel(hosts.equipment, row["id"], value["id"])
def test_catalog_and_history_never_expose_password(ready, monkeypatch):
equipment, hosts, row = ready
values = catalog(equipment, row)
assert next(v for v in values if v["id"] == "pin6-on")["unavailable"]
assert not next(v for v in values if v["id"] == "pin4-pulse")["unavailable"]
value = runtime.enqueue(hosts, row["id"], "1" * 32, "pin4-on")
sender(monkeypatch)
runtime.pump(hosts)
public = json.dumps([values, journal.listing(equipment, row["id"])], ensure_ascii=False)
assert "123456" not in public and '"password"' not in public and "identity_key" not in public
assert "••••••*SERV*8.4.1" in public
assert value["description"]["queue_seconds"] == 3
def test_tracker_acceptance_is_persisted_but_does_not_finish_intent(ready, monkeypatch):
equipment, hosts, row = ready
sender(monkeypatch)
job = runtime.enqueue(hosts, row["id"], "9" * 32, "position")
runtime.pump(hosts)
accepted = time.time()
result = {
"id": job["id"],
"kind": "request-position",
"state": "dispatched",
"device_code": 6,
"device_accepted_at": accepted,
"received_at": accepted,
}
network.record(hosts, row["id"], job["id"], result)
network.record(hosts, row["id"], job["id"], result)
hosts.equipment = EquipmentStore(equipment.root.parent, {})
item = journal.listing(hosts.equipment, row["id"])["items"][0]
assert item["state"] == "dispatched" and item["device_accepted_at"] == accepted
events = [e for e in item["events"] if e.get("evidence") == "device_accepted_at"]
assert len(events) == 1 and events[0]["state"] == "device_accepted"
network.record(
hosts, row["id"], job["id"], {**result, "state": "device_confirmed", "device_code": 0}
)
item = journal.listing(hosts.equipment, row["id"])["items"][0]
assert item["state"] == "device_confirmed" and item["device_code"] == 0
assert item["device_accepted_at"] == accepted
def test_bounded_queue_parallel_duplicate_and_cursor(ready):
equipment, hosts, row = ready
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(
pool.map(lambda _: runtime.enqueue(hosts, row["id"], "1" * 32, "position"), range(2))
)
assert results[0]["id"] == results[1]["id"]
for n in range(2, 33):
runtime.enqueue(hosts, row["id"], f"{n:032x}", "position")
with pytest.raises(EquipmentError, match="заполнена"):
runtime.enqueue(hosts, row["id"], "f" * 32, "position")
page = journal.listing(equipment, row["id"], limit=20)
older = journal.listing(equipment, row["id"], before=page["next_before"], limit=20)
assert len(page["items"]) == 20 and len(older["items"]) == 12
assert len({x["id"] for x in page["items"] + older["items"]}) == 32
def test_cancel_race_is_rechecked_inside_dispatch_transaction(ready, monkeypatch):
equipment, hosts, row = ready
value = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
sent = sender(monkeypatch)
original = network.start
def intercept(*args, **kwargs):
runtime.cancel(equipment, row["id"], value["id"])
return original(*args, **kwargs)
monkeypatch.setattr(network, "start", intercept)
runtime.pump(hosts)
assert sent == []
assert journal.listing(equipment, row["id"])["items"][0]["state"] == "cancelled"
def test_pending_and_later_completion_remain_visible_outside_history_page(ready):
equipment, hosts, row = ready
for n in range(1, 33):
runtime.enqueue(hosts, row["id"], f"{n:032x}", "position")
first_id = f"{1:032x}"
page = journal.listing(equipment, row["id"])
assert len(page["items"]) == 25
assert first_id not in {i["id"] for i in page["items"]}
assert len(page["tracked_items"]) == 32
runtime.cancel(equipment, row["id"], first_id)
refreshed = journal.listing(equipment, row["id"], tracked=[first_id, "not-in-this-device"])
result = next(i for i in refreshed["tracked_items"] if i["id"] == first_id)
assert result["state"] == "cancelled"
assert len(refreshed["tracked_items"]) == 32
def test_queue_expiry_survives_core_downtime(ready, monkeypatch):
equipment, hosts, row = ready
value = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
hosts.equipment = EquipmentStore(equipment.root.parent, {})
sent = sender(monkeypatch)
monkeypatch.setattr(runtime.time, "time", lambda: value["created_at"] + 31)
runtime.pump(hosts)
assert sent == []
item = journal.listing(hosts.equipment, row["id"])["items"][0]
assert item["state"] == "expired" and item["reason"] == "queue_deadline"
def test_legacy_backfill_keeps_unknown_time_and_closes_orphans(ready):
equipment, hosts, row = ready
old = {
**row,
"network_operation": {
"id": "9" * 32,
"kind": "request-position",
"scope": "command",
"command": {"kind": "request-position"},
"state": "dispatched",
"created_at": 1,
},
}
current = {
**row,
"network_operation": {
"id": "8" * 32,
"kind": "request-position",
"scope": "command",
"command": {"kind": "request-position"},
"state": "device_confirmed",
"created_at": 2,
"password": "never-show-this",
"replies": ["never-show-this"],
},
}
with equipment.db() as db:
db.execute("DELETE FROM command_journal_migrations")
db.execute("INSERT INTO history VALUES(?,?,?)", (row["id"], 1, json.dumps(old)))
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(current), row["id"]))
reloaded = EquipmentStore(equipment.root.parent, {})
items = journal.listing(reloaded, row["id"])["items"]
assert [i["state"] for i in items] == ["device_confirmed", "uncertain"]
assert items[0]["events"][0]["historical"]
assert "never-show-this" not in json.dumps(items)
assert len(journal.listing(EquipmentStore(equipment.root.parent, {}), row["id"])["items"]) == 2
def test_runtime_api_rejects_foreign_origin_and_arbitrary_command(ready):
from types import SimpleNamespace
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.independent_equipment_api import router
equipment, hosts, row = ready
app = FastAPI()
app.include_router(router)
app.state.fleet = SimpleNamespace(
lock=hosts.lock, independent_equipment=equipment, vps_hosts=hosts
)
with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 12345)) as client:
path = f"/api/v1/fleet/equipment/instances/{row['id']}/commands"
assert client.get(path).status_code == 200
body = {"request_id": "1" * 32, "preset_id": "position"}
assert (
client.post(path, json=body, headers={"Origin": "https://foreign.example"}).status_code
== 403
)
assert client.post(path, json={**body, "raw": "reboot"}).status_code == 422
assert client.post(path, json={**body, "preset_id": "arbitrary"}).status_code == 409
result = client.post(path, json=body)
assert result.status_code == 200 and result.json()["state"] == "waiting"
assert client.post(path, json=body).json()["id"] == result.json()["id"]
assert client.get(path).json()["items"][0]["id"] == body["request_id"]
assert (
client.post(path + "/" + body["request_id"] + "/cancel").json()["state"] == "cancelled"
)
def test_preview_matches_actual_qualified_vps_payload(ready):
import importlib.util
from pathlib import Path
from k1link.fleet.equipment_actions import plan
equipment, _, row = ready
path = Path(__file__).resolve().parents[1] / "apps/vps-host/ndc_vps/actions.py"
spec = importlib.util.spec_from_file_location("qualified_b2_actions", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
for preset in catalog(equipment, row):
if preset["unavailable"]:
continue
body = plan(equipment, row, preset["command"])
body.pop("secondary")
body["id"] = "1" * 32
wire = bytes.fromhex(module.prepare(body)["binary"])
if preset["encoding"].endswith("FC"):
assert wire.decode().replace("123456", "••••••") == preset["wire"]
else:
assert wire.hex(" ").upper() == preset["wire"]
+82
View File
@@ -0,0 +1,82 @@
import hashlib
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.fleet.equipment_firmware import MAX_FIRMWARE_BYTES, FirmwareArchive, FirmwareError
from k1link.web.equipment_firmware_api import router
def test_archive_roundtrip_dedup_and_integrity_survive_reopen(tmp_path):
data = b"synthetic manufacturer image"
digest = hashlib.sha256(data).hexdigest()
known = {"arnavi-b2": {digest: {"version": "test", "source_url": "https://example.test"}}}
archive = FirmwareArchive(tmp_path, known)
item = archive.add("arnavi-b2", "sample.dfw", data)
assert item["version"] == "test"
assert item["source"] == "manufacturer"
assert not item["installable"]
reopened = FirmwareArchive(tmp_path, known)
assert reopened.add("arnavi-b2", "renamed.dfw", data) == item
assert reopened.listing("arnavi-b2") == [item]
assert reopened.download("arnavi-b2", digest) == (item, data)
db = reopened.connect()
with db:
db.execute("UPDATE images SET payload=?", (b"modified",))
db.close()
with pytest.raises(FirmwareError, match="повреждён"):
reopened.download("arnavi-b2", digest)
assert reopened.add("arnavi-b2", "sample.dfw", data) == item
assert reopened.download("arnavi-b2", digest) == (item, data)
def test_filename_cannot_assert_version_or_manufacturer(tmp_path):
archive = FirmwareArchive(tmp_path, {"arnavi-b2": {}})
item = archive.add("arnavi-b2", "231 (B2) -0.05.dfw", b"unknown image")
assert item["source"] == "user"
assert item["version"] is None
assert item["source_url"] is None
assert not item["installable"]
for name in ["../file.dfw", "file.exe", "file\n.dfw", "dir/file.dfw"]:
with pytest.raises(FirmwareError):
archive.add("arnavi-b2", name, b"x")
for data in [b"", b"x" * (MAX_FIRMWARE_BYTES + 1)]:
with pytest.raises(FirmwareError):
archive.add("arnavi-b2", "test.dfw", data)
with pytest.raises(FirmwareError):
archive.add("unknown", "test.dfw", b"x")
with pytest.raises(FirmwareError):
archive.download("arnavi-b2", "../anything")
def test_local_api_keeps_upload_separate_from_device_actions(tmp_path):
app = FastAPI()
app.state.fleet = SimpleNamespace(root=tmp_path)
app.include_router(router)
with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 1234)) as client:
path = "/api/v1/fleet/equipment/firmware/arnavi-b2"
assert client.get(path).json() == {"items": [], "update_available": False}
assert client.post(path + "?filename=sample.dfw", content=b"x").status_code == 415
uploaded = client.post(
path + "?filename=sample.dfw",
content=b"sample image",
headers={"Content-Type": "application/octet-stream"},
)
assert uploaded.status_code == 200
item = uploaded.json()
result = client.get(path + f"/{item['id']}/download")
assert result.content == b"sample image"
assert result.headers["x-content-sha256"] == item["sha256"]
assert "attachment" in result.headers["content-disposition"]
assert client.get(path).json()["items"] == [item]
assert client.post(path + "/update", json={}).status_code == 404
assert client.get(path, headers={"Origin": "https://foreign.test"}).status_code == 403
rejected = client.post(
path + "?filename=large.dfw",
content=b"x" * (MAX_FIRMWARE_BYTES + 1),
headers={"Content-Type": "application/octet-stream"},
)
assert rejected.status_code == 413
assert len(client.get(path).json()["items"]) == 1
+875
View File
@@ -0,0 +1,875 @@
"""Synthetic tests for operation persistence, authority and secret projection."""
import hashlib
import json
import time
from unittest.mock import Mock
import pytest
from k1link.device_plugins.arnavi_b2.profiles import Policy
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
from k1link.fleet import equipment_network as network
from k1link.fleet.independent_equipment import EquipmentError, EquipmentStore
from k1link.fleet.vps_hosts import VPSHosts
@pytest.fixture
def full_core_context(context):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
equipment, hosts, row = context
path = equipment.root / "evidence" / row["evidence_id"]
previous = decode_configuration((path / "configuration.bin").read_bytes())
config = Configuration(
previous.records
+ tuple(
Setting(n, value)
for n, value in (
(111, b""),
(112, b"\0\0"),
(7, b"\0"),
(113, b""),
(114, b"\0\0"),
(6, b"\0"),
(70, b"current.example"),
(71, b"\x26\xc2"),
(62, b"\0\x96"),
(72, b"\0\0\0\1"),
(222, b"unknown-secret"),
)
)
)
(path / "configuration.bin").write_bytes(config.encode())
(path / "identity.json").write_text(json.dumps({"imei": row["identity_key"]}))
row["observed"]["read_at"] = 10
row["settings"]["parameters"]["25"] = 16
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.15"
hosts.save(host)
return equipment, hosts, row, config
def test_full_network_profile_body_preserves_unknown_fields_and_is_private(
full_core_context, monkeypatch
):
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
equipment, hosts, row, config = full_core_context
sent = []
def send(host, method, path, body=None):
sent.append(body)
assert equipment.listing()[0]["network_operation"]["id"] == body["id"]
return {"id": body["id"], "kind": body["kind"], "state": "queued"}
monkeypatch.setattr(network, "request", send)
result = network.start(hosts, row["id"], 1)
assert sent[0]["kind"] == "configure-all"
assert sent[0]["expected_sha256"] == hashlib.sha256(config.encode()).hexdigest()
target = decode_configuration(bytes.fromhex(sent[0]["target_configuration"]))
assert target.integer(25, 2) == 16 and target.value(222) == config.value(222)
assert result["network_operation"]["scope"] == "configuration"
assert all(
text not in json.dumps(result)
for text in (
"unknown-secret",
'"target_configuration":',
"123456",
sent[0]["target_configuration"],
)
)
def test_full_network_read_snapshot_refreshes_config_but_not_sim_identity(
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": "observed",
"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, True)
assert result["network_operation"]["record_count"] == len(config.records)
assert result["observed"]["configuration_transport"] == "vps"
assert result["observed"]["read_at"] == 10
assert result["observed"]["configuration_read_at"] > 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)
+161
View File
@@ -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"]))
+33
View File
@@ -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")
+365
View File
@@ -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
+93
View File
@@ -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("<I", int(time.time())) + bytes((code,)) + token
return b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]"
@pytest.fixture
def pending(store): # noqa: F811
from ndc_vps.commands import Commands
commands = Commands(store)
imei = "123456789012345"
other = "123456789012346"
store.set_devices(
[
{"imei": imei, "instance_id": "a" * 32},
{"imei": other, "instance_id": "b" * 32},
]
)
commands.sessions[imei] = {"primary", "secondary"}
commands.sessions[other] = {"another-tracker"}
body = {
"id": "c" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
commands.submit(body)
raw = commands.take(imei, "primary")
return commands, imei, other, body, raw[5:9]
def test_second_stream_receipt_confirms_once_without_resending(pending):
commands, imei, _, body, token = pending
commands.receive(imei, receipt(token), "secondary")
confirmed = commands.get(body["id"])
assert confirmed["state"] == "device_confirmed" and confirmed["device_code"] == 0
assert commands.take(imei, "secondary") is None
commands.receive(imei, receipt(token, 5), "primary")
assert commands.get(body["id"]) == confirmed
assert type(commands)(commands.store).get(body["id"]) == confirmed
def test_ack_is_not_completion_and_first_acceptance_survives_duplicate(pending):
commands, imei, _, body, token = pending
commands.receive(imei, receipt(token, 6), "secondary")
accepted = commands.get(body["id"])
assert accepted["state"] == "dispatched" and accepted["device_code"] == 6
assert accepted["device_accepted_at"] > 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"
File diff suppressed because it is too large Load Diff
+60
View File
@@ -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
+379
View File
@@ -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("<I", int(time.time())) + bytes([code]) + raw[5:9]
ops.commands.receive(
body["imei"], b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]", "live"
)
def restored(ops):
return type(ops)(ops.store, type(ops.commands)(ops.store))
def test_offline_intent_survives_time_restart_duplicate_submit_and_cancel(runtime):
ops, body, now = runtime
first = ops.submit(body)
now[0] += 86400
ops = restored(ops)
assert ops.submit(body)["id"] == first["id"]
assert ops.get(body["id"])["state"] == "queued"
assert ops.get(body["id"])["attempt_count"] == 0
with pytest.raises(ValueError, match="conflict"):
ops.submit({**body, "kind": "restart"})
assert ops.cancel(body["id"])["state"] == "stopped"
connect(ops, body)
assert restored(ops).get(body["id"])["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_late_transport_observation_is_visible_after_operation_completed(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
raw, _, ticket = ops.commands.take_delivery(body["imei"], "live", with_receipt=True)
reply(ops, body, raw)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert ops.get(body["id"])["transport"][0]["state"] == "prepared"
ops.commands.transport.record([
(ticket, "written", now[0], 0, None),
(ticket, "tcp_acknowledged", now[0] + .5, .5, None),
])
result = ops.get(body["id"])
assert result["state"] == "device_confirmed"
assert result["transport"][0]["tcp_ack_seconds"] == .5
assert ops.history(body["id"])["items"][0]["transport"] == result["transport"]
assert restored(ops).get(body["id"])["transport"] == result["transport"]
def test_lost_tracker_reply_has_new_attempt_same_intent_and_complete_history(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
first = ops.commands.take(body["imei"], "live")
now[0] += 31
assert ops.get(body["id"])["state"] == "queued"
assert ops.get(body["id"])["attempt_count"] == 1
ops = restored(ops)
now[0] += 5
connect(ops, body)
ops.advance(body["imei"])
second = ops.commands.take(body["imei"], "live")
assert first[5:9] != second[5:9]
reply(ops, body, first) # Old attempt cannot confirm the new one.
assert ops.get(body["id"])["state"] == "dispatched"
reply(ops, body, second)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert ops.get(body["id"])["attempt_count"] == 2
assert [x["state"] for x in ops.history(body["id"])["items"]] == [
"device_confirmed",
"unconfirmed",
]
assert restored(ops).get(body["id"])["state"] == "device_confirmed"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM operations").fetchone()[0] == 1
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 2
def test_vps_crash_after_dispatch_resumes_intent_not_old_attempt(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
assert ops.commands.take(body["imei"], "live")
ops = restored(ops)
assert ops.get(body["id"])["state"] == "queued"
now[0] += 5
connect(ops, body)
ops.advance(body["imei"])
raw = ops.commands.take(body["imei"], "live")
reply(ops, body, raw)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert len(ops.history(body["id"])["items"]) == 2
def test_vps_crash_before_attempt_admission_and_cancellation_race(runtime, monkeypatch):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
def crash(*args):
raise RuntimeError("simulated process loss")
monkeypatch.setattr(ops.commands, "submit", crash)
with pytest.raises(RuntimeError):
ops.advance(body["imei"])
ops = restored(ops)
assert ops.cancel(body["id"])["state"] == "stopped"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 0
def test_cancel_before_lost_post_arrives_is_a_persisted_tombstone(runtime):
ops, body, _ = runtime
assert ops.cancel(body["id"], body["kind"])["state"] == "stopped"
ops = restored(ops)
connect(ops, body)
assert ops.submit(body)["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_offline_tracker_does_not_block_another_and_fifo_is_per_imei(runtime):
ops, first, _ = runtime
second = {**first, "id": "b" * 32, "imei": "123456789012346"}
ops.store.set_devices(
[
{"imei": first["imei"], "instance_id": "c" * 32},
{"imei": second["imei"], "instance_id": "d" * 32},
]
)
ops.submit(first)
ops.submit(second)
ops.submit({**second, "id": "e" * 32})
connect(ops, second)
ops.advance(first["imei"])
ops.advance(second["imei"])
raw = ops.commands.take(second["imei"], "live")
assert ops.get("e" * 32)["attempt_count"] == 0
reply(ops, second, raw)
assert ops.get(second["id"])["state"] == "device_confirmed"
assert ops.get(first["id"])["attempt_count"] == 0
assert ops.get("e" * 32)["attempt_count"] == 1
@pytest.mark.parametrize(
"code,expected", [(1, "device_rejected"), (5, "device_rejected"), (7, "queued")]
)
def test_permanent_rejection_and_device_queue_backpressure_differ(runtime, code, expected):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
reply(ops, body, ops.commands.take(body["imei"], "live"), code)
assert ops.get(body["id"])["state"] == expected
def test_restart_accepted_by_b2_never_replayed_when_return_evidence_missing(runtime):
ops, body, now = runtime
body["kind"] = "restart"
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
reply(ops, body, ops.commands.take(body["imei"], "live"))
now[0] += 181
assert ops.get(body["id"])["state"] == "accepted"
assert ops.get(body["id"])["attempt_count"] == 1
@pytest.mark.parametrize("observed", ["target", "before", "divergent"])
def test_uncertain_write_reads_state_before_any_retry(full_context, observed): # noqa: F811
from ndc_vps.operations import Operations
from ndc_vps.usb_protocol import Configuration, Setting
commands, body, before, target, wire, now = full_context
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
assert b"SERV*1.8" in commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 181
assert ops.get(body["id"])["runtime_phase"] == "retry-wait"
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
image = (
target
if observed == "target"
else before
if observed == "before"
else Configuration(
tuple(
Setting(r.number, b"\x00\x11" if r.number == 25 else r.value)
for r in before.records
)
)
)
commands.web_receive(wire(5, image.encode()), "192.0.2.1")
result = ops.get(body["id"])
assert (
result["state"]
== {"target": "verified", "before": "queued", "divergent": "rejected"}[observed]
)
assert result["attempt_count"] == 2
assert "123456" not in json.dumps(ops.history(body["id"]))
with commands.store.db() as db:
images = sum(
bool(json.loads(r[0]).get("write_reply_sent_at"))
for r in db.execute("SELECT body FROM commands")
)
assert images == 1
def test_cancelled_inflight_keeps_final_receipt_but_stops_unknown_retry(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
wire = ops.commands.take(body["imei"], "live")
assert ops.cancel(body["id"])["stop_requested"]
now[0] += 31
result = ops.get(body["id"])
assert result["state"] == "stopped" and result["attempt_count"] == 1
connect(ops, body)
reply(ops, body, wire)
assert ops.get(body["id"])["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_repeated_reads_crash_plan_after_admission_reuses_child(runtime, monkeypatch):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
original = ops.commands.submit
def admitted(body):
original(body)
raise RuntimeError("crash after commit")
monkeypatch.setattr(ops.commands, "submit", admitted)
with pytest.raises(RuntimeError):
ops.advance(body["imei"])
ops = restored(ops)
connect(ops, body)
assert ops.get(body["id"])["attempt_count"] == 1
wire = ops.commands.take(body["imei"], "live")
reply(ops, body, wire)
assert ops.get(body["id"])["state"] == "device_confirmed"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
def test_old_image_read_allows_fresh_preflight_before_second_write(full_context): # noqa: F811
from ndc_vps.operations import Operations
commands, body, before, target, wire, now = full_context
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 181
ops.get(body["id"])
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
assert ops.get(body["id"])["state"] == "queued"
now[0] += 15
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
assert b"SERV*1.8" in commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 15
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
assert ops.get(body["id"])["state"] == "verified"
assert ops.get(body["id"])["attempt_count"] == 3
@pytest.mark.parametrize("both", [False, True])
def test_sim_recovery_reads_target_and_fresh_modem_without_second_restart(full_context, both): # noqa: F811
import hashlib
from ndc_vps.operations import Operations
from ndc_vps.usb_protocol import Configuration, Setting
from test_vps_host import sim_packet
commands, body, before, _, wire, now = full_context
before = Configuration(
before.records + (Setting(72, (2072 | (1 << 20) if both else 2072).to_bytes(4, "big")),)
)
target = Configuration(
tuple(
Setting(
r.number,
(2072 | (0 if both else 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(),
)
if both:
body.pop("sim_slot")
body["sim_policy"] = "both"
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
commands.web_receive(wire(2), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
assert commands.take(body["imei"], "live")[-3:-1] == b"\x01\x07"
now[0] += 361
ops.get(body["id"])
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
ops.observe(body["imei"], sim_packet(now[0], slot=2))
ops.observe(
body["imei"], sim_packet(now[0] - 1, slot=1)
) # delayed older sample cannot downgrade
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
result = ops.get(body["id"])
assert result["state"] == "sim_selected" and result["active_sim"] == 2
assert result["attempt_count"] == 2 and commands.take(body["imei"], "live") is None
+208
View File
@@ -0,0 +1,208 @@
"""A tracker packet and the command evidence it carries have one commit boundary."""
import asyncio
import sqlite3
import subprocess
import sys
import time
from pathlib import Path
import pytest
from test_vps_command_receipts import receipt
from test_vps_host import store # noqa: F401
@pytest.mark.parametrize("failure", ["before-receipt", "after-receipt", None])
def test_packet_command_and_ack_share_commit_boundary(store, monkeypatch, failure): # noqa: F811
from ndc_vps.commands import Commands
from ndc_vps.service import Service
service = Service(store)
commands = service.commands
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
commands.sessions[imei] = {"outbound"}
body = {
"id": "c" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
commands.submit(body)
outgoing = commands.take(imei, "outbound")
raw = receipt(outgoing[5:9])
def failed(*args):
raise OSError("simulated failure inside receive pipeline")
if failure == "before-receipt":
monkeypatch.setattr(commands, "receive", failed)
elif failure == "after-receipt":
monkeypatch.setattr(service.operations, "observe", failed)
class Writer:
closed = False
def __init__(self):
self.writes = []
def get_extra_info(self, name):
return ("192.0.2.1", 12345)
def is_closing(self):
return self.closed
def write(self, data):
if data == b"{\x00\x01}":
# Check from a separate connection exactly when the ACK leaves.
assert commands.get(body["id"])["state"] == "device_confirmed"
assert len(store.fetch(0)["items"]) == 1
self.writes.append(data)
async def drain(self):
pass
def close(self):
self.closed = True
class Delivery:
def __init__(self, writer):
self.writer = writer
def ready(self):
return True
def write(self, data, *args):
self.writer.write(data)
def abort(self):
self.writer.close()
monkeypatch.setattr("ndc_vps.service.Delivery", Delivery)
async def exchange():
reader = asyncio.StreamReader()
reader.feed_data(b"\xff\x23" + int(imei).to_bytes(8, "little") + raw)
reader.feed_eof()
writer = Writer()
await service.tracker(reader, writer)
assert writer.closed and service.connections == 0
return writer.writes
writes = asyncio.run(exchange())
if failure:
assert b"{\x00\x01}" not in writes
assert store.fetch(0)["items"] == []
assert commands.get(body["id"])["state"] == "dispatched"
else:
assert writes[-1] == b"{\x00\x01}"
store.acknowledge(store.fetch(0)["items"][0]["id"])
assert store.fetch(0)["items"] == []
assert Commands(store).get(body["id"])["state"] == "device_confirmed"
def test_sqlite_failure_does_not_leave_partial_modem_or_command_evidence(store): # noqa: F811
from ndc_vps.service import Service
from test_vps_host import sim_packet
service = Service(store)
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
raw = sim_packet(time.time(), slot=2)
with pytest.raises(sqlite3.OperationalError), store.packet_transaction():
store.append(imei, raw, [])
service.operations.observe(imei, raw)
with store.db() as db:
db.execute("INSERT INTO missing_table VALUES(1)")
assert store.fetch(0)["items"] == []
with store.db() as db:
assert db.execute("SELECT count(*) FROM operation_modem").fetchone()[0] == 0
# The failed scope must not leak its connection into the next packet.
with store.packet_transaction():
store.append(imei, raw, [])
service.operations.observe(imei, raw)
assert len(store.fetch(0)["items"]) == 1
with store.db() as db:
assert db.execute("SELECT count(*) FROM operation_modem").fetchone()[0] == 1
@pytest.mark.parametrize("committed", [False, True])
def test_process_loss_cannot_split_packet_and_durable_operation_result(store, committed): # noqa: F811
from ndc_vps import store as store_module
from ndc_vps.service import Service
# os._exit skips Python context-manager cleanup, as a process crash would.
script = """
import os, sys, time, struct
sys.path.insert(0, sys.argv[1])
from ndc_vps.store import Store
from ndc_vps.service import Service
service = Service(Store(sys.argv[2]))
imei = '123456789012345'
service.store.set_devices([{'imei': imei, 'instance_id': 'a'*32}])
body = {'id':'c'*32, 'imei':imei, 'kind':'request-position', 'model':231, 'firmware':'0.01'}
commands = service.commands
commands.sessions[imei] = {'live'}
commands.session_activity[imei,'live'] = time.monotonic()
service.operations.submit(body)
service.operations.advance(imei)
outgoing = commands.take(imei, 'live')
data = struct.pack('<I', int(time.time())) + b'\\0' + outgoing[5:9]
raw = b'[\\x01\\x09\\x05\\0' + data + bytes([sum(data)%256]) + b']'
with service.store.packet_transaction():
service.store.append(imei, raw, [])
commands.receive(imei, raw, 'live')
service.operations.observe(imei, raw)
if sys.argv[3] == 'before':
os._exit(77)
os._exit(77)
"""
process = subprocess.run(
[
sys.executable,
"-c",
script,
str(Path(store_module.__file__).parents[1]),
str(store.root),
"after" if committed else "before",
],
capture_output=True,
timeout=10,
)
assert process.returncode == 77, process.stderr.decode()
recovered = Service(store)
result = recovered.operations.get("c" * 32)
assert result["state"] == ("device_confirmed" if committed else "queued")
assert result["attempt_count"] == 1
assert len(store.fetch(0)["items"]) == int(committed)
with store.db() as db:
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
def test_other_worker_cannot_observe_uncommitted_packet(store): # noqa: F811
import threading
from concurrent.futures import ThreadPoolExecutor
from test_vps_host import package
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
written, release = threading.Event(), threading.Event()
def ingest():
with store.packet_transaction():
store.append(imei, package(), [])
written.set()
assert release.wait(5)
with ThreadPoolExecutor(max_workers=1) as worker:
pending = worker.submit(ingest)
try:
assert written.wait(5)
assert store.fetch(0)["items"] == []
finally:
release.set()
pending.result(timeout=5)
assert len(store.fetch(0)["items"]) == 1
+284
View File
@@ -0,0 +1,284 @@
"""State migration retains durable identities/history and fails before foreign mutations."""
import gzip
import hashlib
import importlib.util
import io
import json
import sqlite3
import ssl
import subprocess
import tarfile
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_vps_host import store # noqa: F401
@pytest.fixture
def migration(store, monkeypatch, tmp_path): # noqa: F811
source = Path(__file__).resolve().parents[1] / "apps/vps-host/portable_state.py"
spec = importlib.util.spec_from_file_location("portable_state_test", source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
state = store.root
subprocess.run(
[
"openssl",
"req",
"-x509",
"-newkey",
"rsa:2048",
"-nodes",
"-days",
"1",
"-subj",
"/CN=synthetic",
"-keyout",
str(state / "tls.key"),
"-out",
str(state / "tls.crt"),
],
capture_output=True,
check=True,
)
fingerprint = hashlib.sha256(
ssl.PEM_cert_to_DER_cert((state / "tls.crt").read_text())
).hexdigest()
config = {
**store.config,
"host_id": "vps_" + fingerprint,
"fingerprint": fingerprint,
"public_host": "example.org",
}
(state / "host.json").write_text(json.dumps(config))
store.config = config
store.invitation()
from ndc_vps.commands import Commands
from ndc_vps.operations import Operations
commands = Commands(store)
ops = Operations(store, commands)
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
body = {
"id": "b" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
ops.submit(body)
commands.sessions[imei] = {"old"}
commands.session_activity[imei, "old"] = module.time.monotonic()
commands.session_started[imei, "old"] = module.time.monotonic()
ops.advance(imei)
assert commands.take(imei, "old")
ops.submit({**body, "id": "c" * 32})
ops.cancel("d" * 32, "request-position")
root = tmp_path / "source"
root.mkdir()
unit = tmp_path / "unit"
unit.write_text("ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json")
artifact = "e" * 64
proposal = {"previous": "/releases/" + artifact, "artifact": artifact, "plan_sha256": "plan"}
running = [True]
def run(*args):
if args[1] == "stop":
running[0] = False
elif args[1] == "start":
assert not (root / "migration-fence.json").exists()
running[0] = True
real_run = subprocess.run
def inspect(*args, **kwargs):
if args[0][0] == "systemctl":
return SimpleNamespace(stdout=b"active" if running[0] else b"inactive")
return real_run(*args, **kwargs)
monkeypatch.setattr(module.subprocess, "run", inspect)
monkeypatch.setattr(module.os, "geteuid", lambda: 0)
engine = SimpleNamespace(
ROOT=root,
STATE=state,
UNIT=unit,
run=run,
plan=lambda _: proposal,
digest=lambda: artifact,
healthy=lambda: None,
)
return module, engine, store, ops, tmp_path, running
def export(migration):
m, engine, _, _, tmp, running = migration
archive = tmp / "private-state.tar.gz"
m.export_state(engine, archive)
assert archive.stat().st_mode & 0o777 == 0o600
assert not running[0] and (engine.ROOT / "migration-fence.json").exists()
return archive
def test_archive_preserves_database_identity_attempts_stop_markers_and_recovery(migration):
m, engine, original, ops, tmp, _ = migration
before = {name: m.sha(engine.STATE / name) for name in m.FILES - {"journal.sqlite3"}}
archive = export(migration)
unpacked = tmp / "unpacked"
unpacked.mkdir()
m.unpack(archive, m.sha(archive), unpacked, engine.digest())
for name, digest in before.items():
assert m.sha(unpacked / "state" / name) == digest
with original.db() as a, sqlite3.connect(unpacked / "state/journal.sqlite3") as b:
assert list(a.iterdump()) == list(b.iterdump())
from ndc_vps.commands import Commands
from ndc_vps.operations import Operations
from ndc_vps.store import Store
restored_store = Store(unpacked / "state")
restored = Operations(restored_store, Commands(restored_store))
assert restored.get("b" * 32)["id"] == "b" * 32
assert restored.get("b" * 32)["state"] == "queued"
assert restored.get("b" * 32)["attempt_count"] == 1
assert restored.get("c" * 32)["attempt_count"] == 0
assert restored.history("b" * 32)["items"][0]["state"] == "uncertain"
body = {
"id": "d" * 32,
"imei": "123456789012345",
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
assert restored.submit(body)["state"] == "stopped"
assert not restored.commands.sessions # Never copy stale TCP-session liveness.
@pytest.mark.parametrize(
"variant",
["traversal", "absolute", "link", "duplicate", "extra", "missing", "oversize", "corrupt"],
)
def test_invalid_archive_rejected_without_product_mutation(migration, variant):
m, engine, _, _, tmp, _ = migration
original = export(migration)
archive = tmp / "invalid.tar.gz"
with (
tarfile.open(original) as source,
tarfile.open(archive, "w:gz", format=tarfile.USTAR_FORMAT) as dst,
):
for info in source:
if variant == "missing" and info.name == "state/connect.key":
continue
data = source.extractfile(info).read()
if variant == "corrupt" and info.name == "state/connect.key":
data = b"changed"
info.size = len(data)
dst.addfile(info, io.BytesIO(data))
if variant not in ("missing", "corrupt"):
name = {
"traversal": "../escaped",
"absolute": "/escaped",
"link": "state/host.json",
"duplicate": "state/host.json",
"extra": "extra",
"oversize": "manifest.json",
}[variant]
extra = tarfile.TarInfo(name)
if variant == "link":
extra.type, extra.linkname = tarfile.SYMTYPE, "/etc/passwd"
dst.addfile(extra)
destination = tmp / "target"
destination.mkdir()
with pytest.raises(ValueError):
m.unpack(archive, m.sha(archive), destination, engine.digest())
assert not (tmp / "escaped").exists()
def test_checksum_and_release_mismatch_rejected_before_state_use(migration):
m, engine, _, _, tmp, _ = migration
archive = export(migration)
target = tmp / "target"
target.mkdir()
with pytest.raises(ValueError, match="digest"):
m.unpack(archive, "0" * 64, target, engine.digest())
assert not list(target.iterdir())
with pytest.raises(ValueError, match="exact installer"):
m.unpack(archive, m.sha(archive), target, "f" * 64)
def test_archive_size_limit_is_checked_before_reading_large_member(migration):
m, engine, _, _, tmp, _ = migration
archive = tmp / "oversized.tar.gz"
info = tarfile.TarInfo("state/journal.sqlite3")
info.size = m.MAX_BYTES + 1
# Header only: this must be rejected without allocating or reading 2 GiB.
with gzip.open(archive, "wb") as stream:
stream.write(info.tobuf(format=tarfile.USTAR_FORMAT))
target = tmp / "target"
target.mkdir()
with pytest.raises(ValueError, match="size limit"):
m.unpack(archive, m.sha(archive), target, engine.digest())
assert not list(target.iterdir())
def test_export_failure_keeps_source_fenced_until_explicit_resume(migration, monkeypatch):
m, engine, _, _, tmp, running = migration
monkeypatch.setattr(m, "check_state", lambda _: (_ for _ in ()).throw(ValueError("broken")))
with pytest.raises(ValueError, match="broken"):
m.export_state(engine, tmp / "failed.tar.gz")
assert not running[0]
assert not (tmp / "failed.tar.gz").exists()
assert (engine.ROOT / "migration-fence.json").exists()
m.resume_source(engine)
assert running[0] and not (engine.ROOT / "migration-fence.json").exists()
def test_import_never_overwrites_existing_installation(migration):
m, engine, _, _, tmp, _ = migration
with pytest.raises(ValueError, match="empty product"):
m.import_state(engine, tmp / "does-not-exist", "0" * 64)
def test_existing_export_path_does_not_stop_source(migration):
m, engine, _, _, tmp, running = migration
existing = tmp / "existing"
existing.write_bytes(b"keep")
with pytest.raises(ValueError, match="new archive"):
m.export_state(engine, existing)
assert running[0] and existing.read_bytes() == b"keep"
@pytest.mark.parametrize("failure", ["before_publish", "after_publish"])
def test_failed_import_exposes_no_partial_identity(migration, monkeypatch, failure):
m, source, _, _, tmp, _ = migration
archive = export(migration)
target = SimpleNamespace(**vars(source))
target.ROOT, target.STATE, target.UNIT = (
tmp / "target",
tmp / "target-state",
tmp / "target-unit",
)
original_rename = m.os.rename
def rename(old, new):
assert set(p.name for p in old.iterdir()) == m.FILES
assert not new.exists()
if failure == "before_publish":
raise OSError("simulated publication failure")
return original_rename(old, new)
def apply(*args):
assert m.check_state(target.STATE)["host_id"] == m.check_state(source.STATE)["host_id"]
raise OSError("simulated service installation failure")
target.apply = apply
monkeypatch.setattr(m.os, "rename", rename)
with pytest.raises(OSError, match="simulated"):
m.import_state(target, archive, m.sha(archive))
if failure == "before_publish":
assert not target.STATE.exists()
else:
assert set(p.name for p in target.STATE.iterdir()) == m.FILES
assert m.check_state(target.STATE)["host_id"] == m.check_state(source.STATE)["host_id"]
assert not list(tmp.glob(".ndc-vps-import-*"))