2304 lines
87 KiB
Python
2304 lines
87 KiB
Python
"""Durability, identity admission, decoder and shared VPS assignment acceptance."""
|
|
|
|
import asyncio
|
|
import base64
|
|
import hashlib
|
|
import importlib
|
|
import json
|
|
import shutil
|
|
import struct
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from k1link.device_plugins.arnavi_b2 import internal
|
|
from k1link.fleet.vps_hosts import VPSHosts
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def test_transport_ack_prefix_and_abort_are_observations_only(store, monkeypatch):
|
|
from ndc_vps import delivery
|
|
|
|
class Writer:
|
|
kernel = 0
|
|
closed = False
|
|
buffer = 0
|
|
|
|
def __init__(self):
|
|
self.transport = self
|
|
|
|
def get_extra_info(self, _):
|
|
return self
|
|
|
|
def setsockopt(self, *args):
|
|
pass
|
|
|
|
def is_closing(self):
|
|
return self.closed
|
|
|
|
def write(self, data):
|
|
self.kernel += len(data)
|
|
|
|
def get_write_buffer_size(self):
|
|
return self.buffer
|
|
|
|
def abort(self):
|
|
self.closed = True
|
|
self.kernel = self.buffer = 0
|
|
|
|
async def exercise():
|
|
writer, first, second = Writer(), [], []
|
|
monkeypatch.setattr(delivery, "queued_bytes", lambda _: writer.kernel)
|
|
guard = delivery.Delivery(writer)
|
|
guard.write(b"header")
|
|
guard.write(b"one", time.monotonic() + 1, lambda *x: first.append(x))
|
|
guard.write(b"two", time.monotonic() + 1, lambda *x: second.append(x))
|
|
writer.kernel = 3 # Only the later command is still unacknowledged.
|
|
guard.check()
|
|
assert [x[0] for x in first] == ["written", "tcp_acknowledged"]
|
|
assert [x[0] for x in second] == ["written"]
|
|
guard.abort()
|
|
guard.abort()
|
|
assert [x[0] for x in second] == ["written", "unconfirmed"]
|
|
assert second[-1][3] == "connection_closed"
|
|
assert first[-1][2] >= 0
|
|
|
|
for queued in (None, 3):
|
|
writer, observed = Writer(), []
|
|
monkeypatch.setattr(delivery, "queued_bytes", lambda _, q=queued: q)
|
|
guard = delivery.Delivery(writer)
|
|
guard.write(b"cmd", time.monotonic() + 0.01, lambda *x, log=observed: log.append(x))
|
|
await asyncio.sleep(0.03)
|
|
assert [x[0] for x in observed] == ["written", "unconfirmed"]
|
|
assert observed[-1][3] == "delivery_deadline"
|
|
|
|
writer, observed = Writer(), []
|
|
guard = delivery.Delivery(writer)
|
|
with pytest.raises(TimeoutError):
|
|
guard.write(b"cmd", time.monotonic() - 1, lambda *x: observed.append(x))
|
|
assert [x[0] for x in observed] == ["unconfirmed"]
|
|
assert observed[0][3] == "expired_before_write"
|
|
|
|
asyncio.run(exercise())
|
|
|
|
|
|
def test_transport_journal_survives_crash_without_promoting_command(store):
|
|
from ndc_vps.commands import Commands
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
commands.sessions[imei] = {"private-session"}
|
|
request = dict(id="a" * 32, imei=imei, kind="request-position", model=231, firmware="0.01")
|
|
commands.submit(request)
|
|
_, _, ticket = commands.take_delivery(imei, "private-session", with_receipt=True)
|
|
assert commands.get(request["id"])["transport"][0]["state"] == "prepared"
|
|
now = time.time()
|
|
commands.transport.record([(ticket, "written", now, 0, None)])
|
|
assert commands.get(request["id"])["state"] == "dispatched"
|
|
commands.transport.record([(ticket, "tcp_acknowledged", now + .5, .5, None)])
|
|
value = commands.get(request["id"])
|
|
assert value["state"] == "dispatched" # Not proof of B2 execution.
|
|
assert value["transport"][0]["tcp_ack_seconds"] == .5
|
|
assert commands.submit(request) == value # Lost API response reuses the same facts.
|
|
assert "private-session" not in json.dumps(value["transport"])
|
|
# A late close cannot erase an observed ACK; restart preserves it.
|
|
commands.transport.record([(ticket, "unconfirmed", now + 1, 1, "connection_closed")])
|
|
commands = Commands(store)
|
|
assert commands.get(request["id"])["transport"][0]["state"] == "tcp_acknowledged"
|
|
assert commands.get(request["id"])["state"] == "uncertain"
|
|
|
|
request["id"] = "b" * 32
|
|
commands.sessions[imei] = {"new-session"}
|
|
commands.submit(request)
|
|
_, _, ticket = commands.take_delivery(imei, "new-session", with_receipt=True)
|
|
commands.transport.record([(ticket, "written", now + 2, 0, None)])
|
|
commands = Commands(store)
|
|
value = commands.get(request["id"])
|
|
assert value["transport"][0]["state"] == "unconfirmed"
|
|
assert value["transport"][0]["reason"] == "host_restarted"
|
|
assert commands.take_delivery(imei, "new-session", with_receipt=True) is None
|
|
|
|
|
|
def test_transport_observations_commit_when_socket_cancels_sender(store, monkeypatch):
|
|
from ndc_vps.service import Service
|
|
|
|
async def exercise():
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
service = Service(store)
|
|
service.commands.sessions[imei] = {"live"}
|
|
service.commands.session_activity[imei, "live"] = time.monotonic()
|
|
request = dict(id="a" * 32, imei=imei, kind="request-position", model=231, firmware="0.01")
|
|
service.commands.submit(request)
|
|
entered, resume = asyncio.Event(), asyncio.Event()
|
|
original = asyncio.to_thread
|
|
|
|
async def controlled(function, *args, **kwargs):
|
|
if function == service.commands.transport.record:
|
|
entered.set()
|
|
await resume.wait()
|
|
return await original(function, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(asyncio, "to_thread", controlled)
|
|
|
|
class Writer:
|
|
def is_closing(self):
|
|
return False
|
|
|
|
async def drain(self):
|
|
pass
|
|
|
|
class Delivery:
|
|
observer = None
|
|
|
|
def ready(self):
|
|
return True
|
|
|
|
def write(self, data, deadline, observe):
|
|
self.observer = observe
|
|
observe("written", time.time(), 0, None)
|
|
|
|
def abort(self):
|
|
if self.observer:
|
|
self.observer("unconfirmed", time.time(), .1, "connection_closed")
|
|
self.observer = None
|
|
|
|
sender = asyncio.create_task(service.send_commands(imei, Writer(), "live", Delivery()))
|
|
await asyncio.wait_for(entered.wait(), 2)
|
|
sender.cancel()
|
|
await asyncio.sleep(0)
|
|
resume.set()
|
|
await asyncio.gather(sender, return_exceptions=True)
|
|
observed = service.commands.get(request["id"])["transport"]
|
|
assert len(observed) == 1
|
|
assert observed[0]["written_at"] <= observed[0]["closed_at"]
|
|
assert observed[0]["state"] == "unconfirmed"
|
|
assert observed[0]["reason"] == "connection_closed"
|
|
|
|
asyncio.run(exercise())
|
|
|
|
|
|
def test_diagnostic_probe_needs_live_exclusive_observation_and_never_replays(store):
|
|
from ndc_vps import actions
|
|
from ndc_vps.commands import Commands
|
|
from ndc_vps.observation import Observation
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
commands.sessions[imei] = {"original"}
|
|
request = {
|
|
"id": "a" * 32, "imei": imei, "model": 231, "firmware": "0.01",
|
|
"kind": "probe-diagnostic-mode", "observation_id": "b" * 32,
|
|
}
|
|
with pytest.raises(ValueError, match="observation"):
|
|
actions.prepare({k: v for k, v in request.items() if k != "observation_id"})
|
|
with pytest.raises(ValueError, match="unknown action fields"):
|
|
actions.prepare({**request, "binary": "0107"})
|
|
with pytest.raises(ValueError, match="observation unavailable"):
|
|
commands.submit(request)
|
|
observation = Observation(store)
|
|
observation.arm({"id": request["observation_id"]})
|
|
commands.submit(request)
|
|
# Closing an armed window before dispatch prevents any device command.
|
|
observation.close(request["observation_id"])
|
|
assert commands.take(imei, "original") is None
|
|
assert commands.get(request["id"])["state"] == "expired"
|
|
|
|
request = {**request, "id": "d" * 32, "observation_id": "e" * 32}
|
|
observation.arm({"id": request["observation_id"]})
|
|
commands.submit(request)
|
|
wire = commands.take(imei, "original")
|
|
assert wire[:3] == bytes.fromhex("7b07ff")
|
|
assert wire[4] == 0xff and wire[9:] == bytes.fromhex("01007d")
|
|
assert wire[3] == sum(wire[4:-1]) % 256
|
|
assert commands.take(imei, "original") is None
|
|
assert "diagnostic_imei" not in observation.get(request["observation_id"])
|
|
# Same request ID is a lookup, even after a restart; no second toggle.
|
|
commands = Commands(store)
|
|
commands.sessions[imei] = {"reconnected"}
|
|
assert commands.submit(request)["state"] == "uncertain"
|
|
assert commands.take(imei, "reconnected") is None
|
|
with pytest.raises(ValueError, match="observation already used"):
|
|
commands.submit({**request, "id": "f" * 32})
|
|
|
|
|
|
def test_diagnostic_probe_expired_lease_and_changed_request_are_rejected(store, monkeypatch):
|
|
from ndc_vps import observation as module
|
|
from ndc_vps.commands import Commands
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
commands.sessions[imei] = {"original"}
|
|
observer = module.Observation(store)
|
|
request = {
|
|
"id": "a" * 32, "imei": imei, "model": 231, "firmware": "0.01",
|
|
"kind": "probe-diagnostic-mode", "observation_id": "b" * 32,
|
|
}
|
|
lease = observer.arm({"id": request["observation_id"]})
|
|
monkeypatch.setattr(module.time, "time", lambda: lease["expires_at"] + 1)
|
|
with pytest.raises(ValueError, match="observation unavailable"):
|
|
commands.submit(request)
|
|
|
|
|
|
def test_delivery_deadline_covers_kernel_and_asyncio_buffers(store, monkeypatch):
|
|
from ndc_vps import delivery
|
|
|
|
class Socket:
|
|
def setsockopt(self, *args):
|
|
pass
|
|
|
|
class Writer:
|
|
def __init__(self):
|
|
self.transport = self
|
|
self.data = []
|
|
self.kernel = 0
|
|
self.buffer = 0
|
|
self.closed = False
|
|
|
|
def get_extra_info(self, name):
|
|
return Socket()
|
|
|
|
def write(self, data):
|
|
self.data.append(data)
|
|
self.kernel += len(data)
|
|
|
|
def get_write_buffer_size(self):
|
|
return self.buffer
|
|
|
|
def is_closing(self):
|
|
return self.closed
|
|
|
|
def abort(self):
|
|
self.closed = True
|
|
self.buffer = self.kernel = 0
|
|
|
|
async def exercise():
|
|
for kernel, buffer in ((12, 0), (0, 12), (5, 7)):
|
|
writer = Writer()
|
|
monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel)
|
|
guard = delivery.Delivery(writer)
|
|
guard.write(b"c" * 12, time.monotonic() + 0.03)
|
|
writer.kernel, writer.buffer = kernel, buffer
|
|
await asyncio.sleep(0.06)
|
|
assert writer.closed and writer.kernel == writer.buffer == 0
|
|
|
|
# An ACK for the command releases its deadline even with a newer ACK
|
|
# or command queued behind it. Later writes cannot extend its lifetime.
|
|
writer = Writer()
|
|
monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel)
|
|
guard = delivery.Delivery(writer)
|
|
guard.write(b"header")
|
|
guard.write(b"first", time.monotonic() + 0.03)
|
|
guard.write(b"second", time.monotonic() + 1)
|
|
writer.kernel = len(b"second")
|
|
guard.check()
|
|
await asyncio.sleep(0.06)
|
|
assert not writer.closed
|
|
guard.abort()
|
|
assert guard.timer is None
|
|
|
|
writer = Writer()
|
|
monkeypatch.setattr(delivery, "queued_bytes", lambda sock, writer=writer: writer.kernel)
|
|
guard = delivery.Delivery(writer)
|
|
guard.write(b"first", time.monotonic() + 0.03)
|
|
guard.write(b"second", time.monotonic() + 1)
|
|
await asyncio.sleep(0.06)
|
|
assert writer.closed
|
|
|
|
writer = Writer()
|
|
guard = delivery.Delivery(writer)
|
|
monkeypatch.setattr(delivery, "queued_bytes", lambda sock: writer.kernel)
|
|
assert guard.ready()
|
|
writer.buffer = 1
|
|
assert not guard.ready()
|
|
writer.buffer, writer.kernel = 0, 1
|
|
assert not guard.ready()
|
|
writer.kernel = 0
|
|
assert guard.ready()
|
|
with pytest.raises(TimeoutError):
|
|
guard.write(b"expired", time.monotonic() - 1)
|
|
assert not writer.data and writer.closed
|
|
|
|
asyncio.run(exercise())
|
|
|
|
|
|
def test_transport_expiry_never_replays_or_claims_device_confirmation(store, monkeypatch):
|
|
from ndc_vps.commands import Commands
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
commands.sessions[imei] = {"old"}
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"kind": "request-position",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
}
|
|
queued = commands.submit(body)
|
|
data, deadline = commands.take_delivery(imei, "old")
|
|
assert data and 0 < deadline - time.monotonic() <= 30
|
|
assert commands.get(body["id"])["state"] == "dispatched"
|
|
commands.sessions[imei] = {"new"}
|
|
assert commands.take_delivery(imei, "new") is None
|
|
monkeypatch.setattr(time, "time", lambda: queued["expires_at"] + 1)
|
|
assert commands.get(body["id"])["state"] == "unconfirmed"
|
|
assert commands.take_delivery(imei, "new") is None
|
|
assert commands.submit(body)["state"] == "unconfirmed"
|
|
recovered = Commands(store)
|
|
recovered.sessions[imei] = {"new"}
|
|
assert recovered.get(body["id"])["state"] == "unconfirmed"
|
|
assert recovered.take_delivery(imei, "new") is None
|
|
|
|
|
|
def package(timestamp=None, lat=55.1, lon=37.2):
|
|
tags = (
|
|
b"\x03"
|
|
+ struct.pack("<f", lat)
|
|
+ b"\x04"
|
|
+ struct.pack("<f", lon)
|
|
+ b"\x05\x0a\x19\x88\x02"
|
|
)
|
|
data = struct.pack("<I", int(timestamp or time.time())) + tags
|
|
return b"[\x01\x01" + struct.pack("<H", len(tags)) + data + bytes([sum(data) % 256]) + b"]"
|
|
|
|
|
|
@pytest.fixture
|
|
def store(tmp_path):
|
|
src = tmp_path / "src"
|
|
shutil.copytree(ROOT / "apps/vps-host/ndc_vps", src / "ndc_vps")
|
|
shutil.copyfile(
|
|
ROOT / "src/k1link/device_plugins/arnavi_b2/internal.py", src / "ndc_vps/arnavi.py"
|
|
)
|
|
for name in ("usb_protocol.py", "web_protocol.py", "sim_network.py"):
|
|
shutil.copyfile(ROOT / "src/k1link/device_plugins/arnavi_b2" / name, src / "ndc_vps" / name)
|
|
sys.path.insert(0, str(src))
|
|
module = importlib.import_module("ndc_vps.store")
|
|
root = tmp_path / "state"
|
|
root.mkdir(mode=0o700)
|
|
(root / "host.json").write_text(
|
|
json.dumps(
|
|
{
|
|
"host_id": "vps_" + "a" * 64,
|
|
"fingerprint": "a" * 64,
|
|
"endpoint": "https://example.org:19443",
|
|
"api_port": 19443,
|
|
"tracker": {"host": "example.org", "port": 9922},
|
|
}
|
|
)
|
|
)
|
|
result = module.Store(root)
|
|
yield result
|
|
sys.path.remove(str(src))
|
|
for key in list(sys.modules):
|
|
if key == "ndc_vps" or key.startswith("ndc_vps."):
|
|
sys.modules.pop(key)
|
|
|
|
|
|
def test_decoder_fragmentation_checksum_and_acks():
|
|
raw = package()
|
|
for n in range(len(raw)):
|
|
assert internal.parse_package(raw[:n]) is None
|
|
size, packets = internal.parse_package(raw)
|
|
assert size == len(raw)
|
|
assert packets[0]["position"]["satellites"] == 16
|
|
assert packets[0]["position"]["longitude"] == pytest.approx(37.2)
|
|
assert internal.package_ack(1) == b"{\x00\x01}"
|
|
assert internal.header_ack(1) == b"{\x04\x00\x01\x01\x00\x00\x00}"
|
|
damaged = bytearray(raw)
|
|
damaged[-2] ^= 1
|
|
with pytest.raises(ValueError):
|
|
internal.parse_package(bytes(damaged))
|
|
assert internal.parse_package(package(lat=float("nan")))[1][0]["position"] is None
|
|
assert internal.parse_package(package(lat=0, lon=0))[1][0]["position"] is None
|
|
|
|
|
|
def test_one_use_invitation_and_idempotent_owner_retry(store):
|
|
store.invitation()
|
|
code = (store.root / "connect.key").read_text().strip()[5:]
|
|
value = json.loads(base64.urlsafe_b64decode(code + "=" * (-len(code) % 4)))
|
|
body = {"core_id": "core_" + "b" * 64, "token": "T" * 43, "secret": value["secret"]}
|
|
assert store.pair(body)["host_id"].startswith("vps_")
|
|
assert store.pair(body)["host_id"].startswith("vps_")
|
|
assert store.authorize("T" * 43)
|
|
assert not store.authorize("t" * 43)
|
|
with pytest.raises(PermissionError):
|
|
store.pair({**body, "token": "X" * 43})
|
|
with pytest.raises(ValueError):
|
|
store.invitation()
|
|
assert "MCV1." not in (store.root / "connect.key").read_text()
|
|
|
|
|
|
def test_journal_ack_then_retransmit_and_removed_identity(store):
|
|
raw = package()
|
|
imei = "123456789012345"
|
|
with pytest.raises(PermissionError):
|
|
store.append(imei, raw, internal.parse_package(raw)[1])
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
store.append(imei, raw, internal.parse_package(raw)[1])
|
|
store.append(imei, raw, internal.parse_package(raw)[1])
|
|
rows = store.fetch(0)["items"]
|
|
assert len(rows) == 1
|
|
assert base64.b64decode(rows[0]["raw"]) == raw
|
|
store.acknowledge(rows[0]["id"])
|
|
store.append(imei, raw, internal.parse_package(raw)[1])
|
|
assert store.fetch(0)["items"] == []
|
|
store.set_devices([])
|
|
assert store.admitted(imei) is None
|
|
|
|
|
|
def test_tcp_partial_frames_actual_ack_after_durable_commit(store):
|
|
from ndc_vps.service import Service
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
|
|
async def exercise():
|
|
service = Service(store)
|
|
server = await asyncio.start_server(service.tracker, "127.0.0.1", 0)
|
|
async with server:
|
|
reader, writer = await asyncio.open_connection(
|
|
"127.0.0.1", server.sockets[0].getsockname()[1]
|
|
)
|
|
writer.write(b"\xff\x23" + int(imei).to_bytes(8, "little"))
|
|
await writer.drain()
|
|
assert (await reader.readexactly(9))[0] == 0x7B
|
|
raw = package()
|
|
for part in (raw[:7], raw[7:]):
|
|
writer.write(part)
|
|
await writer.drain()
|
|
assert await reader.readexactly(4) == b"{\x00\x01}"
|
|
assert len(store.fetch(0)["items"]) == 1
|
|
writer.close()
|
|
await writer.wait_closed()
|
|
|
|
asyncio.run(exercise())
|
|
|
|
|
|
def test_core_cursor_and_position_order_are_one_transaction(tmp_path):
|
|
class Equipment:
|
|
vehicle = "rover-a"
|
|
|
|
def listing(self, vehicle=None):
|
|
return [{"id": "c" * 32, "name": "B2", "vehicle_id": self.vehicle}]
|
|
|
|
eq = Equipment()
|
|
hosts = VPSHosts(tmp_path, "core", eq)
|
|
row = {
|
|
"id": "vps_test",
|
|
"name": "VPS",
|
|
"state": "paired",
|
|
"cursor": 0,
|
|
"vehicle_ids": ["rover-a", "rover-b"],
|
|
"last_sync_at": time.time(),
|
|
}
|
|
hosts.save(row)
|
|
now = int(time.time())
|
|
|
|
def item(seq, measured):
|
|
raw = package(measured)
|
|
return {
|
|
"id": seq,
|
|
"instance_id": "c" * 32,
|
|
"received_at": time.time(),
|
|
"raw": base64.b64encode(raw).decode(),
|
|
"digest": hashlib.sha256(raw).hexdigest(),
|
|
}
|
|
|
|
hosts.ingest(row, [item(1, now), item(2, now - 86400)], [{"id": "c" * 32}])
|
|
assert hosts.rows()[0]["cursor"] == 2
|
|
|
|
status = hosts.telemetry()[0]
|
|
assert status["online"] and status["position_fresh"]
|
|
assert status["position"]["measured_at"] == now
|
|
eq.vehicle = "rover-b"
|
|
assert hosts.telemetry()[0]["position"] is not None # one shared host, reassigned tracker
|
|
eq.vehicle = "rover-c"
|
|
assert hosts.telemetry()[0]["position"] is None
|
|
with pytest.raises(ValueError):
|
|
hosts.ingest(row, [item(3, now), {**item(4, now), "raw": "!!"}], [{"id": "c" * 32}])
|
|
assert hosts.rows()[0]["cursor"] == 2
|
|
|
|
eq.vehicle = "rover-a"
|
|
row["state"] = "replaced"
|
|
hosts.save(row)
|
|
replaced_status = hosts.telemetry()[0]
|
|
assert replaced_status["position"] is None
|
|
assert not replaced_status["online"]
|
|
|
|
|
|
def test_firewall_migration_preserves_legacy_and_refuses_foreign_rollback(tmp_path, monkeypatch):
|
|
import importlib.util
|
|
from types import SimpleNamespace
|
|
|
|
spec = importlib.util.spec_from_file_location(
|
|
"vps_firewall_test", ROOT / "apps/vps-host/firewall.py"
|
|
)
|
|
firewall = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(firewall)
|
|
config, fragment, backup = (
|
|
tmp_path / "nftables.conf",
|
|
tmp_path / "d/host.nft",
|
|
tmp_path / "before.json",
|
|
)
|
|
original = "table inet nodedc_b2_vps { chain input { policy drop; } }\n"
|
|
config.write_text(original)
|
|
for name, value in [("CONFIG", config), ("FRAGMENT", fragment), ("BACKUP", backup)]:
|
|
monkeypatch.setattr(firewall, name, value)
|
|
calls = []
|
|
|
|
def run(*args, **kwargs):
|
|
calls.append((args, kwargs.get("input")))
|
|
return SimpleNamespace(
|
|
stdout=json.dumps(
|
|
{"nftables": [{"chain": {"policy": "drop", "hook": "input"}}]}
|
|
).encode()
|
|
)
|
|
|
|
monkeypatch.setattr(firewall, "run", run)
|
|
|
|
def atomic(path, data, mode=0o600):
|
|
path.write_bytes(data)
|
|
|
|
before = firewall.plan()
|
|
assert firewall.apply(before, 19443, 9922, atomic)
|
|
assert original.strip() in config.read_text()
|
|
assert "19443" in fragment.read_text() and "9922" in fragment.read_text()
|
|
assert all(b"flush" not in (payload or b"") for _, payload in calls)
|
|
assert not firewall.apply(firewall.plan(), 19443, 9922, atomic)
|
|
installed = config.read_text()
|
|
config.write_text(installed + "# owner edit\n")
|
|
with pytest.raises(ValueError):
|
|
firewall.rollback(atomic)
|
|
config.write_text(installed)
|
|
firewall.rollback(atomic)
|
|
assert config.read_text() == original
|
|
assert not fragment.exists()
|
|
|
|
|
|
def test_tls_identity_checked_before_credentials(monkeypatch):
|
|
from k1link.fleet import vps_transport
|
|
from k1link.fleet.trust import PairingError
|
|
|
|
requests = []
|
|
|
|
class Socket:
|
|
def getpeercert(self, binary_form=False):
|
|
return b"wrong certificate"
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
class Context:
|
|
def wrap_socket(self, raw, **kwargs):
|
|
return raw
|
|
|
|
class Connection:
|
|
def __init__(self, *args, **kwargs):
|
|
self.sock = None
|
|
|
|
def request(self, *args, **kwargs):
|
|
requests.append(args)
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
monkeypatch.setattr(vps_transport, "destination", lambda _: ("example.org", 19443, "1.1.1.1"))
|
|
monkeypatch.setattr(vps_transport, "connect", lambda *args: Socket())
|
|
monkeypatch.setattr(vps_transport.ssl, "SSLContext", lambda _: Context())
|
|
monkeypatch.setattr(vps_transport.http.client, "HTTPConnection", Connection)
|
|
with pytest.raises(PairingError, match="Идентичность"):
|
|
vps_transport.request(
|
|
{
|
|
"endpoint": "https://example.org:19443",
|
|
"fingerprint": "a" * 64,
|
|
"token": "synthetic",
|
|
},
|
|
"POST",
|
|
"/v1/pair",
|
|
{"secret": "synthetic"},
|
|
)
|
|
assert requests == []
|
|
|
|
|
|
def test_release_reproducibility_and_decoder_source_closure(tmp_path):
|
|
import importlib.util
|
|
import tarfile
|
|
|
|
spec = importlib.util.spec_from_file_location("vps_builder", ROOT / "scripts/build_vps_host.py")
|
|
builder = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(builder)
|
|
first, second = tmp_path / "first.tar", tmp_path / "second.tar"
|
|
builder.build(first)
|
|
builder.build(second)
|
|
assert first.read_bytes() == second.read_bytes()
|
|
with tarfile.open(first) as release:
|
|
manifest = json.load(release.extractfile("ndc-mission-vps/manifest.json"))
|
|
for name, digest in manifest["files"].items():
|
|
assert (
|
|
hashlib.sha256(release.extractfile("ndc-mission-vps/" + name).read()).hexdigest()
|
|
== digest
|
|
)
|
|
assert (
|
|
release.extractfile("ndc-mission-vps/ndc_vps/arnavi.py").read()
|
|
== (ROOT / "src/k1link/device_plugins/arnavi_b2/internal.py").read_bytes()
|
|
)
|
|
|
|
|
|
def test_network_read_command_at_most_once_and_restart(store):
|
|
from ndc_vps.commands import Commands, frame
|
|
|
|
commands = Commands(store)
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
body = {"id": "d" * 32, "imei": imei, "password": "123456", "kind": "read-settings"}
|
|
assert commands.submit(body)["state"] == "queued"
|
|
assert "payload" not in commands.submit(body)
|
|
assert commands.take(imei) == frame("123456*GETP")
|
|
assert commands.take(imei) is None
|
|
commands = Commands(store)
|
|
assert commands.get(body["id"])["state"] == "uncertain"
|
|
assert commands.take(imei) is None
|
|
with pytest.raises(ValueError):
|
|
commands.submit({**body, "password": "654321"})
|
|
with pytest.raises(ValueError):
|
|
commands.submit({**body, "id": "e" * 32, "kind": "restart"})
|
|
|
|
|
|
def test_network_reply_is_evidence_not_applied_settings(store):
|
|
from ndc_vps.commands import Commands
|
|
|
|
commands = Commands(store)
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
body = {"id": "d" * 32, "imei": imei, "password": "123456", "kind": "read-settings"}
|
|
commands.submit(body)
|
|
commands.take(imei)
|
|
reply = b"#1=example.org,9922"
|
|
data = struct.pack("<I", int(time.time())) + reply
|
|
raw = b"[\x01\x03" + struct.pack("<H", len(reply)) + data + bytes([sum(data) % 256]) + b"]"
|
|
internal.parse_package(raw)
|
|
commands.receive(imei, raw)
|
|
assert commands.get(body["id"])["state"] == "reply_received"
|
|
assert commands.get(body["id"])["replies"] == [reply.decode()]
|
|
|
|
|
|
def test_reinstalled_host_requires_explicit_replacement_and_keeps_history(tmp_path, monkeypatch):
|
|
from k1link.fleet import vps_hosts
|
|
from k1link.fleet.trust import PairingError
|
|
|
|
hosts = VPSHosts(tmp_path, "core", None)
|
|
old = {
|
|
"id": "vps_old",
|
|
"endpoint": "https://example.org:19443",
|
|
"state": "paired",
|
|
"revision": 1,
|
|
"name": "old",
|
|
"vehicle_ids": ["rover-a"],
|
|
}
|
|
hosts.save(old)
|
|
monkeypatch.setattr(
|
|
vps_hosts,
|
|
"invitation",
|
|
lambda _: {"host_id": "vps_new", "endpoint": old["endpoint"], "secret": "synthetic"},
|
|
)
|
|
monkeypatch.setattr(
|
|
vps_hosts,
|
|
"request",
|
|
lambda *args: {"host_id": "vps_new", "schema": "missioncore.vps-host/v1"},
|
|
)
|
|
with pytest.raises(PairingError, match="переустановлен"):
|
|
hosts.pair("synthetic", "replacement", ["rover-a"])
|
|
assert hosts.listing()[0]["id"] == "vps_old"
|
|
result = hosts.pair("synthetic", "replacement", ["rover-a"], replaces_id="vps_old")
|
|
assert result["state"] == "paired"
|
|
assert len(hosts.listing()) == 1
|
|
assert len(hosts.rows()) == 2
|
|
assert hosts.rows()[0]["state"] == "replaced"
|
|
|
|
|
|
def text_package(reply, at):
|
|
raw = reply.encode("ascii")
|
|
data = struct.pack("<I", int(at)) + raw
|
|
return b"[\x01\x03" + struct.pack("<H", len(raw)) + data + bytes([sum(data) % 256]) + b"]"
|
|
|
|
|
|
def test_remote_primary_server_requires_fresh_readback_and_preserves_secondary(store, monkeypatch):
|
|
from ndc_vps import commands as module
|
|
from ndc_vps.commands import Commands, frame
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr(module.time, "time", lambda: now[0])
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
command = Commands(store)
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"password": "123456",
|
|
"kind": "configure-server1",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"expected": {"host": "old.example", "port": 9922},
|
|
"target": {"host": "new.example", "port": 9922},
|
|
}
|
|
before = (
|
|
"#1=old.example,9922,0,0,#2=private,,#5=15,15,10,15#7=private,,#26=example.org,9922,0,0,"
|
|
)
|
|
after = before.replace("old.example", "new.example")
|
|
command.submit(body)
|
|
assert command.take(imei, "session-a") == frame("123456*GETP")
|
|
command.receive(imei, text_package(before, now[0] - 60), "session-a")
|
|
command.receive(imei, text_package(before, now[0]), "session-b")
|
|
assert command.get(body["id"])["stage"] == "preflight"
|
|
command.receive(imei, text_package(before, now[0]), "session-a")
|
|
assert command.get(body["id"])["stage"] == "write"
|
|
assert command.take(imei, "session-b") is None
|
|
assert command.take(imei, "session-a") == frame("123456*SETP*#1=new.example,9922")
|
|
assert command.take(imei, "session-a") is None
|
|
now[0] += 1
|
|
acknowledgement = text_package(after, now[0])
|
|
command.receive(imei, acknowledgement, "session-a")
|
|
assert command.get(body["id"])["state"] == "queued"
|
|
now[0] += 16
|
|
assert command.take(imei, "session-a") == frame("123456*GETP")
|
|
command.receive(imei, acknowledgement, "session-a") # queued/retransmitted SETP reply
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
command.receive(imei, text_package(after, now[0]), "session-a")
|
|
result = command.get(body["id"])
|
|
assert result["state"] == "verified" and result["server1"] == body["target"]
|
|
assert all(k not in result for k in ("password", "payload", "before", "after", "session"))
|
|
assert "private" not in json.dumps(result)
|
|
assert command.submit(body) == result # retry cannot issue another write
|
|
|
|
|
|
@pytest.mark.parametrize("fault", ["secondary", "primary", "restart", "other_setting", "expire"])
|
|
def test_remote_write_failure_never_claims_verified(store, monkeypatch, fault):
|
|
from ndc_vps import commands as module
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr(module.time, "time", lambda: now[0])
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
command = Commands(store)
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"password": "123456",
|
|
"kind": "configure-server1",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"expected": {"host": "old.example", "port": 9922},
|
|
"target": {"host": "new.example", "port": 9922},
|
|
}
|
|
before = "#1=old.example,9922,0,0,#2=a,,#5=15#7=b,,#26=example.org,9922,0,0,"
|
|
if fault == "secondary":
|
|
before = before.replace("#26=example.org", "#26=other.example")
|
|
if fault == "primary":
|
|
before = before.replace("old.example", "changed.example")
|
|
command.submit(body)
|
|
command.take(imei)
|
|
command.receive(imei, text_package(before, now[0]))
|
|
if fault in ("secondary", "primary"):
|
|
assert command.get(body["id"])["state"] == "rejected"
|
|
assert command.take(imei) is None
|
|
return
|
|
if fault == "restart":
|
|
command = Commands(store)
|
|
assert command.get(body["id"])["state"] == "uncertain"
|
|
assert command.take(imei) is None
|
|
return
|
|
command.take(imei)
|
|
if fault == "expire":
|
|
now[0] += 121
|
|
assert command.get(body["id"])["state"] == "unconfirmed"
|
|
assert command.take(imei) is None
|
|
return
|
|
after = before.replace("old.example", "new.example").replace("#5=15", "#5=99")
|
|
now[0] += 1
|
|
command.receive(imei, text_package(after, now[0]))
|
|
now[0] += 16
|
|
command.take(imei)
|
|
command.receive(imei, text_package(after, now[0]))
|
|
assert command.get(body["id"])["state"] == "uncertain"
|
|
|
|
|
|
def test_write_reconnect_or_lost_ack_only_retries_independent_read(store, monkeypatch):
|
|
from ndc_vps import commands as module
|
|
from ndc_vps.commands import Commands, frame
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr(module.time, "time", lambda: now[0])
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"password": "123456",
|
|
"kind": "configure-server1",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"expected": {"host": "old.example", "port": 9922},
|
|
"target": {"host": "new.example", "port": 9922},
|
|
}
|
|
before = "#1=old.example,9922,0,0,#2=a,,#5=15#7=b,,#26=example.org,9922,0,0,"
|
|
commands.submit(body)
|
|
commands.take(imei, "before-reconnect")
|
|
commands.receive(imei, text_package(before, now[0] - 4), "before-reconnect")
|
|
assert commands.take(imei, "before-reconnect") == frame("123456*SETP*#1=new.example,9922")
|
|
now[0] += 16
|
|
assert commands.take(imei, "new-connection") == frame("123456*GETP")
|
|
assert commands.take(imei, "new-connection") is None
|
|
commands.receive(
|
|
imei,
|
|
text_package(before.replace("old.example", "new.example"), now[0] - 4),
|
|
"new-connection",
|
|
)
|
|
assert commands.get(body["id"])["state"] == "verified"
|
|
|
|
|
|
def test_configuration_observation_is_disabled_bounded_and_has_no_public_raw_data(
|
|
store, monkeypatch
|
|
):
|
|
from ndc_vps.observation import Observation
|
|
|
|
capture = Observation(store)
|
|
assert capture.claim() is None
|
|
lease = capture.arm({"id": "e" * 32})
|
|
assert capture.arm({"id": "e" * 32})["expires_at"] == lease["expires_at"]
|
|
with pytest.raises(ValueError, match="already armed"):
|
|
capture.arm({"id": "f" * 32})
|
|
for n in range(4):
|
|
ticket = capture.claim()
|
|
assert ticket == ("e" * 32, n)
|
|
capture.finish(ticket, b"private-device-exchange", [])
|
|
assert capture.claim() is None
|
|
public = capture.get("e" * 32)
|
|
assert len(public["captures"]) == 4
|
|
assert "private-device-exchange" not in json.dumps(public)
|
|
monkeypatch.setattr("ndc_vps.observation.time.time", lambda: lease["expires_at"] + 1)
|
|
assert capture.claim() is None
|
|
assert capture.arm({"id": "f" * 32})["id"] == "f" * 32
|
|
|
|
|
|
def test_unknown_protocol_observation_sends_no_response_and_keeps_internal_service(store):
|
|
from ndc_vps.service import Service
|
|
|
|
async def check():
|
|
service = Service(store)
|
|
service.observation.arm({"id": "f" * 32})
|
|
reader = asyncio.StreamReader()
|
|
reader.feed_data(b"private-body")
|
|
reader.feed_eof()
|
|
await service.observe_configuration(reader, b"GET /conf ")
|
|
result = service.observation.get("f" * 32)
|
|
assert result["captures"][0]["bytes"] == 22
|
|
assert result["captures"][0]["state"] == "captured"
|
|
|
|
asyncio.run(check())
|
|
|
|
|
|
def reference_exchange(imei="123456789012345"):
|
|
request = (
|
|
b"[\x01\x00\x10" + int(imei).to_bytes(8, "little") + bytes.fromhex("0001e702000006025d")
|
|
)
|
|
response = bytes.fromhex("5b00030006025d")
|
|
http = (
|
|
b"POST /c/index.php HTTP/1.1\r\nHost: example.org:9922\r\nContent-Length: 21\r\n\r\n"
|
|
+ request
|
|
)
|
|
return {"request": request.hex(), "response": response.hex()}, http
|
|
|
|
|
|
def test_configuration_download_is_exact_documented_text_and_rejects_arbitrary_fields(store):
|
|
from ndc_vps.actions import frame, prepare
|
|
from ndc_vps.commands import frame as text_frame
|
|
|
|
body = {
|
|
"id": "b" * 32,
|
|
"imei": "123456789012345",
|
|
"kind": "download-configuration",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"password": "654321",
|
|
}
|
|
assert frame(prepare(body)) == text_frame("654321*SERV*1.8")
|
|
for addition in ({"encoding": "binary"}, {"text": "SERV*1.6"}, {"firmware": "0.05"}):
|
|
with pytest.raises(ValueError):
|
|
prepare({**body, **addition})
|
|
|
|
|
|
def test_observation_reference_exact_match_one_shot_restart_and_private_projection(store):
|
|
from ndc_vps.observation import Observation
|
|
|
|
store.set_devices([{"imei": "123456789012345", "instance_id": "c" * 32}])
|
|
reference, http = reference_exchange()
|
|
observer = Observation(store)
|
|
lease = {"id": "a" * 32, "reference": reference}
|
|
assert "reference" not in observer.arm(lease)
|
|
assert "reference" not in observer.arm(lease)
|
|
with pytest.raises(ValueError, match="idempotency"):
|
|
observer.arm({"id": lease["id"]})
|
|
ticket = observer.claim()
|
|
for n in range(len(http)):
|
|
assert observer.reply(ticket, http[:n]) is None
|
|
assert observer.reply(ticket, http[:-2] + b"\x03]") is None
|
|
assert observer.reply(ticket, http) == bytes.fromhex(reference["response"])
|
|
assert observer.reply(ticket, http) is None
|
|
restarted = Observation(store)
|
|
assert restarted.reply(restarted.claim(), http) is None
|
|
assert "reply_dispatched_at" in restarted.get(lease["id"])
|
|
assert reference["request"] not in json.dumps(restarted.get(lease["id"]))
|
|
|
|
|
|
def test_observation_settings_reply_validated_and_close_retains_evidence(store):
|
|
from ndc_vps.observation import Observation
|
|
from ndc_vps.usb_protocol import Configuration, Setting
|
|
from ndc_vps.web_protocol import settings_reply
|
|
|
|
store.set_devices([{"imei": "123456789012345", "instance_id": "c" * 32}])
|
|
ref, _ = reference_exchange()
|
|
request = bytes.fromhex(ref["request"])
|
|
request = request[:2] + b"\x00\x0f" + request[4:18] + b"\x02]"
|
|
raw = settings_reply(Configuration((Setting(62, b"\x00\x96"),)))
|
|
observer = Observation(store)
|
|
body = {"id": "d" * 32, "reference": {"request": request.hex(), "response": raw.hex()}}
|
|
observer.arm(body)
|
|
ticket = observer.claim()
|
|
observer.finish(ticket, b"private", [])
|
|
observer.close(body["id"])
|
|
assert observer.claim() is None
|
|
assert observer.get(body["id"])["captures"][0]["bytes"] == 7
|
|
observer.arm({"id": "e" * 32})
|
|
|
|
|
|
def test_observation_reference_rejects_other_commands_unadmitted_and_expired(store, monkeypatch):
|
|
from ndc_vps.observation import Observation, http_body
|
|
|
|
reference, http = reference_exchange()
|
|
observer = Observation(store)
|
|
body = {"id": "a" * 32, "reference": reference}
|
|
with pytest.raises(ValueError, match="unqualified"):
|
|
observer.arm(body)
|
|
store.set_devices([{"imei": "123456789012345", "instance_id": "c" * 32}])
|
|
with pytest.raises(ValueError, match="unqualified"):
|
|
observer.arm({**body, "reference": {**reference, "response": "5b00040006025d"}})
|
|
lease = observer.arm(body)
|
|
ticket = observer.claim()
|
|
for extra in (b"Content-Length: 21\r\n", b"Transfer-Encoding: chunked\r\n"):
|
|
assert http_body(http.replace(b"Host: ", extra + b"Host: ")) is None
|
|
assert http_body(http.replace(b"POST /c/index.php", b"GET /c/index.php")) is None
|
|
store.set_devices([])
|
|
assert observer.reply(ticket, http) is None
|
|
store.set_devices([{"imei": "123456789012345", "instance_id": "c" * 32}])
|
|
monkeypatch.setattr("ndc_vps.observation.time.time", lambda: lease["expires_at"] + 1)
|
|
assert observer.reply(ticket, http) is None
|
|
|
|
|
|
def test_configuration_upload_is_allowlisted_active_session_no_replay_and_not_fake_confirmed(store):
|
|
from ndc_vps.commands import Commands, frame
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
body = {
|
|
"id": "b" * 32,
|
|
"imei": imei,
|
|
"kind": "upload-configuration",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"password": "123456",
|
|
}
|
|
with pytest.raises(ValueError, match="active session"):
|
|
commands.submit(body)
|
|
commands.sessions[imei] = {"session-a"}
|
|
commands.session_activity[imei, "session-a"] = time.monotonic()
|
|
with pytest.raises(ValueError, match="unknown action"):
|
|
commands.submit({**body, "command": "1.6"})
|
|
receipt = commands.submit(body)
|
|
assert "123456" not in json.dumps(receipt)
|
|
assert commands.take(imei, "session-a") == frame("123456*SERV*1.9")
|
|
assert commands.take(imei, "session-a") is None
|
|
commands.receive(imei, text_package("SERV OK", time.time()), "session-a")
|
|
assert commands.get(body["id"])["state"] == "dispatched"
|
|
restarted = Commands(store)
|
|
assert restarted.get(body["id"])["state"] == "uncertain"
|
|
assert restarted.take(imei, "session-a") is None
|
|
|
|
|
|
def test_reference_reply_service_captures_followup_without_a_second_reply(store):
|
|
from ndc_vps.service import Service
|
|
|
|
async def check():
|
|
store.set_devices([{"imei": "123456789012345", "instance_id": "c" * 32}])
|
|
service = Service(store)
|
|
reference, http = reference_exchange()
|
|
service.observation.arm({"id": "c" * 32, "reference": reference})
|
|
reader = asyncio.StreamReader()
|
|
reader.feed_data(http[10:])
|
|
writes = []
|
|
|
|
class Writer:
|
|
def write(self, data):
|
|
writes.append(data)
|
|
reader.feed_data(b"private-followup")
|
|
reader.feed_eof()
|
|
|
|
async def drain(self):
|
|
pass
|
|
|
|
await service.observe_configuration(reader, http[:10], Writer())
|
|
assert len(writes) == 1
|
|
assert writes[0].partition(b"\r\n\r\n")[2] == bytes.fromhex(reference["response"])
|
|
with store.db() as db:
|
|
raw = db.execute("SELECT raw FROM observation_data").fetchone()[0]
|
|
assert raw == http + b"private-followup"
|
|
assert service.observation.get("c" * 32)["captures"][0]["state"] == "captured"
|
|
|
|
asyncio.run(check())
|
|
|
|
|
|
def test_fresh_connection_wins_over_half_open_predecessor_without_duplicate_command(store):
|
|
from ndc_vps.commands import Commands
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
commands.sessions[imei] = {"old", "new"}
|
|
commands.session_activity.update({(imei, "old"): 100, (imei, "new"): 110})
|
|
body = {
|
|
"id": "d" * 32,
|
|
"imei": imei,
|
|
"kind": "request-position",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
}
|
|
commands.submit(body)
|
|
assert commands.take(imei, "old") is None
|
|
assert commands.get(body["id"])["state"] == "queued"
|
|
assert commands.take(imei, "new") is not None
|
|
assert commands.take(imei, "old") is None
|
|
assert commands.take(imei, "new") is None
|
|
|
|
|
|
def test_unacknowledged_prefix_cannot_steal_command_from_drained_session(store):
|
|
from ndc_vps.commands import Commands
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
commands = Commands(store)
|
|
commands.sessions[imei] = {"drained", "fresher"}
|
|
commands.session_activity.update({(imei, "drained"): 100, (imei, "fresher"): 110})
|
|
commands.session_ready.update({(imei, "drained"): False, (imei, "fresher"): False})
|
|
body = {
|
|
"id": "d" * 32,
|
|
"imei": imei,
|
|
"kind": "request-position",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
}
|
|
original = commands.submit(body)
|
|
assert commands.take(imei, "drained") is None
|
|
assert commands.take(imei, "fresher") is None
|
|
assert commands.get(body["id"])["state"] == "queued"
|
|
commands.session_ready[imei, "drained"] = True
|
|
assert commands.take(imei, "fresher") is None
|
|
assert commands.take(imei, "drained") is not None
|
|
assert commands.get(body["id"])["expires_at"] == original["expires_at"]
|
|
commands.session_ready[imei, "fresher"] = True
|
|
assert commands.take(imei, "fresher") is None # never replay on the recovered stream
|
|
assert commands.get(body["id"])["state"] == "dispatched"
|
|
|
|
|
|
@pytest.mark.parametrize("last_input", [None, 94.999, 101.0])
|
|
def test_configuration_waits_for_recent_input_without_consuming_dispatch(
|
|
full_context, monkeypatch, last_input
|
|
):
|
|
command, body, _, _, _, _ = full_context
|
|
imei = body["imei"]
|
|
monkeypatch.setattr("ndc_vps.commands.time.monotonic", lambda: 100.0)
|
|
command.session_activity.pop((imei, "live"))
|
|
if last_input is not None:
|
|
command.session_activity[imei, "live"] = last_input
|
|
original = command.submit(body)
|
|
assert command.take(imei, "live") is None
|
|
assert command.get(body["id"])["state"] == "queued"
|
|
command.session_activity[imei, "live"] = 100.0
|
|
assert command.take(imei, "live") is not None
|
|
assert command.get(body["id"])["expires_at"] == original["expires_at"]
|
|
assert command.take(imei, "live") is None
|
|
|
|
|
|
def test_configuration_silent_stream_expires_without_any_dispatch(full_context, monkeypatch):
|
|
command, body, _, _, _, now = full_context
|
|
monkeypatch.setattr("ndc_vps.commands.time.monotonic", lambda: 100.0)
|
|
command.session_activity[body["imei"], "live"] = 90.0
|
|
original = command.submit(body)
|
|
assert command.take(body["imei"], "live") is None
|
|
now[0] = original["expires_at"] + 1
|
|
command.session_activity[body["imei"], "live"] = 100.0
|
|
assert command.take(body["imei"], "live") is None
|
|
result = command.get(body["id"])
|
|
assert result["state"] == "expired" and "dispatched_at" not in result
|
|
|
|
|
|
@pytest.fixture
|
|
def full_context(store, monkeypatch):
|
|
from ndc_vps.commands import Commands
|
|
from ndc_vps.usb_protocol import Configuration, Setting
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
command = Commands(store)
|
|
command.sessions[imei] = {"live"}
|
|
command.session_activity[imei, "live"] = time.monotonic()
|
|
command.session_peers[imei, "live"] = "192.0.2.1"
|
|
before = Configuration(
|
|
tuple(
|
|
Setting(n, v)
|
|
for n, v in (
|
|
(3, b"example.org"),
|
|
(4, b"\x26\xc2"),
|
|
(5, b"123456"),
|
|
(8, b"\x00"),
|
|
(70, b"example.org"),
|
|
(71, b"\x26\xc2"),
|
|
(25, b"\x00\x0f"),
|
|
(222, b"unknown\xff"),
|
|
)
|
|
)
|
|
)
|
|
target = Configuration(
|
|
tuple(Setting(r.number, b"\x00\x10" if r.number == 25 else r.value) for r in before.records)
|
|
)
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"kind": "configure-all",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"password": "123456",
|
|
"expected_sha256": hashlib.sha256(before.encode()).hexdigest(),
|
|
"target_configuration": target.encode().hex(),
|
|
}
|
|
|
|
def wire(operation, payload=b""):
|
|
raw = (
|
|
int(imei).to_bytes(8, "little")
|
|
+ bytes.fromhex("0001e7020000")
|
|
+ bytes([operation])
|
|
+ payload
|
|
)
|
|
return b"[\x01" + len(raw).to_bytes(2, "big") + raw + b"]"
|
|
|
|
return command, body, before, target, wire, now
|
|
|
|
|
|
def test_full_configuration_preflight_single_write_and_independent_verified_readback(full_context):
|
|
from ndc_vps.commands import frame
|
|
from ndc_vps.web_protocol import decode_settings_reply
|
|
|
|
command, body, before, target, wire, now = full_context
|
|
command.submit(body)
|
|
assert command.take(body["imei"], "live") == frame("123456*SERV*1.9")
|
|
assert command.web_receive(wire(5, before.encode()), "192.0.2.2") is None
|
|
assert command.get(body["id"])["stage"] == "preflight"
|
|
assert command.web_receive(wire(6, b"\x02"), "192.0.2.1") == bytes.fromhex("5b00030006025d")
|
|
assert command.web_receive(wire(5, before.encode()), "192.0.2.1") == bytes.fromhex(
|
|
"5b00030005015d"
|
|
)
|
|
assert command.take(body["imei"], "live") is None
|
|
now[0] += 3
|
|
assert command.take(body["imei"], "live") is None
|
|
now[0] += 13
|
|
assert command.take(body["imei"], "live") == frame("123456*SERV*1.8")
|
|
reply = command.web_receive(wire(2), "192.0.2.1")
|
|
assert decode_settings_reply(reply).encode() == target.encode()
|
|
assert command.web_receive(wire(2), "192.0.2.1") is None
|
|
assert command.get(body["id"])["state"] == "queued"
|
|
now[0] += 16
|
|
assert command.take(body["imei"], "live") == frame("123456*SERV*1.9")
|
|
command.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
result = command.get(body["id"])
|
|
assert result["state"] == "verified" and result["configuration"] == target.encode().hex()
|
|
assert all(
|
|
k not in result
|
|
for k in ("password", "target_configuration", "before_configuration", "payload")
|
|
)
|
|
|
|
|
|
def test_settings_image_transport_deadline_cannot_outlive_operation(full_context):
|
|
command, body, before, target, wire, now = full_context
|
|
queued = command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] = queued["expires_at"] - 1
|
|
command.take(body["imei"], "live")
|
|
reply, deadline = command.web_receive(wire(2), "192.0.2.1", with_deadline=True)
|
|
assert reply and 0 < deadline - time.monotonic() <= 1
|
|
assert command.web_receive(wire(2), "192.0.2.1", with_deadline=True) is None
|
|
now[0] += 2
|
|
assert command.get(body["id"])["state"] == "uncertain"
|
|
|
|
|
|
def test_full_configuration_stale_predecessor_rejected_without_write(full_context):
|
|
command, body, before, target, wire, now = full_context
|
|
command.submit({**body, "expected_sha256": "0" * 64})
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
assert command.get(body["id"])["state"] == "rejected"
|
|
assert command.web_receive(wire(2), "192.0.2.1") is None
|
|
|
|
|
|
def test_full_configuration_timeout_after_write_is_uncertain_and_restart_does_not_replay(
|
|
full_context,
|
|
):
|
|
from ndc_vps.commands import Commands
|
|
|
|
command, body, before, target, wire, now = full_context
|
|
command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 16
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(2), "192.0.2.1")
|
|
restarted = Commands(command.store)
|
|
assert restarted.get(body["id"])["state"] == "queued"
|
|
now[0] += 200
|
|
assert command.get(body["id"])["state"] == "uncertain"
|
|
assert restarted.take(body["imei"], "live") is None
|
|
|
|
|
|
@pytest.mark.parametrize("readback_dispatched", [False, True])
|
|
@pytest.mark.parametrize("observed", ["target", "before", "different"])
|
|
def test_configuration_crash_resumes_only_readback_with_original_identity_and_deadline(
|
|
full_context, readback_dispatched, observed
|
|
):
|
|
from ndc_vps.commands import Commands, frame
|
|
from ndc_vps.usb_protocol import Configuration, Setting
|
|
|
|
command, body, before, target, wire, now = full_context
|
|
accepted = command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 16
|
|
command.take(body["imei"], "live")
|
|
assert command.web_receive(wire(2), "192.0.2.1")
|
|
if readback_dispatched:
|
|
now[0] += 16
|
|
assert command.take(body["imei"], "live") == frame("123456*SERV*1.9")
|
|
restarted = Commands(command.store)
|
|
pending = restarted.submit(body)
|
|
assert pending["state"] == "queued" and pending["stage"] == "verify"
|
|
assert pending["recovery_count"] == 1 and pending["recovery_verification"]
|
|
assert pending["id"] == accepted["id"] and pending["expires_at"] == accepted["expires_at"]
|
|
restarted.sessions[body["imei"]] = {"new"}
|
|
restarted.session_peers[body["imei"], "new"] = "192.0.2.1"
|
|
restarted.session_activity[body["imei"], "new"] = time.monotonic()
|
|
assert restarted.web_receive(wire(2), "192.0.2.1") is None
|
|
assert restarted.take(body["imei"], "new") is None # original/recovery pacing
|
|
now[0] += 16
|
|
assert restarted.take(body["imei"], "new") == frame("123456*SERV*1.9")
|
|
assert restarted.take(body["imei"], "new") is None
|
|
assert restarted.web_receive(wire(2), "192.0.2.1") is None
|
|
actual = {"target": target, "before": before}.get(observed)
|
|
if actual is None:
|
|
actual = Configuration(
|
|
tuple(
|
|
Setting(r.number, b"\x00\x11" if r.number == 25 else r.value)
|
|
for r in before.records
|
|
)
|
|
)
|
|
restarted.web_receive(wire(5, actual.encode()), "192.0.2.1")
|
|
result = restarted.get(body["id"])
|
|
assert (
|
|
result["state"]
|
|
== {"target": "verified", "before": "not_applied", "different": "uncertain"}[observed]
|
|
)
|
|
assert result["configuration"] == actual.encode().hex()
|
|
assert Commands(command.store).get(body["id"]) == result
|
|
|
|
|
|
@pytest.mark.parametrize("new_connection", [False, True])
|
|
def test_b2_reconnect_can_resume_only_readback_on_a_new_connection(full_context, new_connection):
|
|
from ndc_vps.commands import frame
|
|
|
|
command, body, before, target, wire, now = full_context
|
|
accepted = command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 16
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(2), "192.0.2.1")
|
|
now[0] += 16
|
|
command.take(body["imei"], "live")
|
|
with command.store.db() as db:
|
|
saved = json.loads(
|
|
db.execute("SELECT body FROM commands WHERE id=?", (body["id"],)).fetchone()[0]
|
|
)
|
|
key = body["imei"], "reconnected"
|
|
command.sessions[body["imei"]].add(key[1]) # old TCP stream is still half-open
|
|
command.session_started[key] = saved["monotonic"] + (1 if new_connection else -1)
|
|
command.session_activity[key] = time.monotonic()
|
|
command.session_peers[key] = "192.0.2.1"
|
|
assert command.take(*key) is None
|
|
now[0] += 16
|
|
if new_connection:
|
|
assert command.take(*key) == frame("123456*SERV*1.9")
|
|
assert command.web_receive(wire(2), "192.0.2.1") is None
|
|
command.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
assert command.get(body["id"])["state"] == "verified"
|
|
else:
|
|
assert command.take(*key) is None
|
|
assert "recovery_count" not in command.get(body["id"])
|
|
assert command.get(body["id"])["expires_at"] == accepted["expires_at"]
|
|
|
|
|
|
def test_expired_configuration_recovery_never_reopens_or_extends_deadline(full_context):
|
|
from ndc_vps.commands import Commands
|
|
|
|
command, body, before, _, wire, now = full_context
|
|
accepted = command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 16
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(2), "192.0.2.1")
|
|
for _ in range(2):
|
|
command = Commands(command.store)
|
|
assert command.get(body["id"])["recovery_count"] == 2
|
|
now[0] = accepted["expires_at"] + 1
|
|
command = Commands(command.store)
|
|
result = command.get(body["id"])
|
|
assert result["state"] == "uncertain"
|
|
assert result["expires_at"] == accepted["expires_at"]
|
|
assert result["recovery_count"] == 2
|
|
assert command.take(body["imei"], "new") is None
|
|
|
|
|
|
def test_full_read_crc_failure_and_unrelated_text_never_confirm_settings(full_context):
|
|
command, body, before, target, wire, now = full_context
|
|
body = {k: v for k, v in body.items() if k not in ("expected_sha256", "target_configuration")}
|
|
body["kind"] = "read-configuration"
|
|
command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.receive(body["imei"], text_package("SERV OK", now[0]), "live")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
with pytest.raises(ValueError):
|
|
command.web_receive(wire(5, before.encode()[:-1] + b"!"), "192.0.2.1")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
assert command.get(body["id"])["state"] == "observed"
|
|
|
|
|
|
@pytest.mark.parametrize("peer", ["192.0.2.1", "192.0.2.2"])
|
|
def test_configuration_http_fragmentation_keepalive_and_active_peer(
|
|
full_context, peer, monkeypatch
|
|
):
|
|
from ndc_vps.service import Service
|
|
from ndc_vps.web_protocol import time_reply
|
|
|
|
monkeypatch.setattr("ndc_vps.delivery.queued_bytes", lambda sock: 0)
|
|
command, body, before, target, wire, now = full_context
|
|
body = {k: v for k, v in body.items() if k not in ("expected_sha256", "target_configuration")}
|
|
body["kind"] = "read-configuration"
|
|
|
|
async def check():
|
|
service = Service(command.store)
|
|
service.commands = command
|
|
command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
reader = asyncio.StreamReader()
|
|
replies = []
|
|
|
|
class Writer:
|
|
closed = False
|
|
|
|
@property
|
|
def transport(self):
|
|
return self
|
|
|
|
def get_extra_info(self, name):
|
|
if name == "socket":
|
|
return self
|
|
return peer, 12345
|
|
|
|
def setsockopt(self, *args):
|
|
pass
|
|
|
|
def get_write_buffer_size(self):
|
|
return 0
|
|
|
|
def is_closing(self):
|
|
return self.closed
|
|
|
|
def abort(self):
|
|
self.closed = True
|
|
|
|
def write(self, value):
|
|
replies.append(value.partition(b"\r\n\r\n")[2])
|
|
|
|
async def drain(self):
|
|
pass
|
|
|
|
def close(self):
|
|
self.closed = True
|
|
|
|
writer = Writer()
|
|
raw = b""
|
|
for data in (wire(6, b"\x02"), wire(5, before.encode()), wire(7)):
|
|
raw += (
|
|
b"POST /c/index.php HTTP/1.1\r\n"
|
|
+ f"Content-Length: {len(data)}\r\n\r\n".encode()
|
|
+ data
|
|
)
|
|
|
|
async def feed():
|
|
for offset in range(0, len(raw), 7):
|
|
reader.feed_data(raw[offset : offset + 7])
|
|
await asyncio.sleep(0)
|
|
reader.feed_eof()
|
|
|
|
await asyncio.gather(service.tracker(reader, writer), feed())
|
|
assert writer.closed and service.connections == 0
|
|
assert replies == (
|
|
[
|
|
bytes.fromhex("5b00030006025d"),
|
|
bytes.fromhex("5b00030005015d"),
|
|
time_reply(int(now[0])),
|
|
]
|
|
if peer == "192.0.2.1"
|
|
else []
|
|
)
|
|
assert command.get(body["id"])["state"] == (
|
|
"observed" if peer == "192.0.2.1" else "dispatched"
|
|
)
|
|
|
|
asyncio.run(check())
|
|
|
|
|
|
def test_token_actions_expire_offline_do_not_replay_and_require_exact_confirmation(
|
|
store, monkeypatch
|
|
):
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
command = Commands(store)
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
body = {
|
|
"id": "d" * 32,
|
|
"imei": imei,
|
|
"kind": "pulse-output",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"pin": 4,
|
|
"seconds": 2,
|
|
}
|
|
with pytest.raises(ValueError, match="no active session"):
|
|
command.submit(body)
|
|
command.sessions[imei] = {"session-a"}
|
|
command.submit(body)
|
|
assert command.take(imei, "different") is None
|
|
raw = command.take(imei, "session-a")
|
|
assert raw[2] == 255 and raw[4] == 255 and raw[-5:-1] == b"\x18\x04\x00\x02"
|
|
token = raw[5:9]
|
|
assert command.take(imei, "session-a") is None
|
|
assert "token" not in command.get(body["id"])
|
|
|
|
def reply(value, code=0):
|
|
data = struct.pack("<I", int(now[0])) + bytes((code,)) + value
|
|
return b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]"
|
|
|
|
command.receive(imei, reply(token), "different")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
command.receive(imei, reply(bytes(x ^ 255 for x in token)), "session-a")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
command.receive(imei, reply(token, 6), "session-a")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
command.receive(imei, reply(token), "session-a")
|
|
assert command.get(body["id"])["state"] == "device_confirmed"
|
|
body["id"] = "e" * 32
|
|
command.submit(body)
|
|
now[0] += 4
|
|
assert command.take(imei, "session-a") is None
|
|
assert command.get(body["id"])["state"] == "expired"
|
|
body["id"] = "f" * 32
|
|
command.submit(body)
|
|
restarted = Commands(store)
|
|
assert restarted.take(imei, "session-a") is None
|
|
assert restarted.get(body["id"])["state"] == "expired"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"changes",
|
|
[{"pin": 0}, {"seconds": 60}, {"seconds": True}, {"raw": "0107"}, {"firmware": "0.05"}],
|
|
)
|
|
def test_action_validation_never_accepts_arbitrary_commands(store, changes):
|
|
from ndc_vps.actions import prepare
|
|
|
|
with pytest.raises(ValueError):
|
|
prepare(
|
|
{
|
|
"id": "d" * 32,
|
|
"imei": "123456789012345",
|
|
"kind": "pulse-output",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"pin": 4,
|
|
"seconds": 2,
|
|
**changes,
|
|
}
|
|
)
|
|
|
|
|
|
def test_text_pulse_uses_b2_serv_format_without_fabricating_confirmation(store, monkeypatch):
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
command = Commands(store)
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
command.sessions[imei] = {"session-a"}
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"kind": "pulse-output",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"pin": 5,
|
|
"seconds": 5,
|
|
"encoding": "text",
|
|
"password": "123456",
|
|
}
|
|
result = command.submit(body)
|
|
assert "password" not in result and "binary" not in result
|
|
assert command.take(imei, "different-session") is None
|
|
raw = command.take(imei, "session-a")
|
|
payload = b"123456*SERV*24.5.0.5"
|
|
assert raw == bytes((0x7B, len(payload), 0xFC, sum(payload) % 256)) + payload + b"}"
|
|
assert command.take(imei, "session-a") is None
|
|
# An unrelated valid token reply must neither crash nor confirm a text pulse.
|
|
data = struct.pack("<I", int(now[0])) + b"\x00\x01\x02\x03\x04"
|
|
reply = b"[\x01\x09\x05\0" + data + bytes((sum(data) % 256,)) + b"]"
|
|
command.receive(imei, reply, "session-a")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
assert command.submit(body)["state"] == "dispatched"
|
|
now[0] += 31
|
|
assert command.get(body["id"])["state"] == "unconfirmed"
|
|
assert "123456" not in json.dumps(command.get(body["id"]))
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"changes",
|
|
[
|
|
{"password": None},
|
|
{"password": "12345"},
|
|
{"password": "123456*SERV*1.7"},
|
|
{"encoding": "raw"},
|
|
{"seconds": 6},
|
|
{"text": "anything"},
|
|
{"pin": True},
|
|
],
|
|
)
|
|
def test_text_pulse_rejects_invalid_or_unbounded_payloads(store, changes):
|
|
from ndc_vps.actions import prepare
|
|
|
|
with pytest.raises(ValueError):
|
|
prepare(
|
|
{
|
|
"kind": "pulse-output",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"pin": 5,
|
|
"seconds": 5,
|
|
"encoding": "text",
|
|
"password": "123456",
|
|
**changes,
|
|
}
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("pin", [4, 5, 6])
|
|
@pytest.mark.parametrize("enabled", [False, True])
|
|
def test_explicit_output_state_is_private_session_bound_and_never_replayed(
|
|
store, monkeypatch, pin, enabled
|
|
):
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
command = Commands(store)
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
body = {
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"kind": "set-output",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"pin": pin,
|
|
"enabled": enabled,
|
|
"password": "654321",
|
|
}
|
|
with pytest.raises(ValueError, match="no active session"):
|
|
command.submit(body)
|
|
command.sessions[imei] = {"session-a"}
|
|
command.submit(body)
|
|
assert command.take(imei, "new-session") is None
|
|
payload = f"654321*SERV*8.{pin}.{int(enabled)}".encode()
|
|
expected = bytes((0x7B, len(payload), 0xFC, sum(payload) % 256)) + payload + b"}"
|
|
assert command.take(imei, "session-a") == expected
|
|
command.receive(imei, text_package("SERV OK", now[0]), "session-a")
|
|
assert command.submit(body)["state"] == "dispatched"
|
|
assert command.take(imei, "session-a") is None
|
|
with pytest.raises(ValueError, match="idempotency conflict"):
|
|
command.submit({**body, "enabled": not enabled})
|
|
assert "654321" not in json.dumps(command.get(body["id"]))
|
|
restarted = Commands(store)
|
|
assert restarted.take(imei, "session-a") is None
|
|
assert restarted.get(body["id"])["state"] == "uncertain"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"changes",
|
|
[
|
|
{"pin": True},
|
|
{"pin": 7},
|
|
{"enabled": 1},
|
|
{"enabled": "false"},
|
|
{"enabled": None},
|
|
{"password": "123456*SERV*1.7"},
|
|
{"password": None},
|
|
{"encoding": "binary"},
|
|
{"seconds": 2},
|
|
{"raw": "080400"},
|
|
{"firmware": "0.05"},
|
|
],
|
|
)
|
|
def test_explicit_output_state_rejects_ambiguous_or_arbitrary_payloads(store, changes):
|
|
from ndc_vps.actions import prepare
|
|
|
|
with pytest.raises(ValueError):
|
|
prepare(
|
|
{
|
|
"kind": "set-output",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"pin": 6,
|
|
"enabled": False,
|
|
"password": "654321",
|
|
**changes,
|
|
}
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def restart_context(store, monkeypatch):
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
monkeypatch.setattr("ndc_vps.commands.time.monotonic", lambda: now[0] - 1700000000)
|
|
command = Commands(store)
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
body = {"id": "d" * 32, "imei": imei, "kind": "restart", "model": 231, "firmware": "0.01"}
|
|
command.sessions[imei] = {"old-a", "old-b"}
|
|
command.session_started[imei, "old-a"] = now[0] - 1700000000 - 10
|
|
command.session_started[imei, "old-b"] = now[0] - 1700000000 - 5
|
|
command.submit(body)
|
|
raw = command.take(imei, "old-a")
|
|
assert raw[2] == 255 and raw[-3:-1] == b"\x01\x07"
|
|
return command, body, now, raw[5:9]
|
|
|
|
|
|
def test_restart_ack_is_not_return_and_fresh_new_session_is_required(restart_context):
|
|
command, body, now, token = restart_context
|
|
data = struct.pack("<I", int(now[0])) + b"\0" + token
|
|
reply = b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]"
|
|
command.receive(body["imei"], reply, "old-a")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
assert command.get(body["id"])["device_code"] == 0
|
|
now[0] += 2
|
|
command.session_started[body["imei"], "new"] = now[0] - 1700000000
|
|
now[0] += 10
|
|
command.receive(body["imei"], package(timestamp=now[0]), "new")
|
|
result = command.get(body["id"])
|
|
assert result["state"] == "reconnected" and result["reconnect_seconds"] == 12
|
|
assert command.submit(body) == result and command.take(body["imei"], "new") is None
|
|
assert (
|
|
not {"token", "binary", "restart_sessions", "allowed_sessions", "session"} & result.keys()
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"mode", ["old-a", "old-b", "unregistered", "early-session", "archive", "future", "text", "late"]
|
|
)
|
|
def test_restart_does_not_confuse_receipt_archive_or_previous_session_with_return(
|
|
restart_context, mode
|
|
):
|
|
command, body, now, _ = restart_context
|
|
initial = now[0]
|
|
now[0] += 20
|
|
session = mode if mode in ("old-a", "old-b", "unregistered") else "new"
|
|
if mode != "unregistered" and session == "new":
|
|
command.session_started[body["imei"], session] = (
|
|
initial - 1700000000 + (-1 if mode == "early-session" else 1)
|
|
)
|
|
raw = package(
|
|
timestamp=initial - 30 if mode == "archive" else now[0] + 60 if mode == "future" else now[0]
|
|
)
|
|
if mode == "text":
|
|
raw = text_package("SERV OK", now[0])
|
|
if mode == "late":
|
|
now[0] += 200
|
|
command.receive(body["imei"], raw, session)
|
|
assert command.get(body["id"])["state"] == ("unconfirmed" if mode == "late" else "dispatched")
|
|
assert command.take(body["imei"], session) is None
|
|
|
|
|
|
def test_restart_service_crash_never_replays_or_completes_on_later_reconnect(restart_context):
|
|
from ndc_vps.commands import Commands
|
|
|
|
command, body, now, _ = restart_context
|
|
resumed = Commands(command.store)
|
|
now[0] += 10
|
|
resumed.sessions[body["imei"]] = {"new"}
|
|
resumed.session_started[body["imei"], "new"] = now[0] - 1700000000 - 1
|
|
resumed.receive(body["imei"], package(timestamp=now[0]), "new")
|
|
assert resumed.get(body["id"])["state"] == "uncertain"
|
|
assert resumed.take(body["imei"], "new") is None
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"changes", [{"password": "123456"}, {"pin": 5}, {"firmware": "0.02"}, {"command": "1.6"}]
|
|
)
|
|
def test_restart_is_narrow_and_rejects_extra_command_fields(store, changes):
|
|
from ndc_vps.actions import prepare
|
|
|
|
with pytest.raises(ValueError):
|
|
prepare(
|
|
{
|
|
"id": "d" * 32,
|
|
"imei": "123456789012345",
|
|
"kind": "restart",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
**changes,
|
|
}
|
|
)
|
|
|
|
|
|
def test_binary_configuration_upload_is_documented_read_only_and_narrow(store):
|
|
from ndc_vps.actions import frame, prepare
|
|
|
|
body = {"kind": "upload-configuration", "model": 231, "firmware": "0.01", "encoding": "binary"}
|
|
raw = frame(prepare(body))
|
|
assert raw[2] == 255 and raw[-3:-1] == b"\x01\x09"
|
|
with pytest.raises(ValueError):
|
|
prepare({**body, "kind": "download-configuration"})
|
|
with pytest.raises(ValueError):
|
|
prepare({**body, "payload": "arbitrary"})
|
|
|
|
|
|
@pytest.mark.parametrize("command", [1, 2])
|
|
def test_no_image_response_is_exact_and_once_in_scoped_observation(store, command):
|
|
from ndc_vps.observation import Observation
|
|
from ndc_vps.web_protocol import decode_request
|
|
|
|
store.set_devices([{"imei": "123456789012345", "instance_id": "c" * 32}])
|
|
ref, _ = reference_exchange()
|
|
raw = bytes.fromhex(ref["request"])
|
|
raw = raw[:2] + b"\x00\x0f" + raw[4:18] + bytes([command, 93])
|
|
assert decode_request(raw)[1] == command
|
|
observer = Observation(store)
|
|
response = b"[\x00\x02\x00" + bytes([command, 93])
|
|
body = {"id": "d" * 32, "reference": {"request": raw.hex(), "response": response.hex()}}
|
|
observer.arm(body)
|
|
ticket = observer.claim()
|
|
http = b"POST /c/index.php HTTP/1.1\r\nContent-Length: 20\r\n\r\n" + raw
|
|
observer.finish(ticket, http, [])
|
|
assert observer.reply(ticket, http) == response
|
|
assert observer.reply(ticket, http) is None
|
|
observer.close(body["id"])
|
|
with pytest.raises(ValueError):
|
|
observer.arm(
|
|
{
|
|
"id": "e" * 32,
|
|
"reference": {
|
|
**body["reference"],
|
|
"response": (b"[\x00\x03\x00" + bytes([command, 0, 93])).hex(),
|
|
},
|
|
}
|
|
)
|
|
|
|
|
|
def test_observation_numeric_identity_reply_is_bounded_and_never_accepts_an_image(store):
|
|
from ndc_vps.observation import Observation
|
|
|
|
store.set_devices([{"imei": "123456789012345", "instance_id": "c" * 32}])
|
|
ref, _ = reference_exchange()
|
|
raw = bytes.fromhex(ref["request"])
|
|
raw = raw[:2] + b"\x00\x0f" + raw[4:18] + b"\x01]"
|
|
reply = bytes.fromhex("5b00060001000123455d")
|
|
observer = Observation(store)
|
|
body = {"id": "d" * 32, "reference": {"request": raw.hex(), "response": reply.hex()}}
|
|
observer.arm(body)
|
|
ticket = observer.claim()
|
|
http = b"POST /c/index.php HTTP/1.1\r\nContent-Length: 20\r\n\r\n" + raw
|
|
observer.finish(ticket, http, [])
|
|
assert observer.reply(ticket, http) == reply
|
|
assert observer.reply(ticket, http) is None
|
|
observer.close(body["id"])
|
|
for response in (reply[:-1], reply + b"image", bytes.fromhex("5b00060001000000005d")):
|
|
with pytest.raises(ValueError):
|
|
observer.arm(
|
|
{"id": "e" * 32, "reference": {**body["reference"], "response": response.hex()}}
|
|
)
|
|
|
|
|
|
def test_numeric_identity_is_stable_scoped_and_survives_legacy_admission(store):
|
|
item = {"imei": "123456789012345", "instance_id": "c" * 32, "device_id": 74565}
|
|
store.set_devices([item])
|
|
assert store.numeric_id(item["imei"]) == 74565
|
|
store.set_devices([{k: v for k, v in item.items() if k != "device_id"}])
|
|
assert store.numeric_id(item["imei"]) == 74565
|
|
with pytest.raises(ValueError, match="conflict"):
|
|
store.set_devices([{**item, "device_id": 74566}])
|
|
assert store.numeric_id(item["imei"]) == 74565
|
|
store.set_devices([])
|
|
assert store.numeric_id(item["imei"]) is None
|
|
store.set_devices([item])
|
|
assert store.numeric_id(item["imei"]) == 74565
|
|
|
|
|
|
@pytest.mark.parametrize("number", [0, -1, 2**32, True, "74565", 1.5, None])
|
|
def test_numeric_identity_rejects_invalid_admission_without_losing_devices(store, number):
|
|
item = {"imei": "123456789012345", "instance_id": "c" * 32, "device_id": 74565}
|
|
store.set_devices([item])
|
|
with pytest.raises(ValueError):
|
|
store.set_devices([{**item, "device_id": number}])
|
|
assert store.numeric_id(item["imei"]) == 74565
|
|
|
|
|
|
def test_startup_identity_and_empty_settings_do_not_complete_or_write_configuration(full_context):
|
|
command, body, before, target, wire, now = full_context
|
|
assert command.web_receive(wire(1), "192.0.2.1") is None
|
|
command.store.set_devices([{"imei": body["imei"], "instance_id": "c" * 32, "device_id": 74565}])
|
|
assert command.web_receive(wire(1), "192.0.2.2") is None
|
|
assert command.web_receive(wire(1), "192.0.2.1") == bytes.fromhex("5b00060001000123455d")
|
|
command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
assert command.web_receive(wire(2), "192.0.2.1") is None
|
|
value = command.get(body["id"])
|
|
assert value["state"] == "dispatched" and value["stage"] == "preflight"
|
|
assert "write_reply_sent_at" not in value and "configuration" not in value
|
|
command.store.set_devices([])
|
|
assert command.web_receive(wire(1), "192.0.2.1") is None
|
|
|
|
|
|
def test_configuration_clock_reply_is_fresh_admitted_and_does_not_advance_write(full_context):
|
|
from ndc_vps.web_protocol import time_reply
|
|
|
|
command, body, before, target, wire, now = full_context
|
|
assert command.web_receive(wire(7), "192.0.2.2") is None
|
|
first, deadline = command.web_receive(wire(7), "192.0.2.1", with_deadline=True)
|
|
assert first == time_reply(int(now[0]))
|
|
assert deadline > 0
|
|
command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
before_clock = command.get(body["id"])
|
|
assert before_clock["stage"] == "write" and before_clock["state"] == "queued"
|
|
now[0] += 1
|
|
assert command.web_receive(wire(7), "192.0.2.1") == time_reply(int(now[0])) != first
|
|
assert command.get(body["id"]) == before_clock
|
|
command.store.set_devices([])
|
|
assert command.web_receive(wire(7), "192.0.2.1") is None
|
|
|
|
|
|
def test_core_admits_only_independently_observed_numeric_id(tmp_path, monkeypatch):
|
|
from k1link.fleet import vps_hosts
|
|
|
|
hosts = VPSHosts(tmp_path, "core", None)
|
|
devices = [
|
|
{"id": "a" * 32, "identity_key": "123456789012345", "observed": {"device_id": "74565"}},
|
|
{"id": "b" * 32, "identity_key": "223456789012345", "observed": {}},
|
|
]
|
|
monkeypatch.setattr(hosts, "devices", lambda row: devices)
|
|
monkeypatch.setattr(hosts, "ingest", lambda *args: 0)
|
|
monkeypatch.setattr(hosts, "save", lambda row: None)
|
|
calls = []
|
|
|
|
def call(host, method, path, body=None):
|
|
calls.append((path, body))
|
|
return {"items": []}
|
|
|
|
monkeypatch.setattr(vps_hosts, "request", call)
|
|
hosts.sync({"cursor": 0})
|
|
items = calls[0][1]["items"]
|
|
assert items[0]["device_id"] == 74565
|
|
assert "device_id" not in items[1]
|
|
assert set(items[0]) == {"imei", "instance_id", "device_id"}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"readback_kind, expected_state", [("unchanged", "not_applied"), ("partial", "uncertain")]
|
|
)
|
|
def test_full_configuration_ignored_or_partial_write_is_never_success_or_replayed(
|
|
full_context, readback_kind, expected_state
|
|
):
|
|
"""A delivered image and SERV OK are insufficient when readback disagrees.
|
|
|
|
The bench accepted the trajectory control but returned the old image for
|
|
polling-interval changes. Preserve this failure contract without a real
|
|
configuration, identity, credential or invented device reply fixture.
|
|
"""
|
|
from ndc_vps.commands import Commands
|
|
from ndc_vps.usb_protocol import Configuration, Setting
|
|
|
|
command, body, before, target, wire, now = full_context
|
|
command.submit(body)
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
now[0] += 16
|
|
command.take(body["imei"], "live")
|
|
delivered = command.web_receive(wire(2), "192.0.2.1")
|
|
assert delivered is not None
|
|
command.receive(body["imei"], text_package("SERV OK", now[0]), "live")
|
|
assert command.get(body["id"])["state"] == "queued"
|
|
# Even a matching unsolicited upload before the independent read must not
|
|
# complete the write or turn its ACK into settings verification.
|
|
command.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
assert command.get(body["id"])["state"] == "queued"
|
|
now[0] += 16
|
|
command.take(body["imei"], "live")
|
|
readback = before
|
|
if readback_kind == "partial":
|
|
readback = Configuration(
|
|
tuple(
|
|
Setting(r.number, b"different-unknown" if r.number == 222 else r.value)
|
|
for r in target.records
|
|
)
|
|
)
|
|
command.web_receive(wire(5, readback.encode()), "192.0.2.1")
|
|
receipt = command.get(body["id"])
|
|
assert receipt["state"] == expected_state
|
|
assert receipt["configuration"] == readback.encode().hex()
|
|
assert receipt["configuration_sha256"] == hashlib.sha256(readback.encode()).hexdigest()
|
|
assert command.submit(body) == receipt # a lost-response retry is a read
|
|
assert command.web_receive(wire(2), "192.0.2.1") is None
|
|
assert command.take(body["imei"], "live") is None
|
|
# Neither a later uncorrelated upload nor a service restart changes the
|
|
# recorded outcome, and neither can replay the original settings image.
|
|
command.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
assert command.get(body["id"]) == receipt
|
|
restarted = Commands(command.store)
|
|
assert restarted.get(body["id"]) == receipt
|
|
assert restarted.take(body["imei"], "live") is None
|
|
|
|
|
|
@pytest.fixture
|
|
def sim_context(full_context, monkeypatch):
|
|
from ndc_vps.usb_protocol import Configuration, Setting
|
|
|
|
command, body, before, _, wire, now = full_context
|
|
monkeypatch.setattr("ndc_vps.commands.time.monotonic", lambda: now[0] - 1700000000)
|
|
before = Configuration(before.records + (Setting(72, (2072).to_bytes(4, "big")),))
|
|
target = Configuration(
|
|
tuple(
|
|
Setting(r.number, (2072 | (1 << 10)).to_bytes(4, "big") if r.number == 72 else r.value)
|
|
for r in before.records
|
|
)
|
|
)
|
|
body.update(
|
|
kind="select-sim",
|
|
sim_slot=2,
|
|
expected_sha256=hashlib.sha256(before.encode()).hexdigest(),
|
|
target_configuration=target.encode().hex(),
|
|
)
|
|
return command, body, before, target, wire, now
|
|
|
|
|
|
def reach_sim_restart(context, unchanged=False):
|
|
command, body, before, target, wire, now = context
|
|
if unchanged:
|
|
body["expected_sha256"] = hashlib.sha256(target.encode()).hexdigest()
|
|
before = target
|
|
command.submit(body)
|
|
command.session_activity[body["imei"], "live"] = time.monotonic()
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, before.encode()), "192.0.2.1")
|
|
if not unchanged:
|
|
now[0] += 16
|
|
command.session_activity[body["imei"], "live"] = time.monotonic()
|
|
command.take(body["imei"], "live")
|
|
assert command.web_receive(wire(2), "192.0.2.1")
|
|
now[0] += 16
|
|
command.session_activity[body["imei"], "live"] = time.monotonic()
|
|
command.take(body["imei"], "live")
|
|
command.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
assert command.get(body["id"])["state"] == "queued"
|
|
assert command.get(body["id"])["stage"] == "restart"
|
|
|
|
|
|
def sim_packet(timestamp, slot=2, gsm=4):
|
|
tags = bytes([99]) + ((gsm << 2) | ((slot - 1) << 5) | (1 << 6) | (1 << 9)).to_bytes(
|
|
4, "little"
|
|
)
|
|
data = int(timestamp).to_bytes(4, "little") + tags
|
|
return b"[\x01\x01\x05\0" + data + bytes([sum(data) % 256]) + b"]"
|
|
|
|
|
|
@pytest.mark.parametrize("unchanged", [False, True])
|
|
def test_sim_switch_only_completes_after_new_session_target_sim_gprs(sim_context, unchanged):
|
|
command, body, _, target, wire, now = sim_context
|
|
reach_sim_restart(sim_context, unchanged)
|
|
raw = command.take(body["imei"], "live")
|
|
assert raw[-3:-1] == b"\x01\x07"
|
|
assert command.take(body["imei"], "live") is None
|
|
command.web_receive(wire(5, target.encode()), "192.0.2.1")
|
|
assert command.get(body["id"])["state"] == "dispatched"
|
|
now[0] += 2
|
|
command.session_started[body["imei"], "new"] = now[0] - 1700000000
|
|
now[0] += 50
|
|
command.receive(body["imei"], sim_packet(now[0]), "new")
|
|
result = command.get(body["id"])
|
|
assert result["state"] == "sim_selected" and result["active_sim"] == 2
|
|
assert result["reconnect_seconds"] == 52
|
|
assert command.submit(body) == result
|
|
assert not {"binary", "token", "password", "restart_sessions"} & result.keys()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"mode",
|
|
[
|
|
"old-session",
|
|
"early-session",
|
|
"no-session",
|
|
"archive",
|
|
"future",
|
|
"wrong-sim",
|
|
"no-gprs",
|
|
"no-ds2",
|
|
"late",
|
|
],
|
|
)
|
|
def test_sim_switch_rejects_insufficient_telemetry(sim_context, mode):
|
|
command, body, _, _, _, now = sim_context
|
|
reach_sim_restart(sim_context)
|
|
command.take(body["imei"], "live")
|
|
dispatched = now[0]
|
|
now[0] += 20
|
|
session = "live" if mode == "old-session" else "new"
|
|
if mode != "no-session":
|
|
command.session_started[body["imei"], session] = (
|
|
dispatched - 1700000000 + (-1 if mode == "early-session" else 1)
|
|
)
|
|
stamp = dispatched - 30 if mode == "archive" else now[0] + 60 if mode == "future" else now[0]
|
|
raw = sim_packet(stamp, slot=1 if mode == "wrong-sim" else 2, gsm=3 if mode == "no-gprs" else 4)
|
|
if mode == "no-ds2":
|
|
raw = package(timestamp=now[0])
|
|
if mode == "late":
|
|
now[0] += 400
|
|
command.receive(body["imei"], raw, session)
|
|
assert command.get(body["id"])["state"] == ("uncertain" if mode == "late" else "dispatched")
|
|
|
|
|
|
@pytest.mark.parametrize("dispatch", [False, True])
|
|
def test_sim_switch_service_restart_never_replays_modem_restart(sim_context, dispatch):
|
|
from ndc_vps.commands import Commands
|
|
|
|
command, body, _, _, _, _ = sim_context
|
|
reach_sim_restart(sim_context)
|
|
if dispatch:
|
|
command.take(body["imei"], "live")
|
|
restored = Commands(command.store)
|
|
assert restored.get(body["id"])["state"] == "uncertain"
|
|
assert restored.take(body["imei"], "live") is None
|
|
|
|
|
|
@pytest.mark.parametrize("slot", [True, 0, 3, "2", 1])
|
|
def test_sim_selection_rejects_invalid_slot_and_disagreeing_flags(sim_context, slot):
|
|
command, body, *_ = sim_context
|
|
with pytest.raises(ValueError):
|
|
command.submit({**body, "sim_slot": slot})
|
|
|
|
|
|
def test_offline_read_waits_across_host_restart_but_never_replays_after_dispatch(
|
|
store, monkeypatch
|
|
):
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
body = {
|
|
"id": "e" * 32,
|
|
"imei": imei,
|
|
"kind": "request-position",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"not_after": now[0] + 25,
|
|
}
|
|
command = Commands(store)
|
|
accepted = command.submit(body)
|
|
assert accepted["state"] == "queued"
|
|
assert command.take(imei, "unregistered") is None
|
|
now[0] += 6
|
|
command = Commands(store)
|
|
assert command.get(body["id"])["state"] == "queued"
|
|
command.sessions[imei] = {"reconnected"}
|
|
assert command.submit(body)["expires_at"] == accepted["expires_at"]
|
|
assert command.take(imei, "reconnected") is not None
|
|
command = Commands(store)
|
|
command.sessions[imei] = {"again"}
|
|
assert command.submit(body)["state"] == "uncertain"
|
|
assert command.take(imei, "again") is None
|
|
assert command.wait_delay(imei) is None
|
|
|
|
|
|
def test_original_deadline_and_terminal_history_survive_duplicate_post(store, monkeypatch):
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
command = Commands(store)
|
|
body = {
|
|
"id": "e" * 32,
|
|
"imei": imei,
|
|
"kind": "request-position",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"not_after": now[0] + 10,
|
|
}
|
|
command.submit(body)
|
|
now[0] += 11
|
|
command.sessions[imei] = {"late"}
|
|
assert command.submit(body)["state"] == "expired"
|
|
assert command.take(imei, "late") is None
|
|
assert Commands(store).get(body["id"])["state"] == "expired"
|
|
with pytest.raises(ValueError, match="idempotency"):
|
|
command.submit({**body, "not_after": now[0] + 10})
|
|
# A request whose initial HTTP delivery itself was delayed is recorded,
|
|
# but must never execute even if the tracker is online on arrival.
|
|
assert command.submit({**body, "id": "f" * 32})["state"] == "expired"
|
|
assert command.take(imei, "late") is None
|
|
assert command.wait_delay(imei) is None
|
|
|
|
|
|
def test_effectful_action_cannot_cross_its_original_request_deadline(store, monkeypatch):
|
|
from ndc_vps.commands import Commands
|
|
|
|
now = [1800000000.0]
|
|
monkeypatch.setattr("ndc_vps.commands.time.time", lambda: now[0])
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
command = Commands(store)
|
|
command.sessions[imei] = {"present"}
|
|
body = {
|
|
"id": "e" * 32,
|
|
"imei": imei,
|
|
"kind": "pulse-output",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
"pin": 4,
|
|
"seconds": 1,
|
|
"not_after": now[0] + 1,
|
|
}
|
|
command.submit(body)
|
|
now[0] += 2
|
|
assert command.take(imei, "present") is None
|
|
assert command.submit(body)["state"] == "expired"
|
|
with pytest.raises(ValueError):
|
|
command.submit({**body, "id": "f" * 32, "not_after": float("nan")})
|
|
|
|
|
|
def test_idle_sender_wakes_on_command_without_periodic_history_poll(store, monkeypatch):
|
|
from ndc_vps.service import Service
|
|
|
|
imei = "123456789012345"
|
|
store.set_devices([{"imei": imei, "instance_id": "c" * 32}])
|
|
|
|
async def exercise():
|
|
service = Service(store)
|
|
service.commands.sessions[imei] = {"present"}
|
|
service.commands.session_activity[imei, "present"] = time.monotonic() - 20
|
|
original = service.commands.take_delivery
|
|
checks = []
|
|
writes = []
|
|
written = asyncio.Event()
|
|
available = [False]
|
|
|
|
def take(*args, **kwargs):
|
|
checks.append(time.monotonic())
|
|
return original(*args, **kwargs)
|
|
|
|
monkeypatch.setattr(service.commands, "take_delivery", take)
|
|
|
|
class Writer:
|
|
def is_closing(self):
|
|
return False
|
|
|
|
async def drain(self):
|
|
pass
|
|
|
|
class Delivery:
|
|
def ready(self):
|
|
return available[0]
|
|
|
|
def write(self, data, deadline, observe=None):
|
|
writes.append(data)
|
|
written.set()
|
|
|
|
def abort(self):
|
|
pass
|
|
|
|
task = asyncio.create_task(service.send_commands(imei, Writer(), "present", Delivery()))
|
|
try:
|
|
await asyncio.sleep(1.1)
|
|
assert len(checks) == 1
|
|
service.commands.submit(
|
|
{
|
|
"id": "a" * 32,
|
|
"imei": imei,
|
|
"kind": "request-position",
|
|
"model": 231,
|
|
"firmware": "0.01",
|
|
}
|
|
)
|
|
service.notify(imei)
|
|
await asyncio.sleep(0.03)
|
|
assert not written.is_set()
|
|
available[0] = True
|
|
service.notify(imei)
|
|
await asyncio.sleep(0.03)
|
|
assert not written.is_set() # A drained stale stream is insufficient.
|
|
service.commands.session_activity[imei, "present"] = time.monotonic()
|
|
service.notify(imei)
|
|
await asyncio.wait_for(written.wait(), 1)
|
|
assert len(writes) == 1
|
|
finally:
|
|
task.cancel()
|
|
await asyncio.gather(task, return_exceptions=True)
|
|
assert not service.wake
|
|
|
|
asyncio.run(exercise())
|