feat(fleet): integrate independent trackers, VPS pairing and recoverable commands
This commit is contained in:
@@ -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
|
||||
@@ -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"]
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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"]))
|
||||
@@ -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")
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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-*"))
|
||||
Reference in New Issue
Block a user