Keep B2 client fixes and move VPS implementation to its standalone repository

This commit is contained in:
DCCONSTRUCTIONS
2026-09-29 12:41:21 +03:00
parent 03d44d0fb1
commit 6dd652f71e
85 changed files with 2201 additions and 9299 deletions
+327
View File
@@ -0,0 +1,327 @@
{
"cases": [
{
"preset": "position",
"request": {
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "request-position",
"model": 231
},
"wire_hex": "0101"
},
{
"preset": "restart",
"request": {
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "restart",
"model": 231
},
"wire_hex": "0107"
},
{
"preset": "pin4-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e31"
},
{
"preset": "pin4-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e30"
},
{
"preset": "pin4-pulse",
"request": {
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 4,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e342e302e35"
},
{
"preset": "pin5-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e31"
},
{
"preset": "pin5-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e30"
},
{
"preset": "pin5-pulse",
"request": {
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 5,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e352e302e35"
},
{
"preset": "pin6-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e31"
},
{
"preset": "pin6-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e30"
},
{
"preset": "pin6-pulse",
"request": {
"encoding": "text",
"firmware": "0.01",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 6,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e362e302e35"
},
{
"preset": "position",
"request": {
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "request-position",
"model": 231
},
"wire_hex": "0101"
},
{
"preset": "restart",
"request": {
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "restart",
"model": 231
},
"wire_hex": "0107"
},
{
"preset": "pin4-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e31"
},
{
"preset": "pin4-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 4
},
"wire_hex": "3132333435362a534552562a382e342e30"
},
{
"preset": "pin4-pulse",
"request": {
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 4,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e342e302e35"
},
{
"preset": "pin5-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e31"
},
{
"preset": "pin5-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 5
},
"wire_hex": "3132333435362a534552562a382e352e30"
},
{
"preset": "pin5-pulse",
"request": {
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 5,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e352e302e35"
},
{
"preset": "pin6-on",
"request": {
"enabled": true,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e31"
},
{
"preset": "pin6-off",
"request": {
"enabled": false,
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "set-output",
"model": 231,
"password": "123456",
"pin": 6
},
"wire_hex": "3132333435362a534552562a382e362e30"
},
{
"preset": "pin6-pulse",
"request": {
"encoding": "text",
"firmware": "0.06",
"id": "11111111111111111111111111111111",
"imei": "123456789012345",
"kind": "pulse-output",
"model": 231,
"password": "123456",
"pin": 6,
"seconds": 5
},
"wire_hex": "3132333435362a534552562a32342e362e302e35"
}
],
"codec_sha256": {
"arnavi.py": "10c0f1bd41c5fd2c89349d3f668c38c88bec36773e7529d138f9c91e1a124136",
"sim_network.py": "9984645831cbd777275a06d54e6a2633537b69ef04281c4e3eb87d0f559c3f44",
"usb_protocol.py": "b2f067c4a443bcd9535a094bc119b8d1e2fd1ecf09a4812c3c49a7f31dfb1073",
"web_protocol.py": "f9c3eba194144e6cc839e80997917967b8075bdbc866fdbefa6929b55cd27c86"
},
"schema": "nodedc.arnavi-client-contract/v1",
"server_version": "0.1.46",
"synthetic_only": true
}
+16
View File
@@ -0,0 +1,16 @@
"""Pinned public protocol vectors replace imports of the extracted VPS server."""
import hashlib
import json
from pathlib import Path
def test_client_codecs_match_the_qualified_server_contract():
root = Path(__file__).resolve().parents[1]
contract = json.loads((root / "tests/fixtures/arnavi_vps/client-v1.json").read_text())
assert contract["schema"] == "nodedc.arnavi-client-contract/v1"
assert contract["synthetic_only"] is True
for server_name, digest in contract["codec_sha256"].items():
name = "internal.py" if server_name == "arnavi.py" else server_name
path = root / "src/k1link/device_plugins/arnavi_b2" / name
assert hashlib.sha256(path.read_bytes()).hexdigest() == digest
+1 -66
View File
@@ -1,13 +1,11 @@
"""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_cellular_telemetry import 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
@@ -95,66 +93,3 @@ def test_automatic_overlay_replaces_apn_and_credentials_only_for_selected_sim():
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
-51
View File
@@ -1,17 +1,9 @@
"""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
@@ -37,49 +29,6 @@ def test_both_permission_preserves_apns_passwords_and_other_flags(flags):
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
+51
View File
@@ -0,0 +1,51 @@
"""Synthetic 0.06 compatibility: keep unknown fields and reject unobserved versions."""
# ruff: noqa: F811 -- imported pytest fixtures are injected by parameter name.
import pytest
from test_equipment_network import context, full_core_context # noqa: F401
from k1link.device_plugins.arnavi_b2.usb_protocol import ProtocolError, decode_configuration
from k1link.device_plugins.arnavi_b2.web_protocol import decode_request
from k1link.fleet import equipment_actions, equipment_network
from k1link.fleet.independent_equipment import EquipmentError
def test_core_propagates_actual_firmware_and_preserves_unknown_config(full_core_context):
equipment, _, row, config = full_core_context
row["observed"]["firmware"] = "0.06"
action = equipment_actions.plan(equipment, row, {"kind": "request-position"})
assert action["firmware"] == "0.06"
planned = equipment_network.plan(equipment, row, full=True)
assert planned["firmware"] == "0.06"
target = decode_configuration(bytes.fromhex(planned["target_configuration"]))
assert target.integer(25, 2) == 16
assert target.value(222) == config.value(222)
assert [r.number for r in target.records] == [r.number for r in config.records]
row["observed"]["firmware"] = "0.07"
with pytest.raises(EquipmentError):
equipment_actions.plan(equipment, row, {"kind": "request-position"})
with pytest.raises(EquipmentError):
equipment_network.plan(equipment, row, full=True)
@pytest.mark.parametrize(
"metadata,accepted",
[
("0001e7020000", True),
("0006e7020000", True),
("0007e7020000", False),
("0006e7030000", False),
("0006e7020001", False),
],
)
def test_web006_upload_keeps_crc_image(metadata, accepted, full_core_context):
*_, config = full_core_context
payload = config.encode()
body = int("123456789012345").to_bytes(8, "little")
body += bytes.fromhex(metadata) + b"\x05" + payload
frame = b"[\x01" + len(body).to_bytes(2, "big") + body + b"]"
if accepted:
assert decode_request(frame)[1:] == (5, payload)
else:
with pytest.raises(ProtocolError):
decode_request(frame)
+3 -10
View File
@@ -63,18 +63,11 @@ def test_initial_usb_apply_rejects_unowned_or_incompatible_destination(case):
def test_initial_usb_apply_accepts_current_shipped_host():
import ast
import json
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)
)
source = Path(__file__).resolve().parent / "fixtures/arnavi_vps/client-v1.json"
version = json.loads(source.read_text())["server_version"]
hosts, _, host = context()
host["status"]["version"] = version
assert apply(hosts, "device", 1) == {"ok": True}
+125
View File
@@ -0,0 +1,125 @@
"""Persisted independent jobs: lost HTTP replies, cancellation and large queues."""
# ruff: noqa: F811
import json
import time
import pytest
from test_equipment_network import context # noqa: F401
from k1link.fleet import equipment_command_dispatch as dispatch
from k1link.fleet import equipment_command_journal as journal
from k1link.fleet import equipment_command_runtime as runtime
from k1link.fleet.independent_equipment import EquipmentStore
@pytest.fixture
def ready(context):
equipment, hosts, row = context
for host in hosts.rows():
host["status"]["version"] = "0.1.43"
host["status"]["capabilities"] = [dispatch.CAPABILITY, "arnavi-b2-durable-operations-v1"]
hosts.save(host)
return equipment, hosts, row
def test_outage_and_restart_keep_exact_job_body_and_id_without_deadline(ready, monkeypatch):
equipment, hosts, row = ready
created = runtime.enqueue(hosts, row["id"], "1" * 32, "pin4-off")
assert created["durable"] and "expires_at" not in created and "queue_deadline" not in created
sent = []
def lost(host, method, path, body=None):
sent.append((method, path, body))
raise OSError("reply lost")
monkeypatch.setattr(dispatch, "request", lost)
runtime.pump(hosts)
assert sent[0][0:2] == ("POST", "/v1/operations")
assert sent[0][2]["priority"] == "manual"
assert "not_after" not in sent[0][2]
hosts.equipment = EquipmentStore(equipment.root.parent, {})
later = time.time() + 86400
monkeypatch.setattr(time, "time", lambda: later)
runtime.pump(hosts)
assert sent[1] == sent[0]
assert journal.listing(hosts.equipment, row["id"])["items"][0]["state"] == "submitting"
assert "password" not in json.dumps(journal.listing(hosts.equipment, row["id"]))
def test_all_jobs_reach_vps_despite_pending_background_and_results_project_by_id(
ready, monkeypatch
):
equipment, hosts, row = ready
with equipment.db() as db:
current = equipment._find(db, "instances", row["id"])
current["network_operation"] = {
"id": "background",
"state": "queued",
"kind": "request-position",
}
db.execute("update instances set body=? where id=?", (json.dumps(current), row["id"]))
for n, preset in enumerate(("pin4-off", "pin5-off", "pin4-on")):
runtime.enqueue(hosts, row["id"], f"{n:032x}", preset)
requests = {}
def send(host, method, path, body=None):
if method == "POST":
requests[body["id"]] = body
return dict(id=body["id"], kind=body["kind"], state="queued", durable=True)
identifier = path.rsplit("/", 1)[1]
return dict(
id=identifier,
kind=requests[identifier]["kind"],
state="delivered",
durable=True,
delivered_at=time.time(),
delivery_seconds=1,
attempt_count=1,
)
monkeypatch.setattr(dispatch, "request", send)
runtime.pump(hosts)
assert len(requests) == 3
later = time.time() + 3
monkeypatch.setattr(time, "time", lambda: later)
runtime.pump(hosts)
entries = journal.listing(equipment, row["id"])["items"]
assert all(x["state"] == "delivered" and x["delivered_at"] == later for x in entries)
with equipment.db() as db:
assert (
equipment._find(db, "instances", row["id"])["network_operation"]["id"] == "background"
)
assert db.execute("select count(*) from command_dispatch").fetchone()[0] == 0
def test_cancel_after_lost_admission_sends_tombstone_not_another_command(ready, monkeypatch):
equipment, hosts, row = ready
runtime.enqueue(hosts, row["id"], "1" * 32, "pin5-pulse")
monkeypatch.setattr(dispatch, "request", lambda *a, **k: (_ for _ in ()).throw(OSError()))
runtime.pump(hosts)
runtime.cancel(equipment, row["id"], "1" * 32, hosts)
later = time.time() + 3
monkeypatch.setattr(time, "time", lambda: later)
seen = []
def stop(host, method, path, body=None):
seen.append((method, path, body))
return dict(
id="1" * 32, kind="pulse-output", state="stopped", durable=True, stop_requested=True
)
monkeypatch.setattr(dispatch, "request", stop)
runtime.pump(hosts)
assert seen[0][1].endswith("/cancel")
assert journal.listing(equipment, row["id"])["items"][0]["state"] == "stopped"
def test_v2_queue_exceeds_old_limit_but_history_response_stays_bounded(ready):
equipment, hosts, row = ready
for n in range(80):
runtime.enqueue(hosts, row["id"], f"{n:032x}", "pin4-off")
response = journal.listing(equipment, row["id"])
assert response["counts"]["waiting"] == 80
assert len(response["items"]) == 25
assert len(response["tracked_items"]) <= 64
+48
View File
@@ -0,0 +1,48 @@
"""Repeat history after transport outbox cleanup; never replay changed settings."""
import json
import pytest
from test_equipment_network import context, full_core_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_repeat import repeat
from k1link.fleet.independent_equipment import EquipmentError
@pytest.mark.parametrize("read_only", [True, False])
def test_repeat_network_intent_after_outbox_cleanup(full_core_context, monkeypatch, read_only): # noqa: F811
equipment, hosts, row, _ = full_core_context
for host in hosts.rows():
host["status"].update(version="0.1.42", capabilities=["arnavi-b2-durable-operations-v1"])
hosts.save(host)
sent = []
def send(host, method, path, body=None):
sent.append(body)
return {"id": body["id"], "kind": body["kind"], "state": "rejected", "durable": True}
monkeypatch.setattr(network, "request", send)
original = network.start(hosts, row["id"], row["revision"], read_only)["network_operation"]
with equipment.db() as db:
assert db.execute("SELECT count(*) FROM network_outbox").fetchone()[0] == 0
repeated = repeat(hosts, row["id"], original["id"], "f" * 32)
assert repeated["state"] == "waiting"
assert "network_intent" not in repeated
assert repeat(hosts, row["id"], original["id"], "f" * 32) == repeated
runtime.pump(hosts)
assert len(sent) == 2 and sent[0]["kind"] == sent[1]["kind"]
assert sent[0]["id"] != sent[1]["id"]
if not read_only:
assert sent[0]["target_configuration"] == sent[1]["target_configuration"]
with equipment.db() as db:
current = equipment._find(db, "instances", row["id"])
current["settings"]["parameters"]["25"] += 1
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(current), row["id"]))
with pytest.raises(EquipmentError, match="Настройки изменились"):
repeat(hosts, row["id"], original["id"], "a" * 32)
assert all(
"network_intent" not in item for item in journal.listing(equipment, row["id"])["items"]
)
+34 -7
View File
@@ -210,7 +210,7 @@ def test_catalog_and_history_never_expose_password(ready, monkeypatch):
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
assert value["description"]["queue_seconds"] == 30
def test_tracker_acceptance_is_persisted_but_does_not_finish_intent(ready, monkeypatch):
@@ -375,24 +375,51 @@ def test_runtime_api_rejects_foreign_origin_and_arbitrary_command(ready):
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)
fixture = Path(__file__).resolve().parent / "fixtures/arnavi_vps/client-v1.json"
contract = json.loads(fixture.read_text())
cases = {
case["preset"]: case
for case in contract["cases"]
if case["request"]["firmware"] == row["observed"]["firmware"]
}
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"])
case = cases[preset["id"]]
assert body == case["request"]
wire = bytes.fromhex(case["wire_hex"])
if preset["encoding"].endswith("FC"):
assert wire.decode().replace("123456", "••••••") == preset["wire"]
else:
assert wire.hex(" ").upper() == preset["wire"]
def test_manual_repeat_uses_new_id_and_preserves_http_idempotency(ready, monkeypatch):
from k1link.fleet.equipment_command_repeat import repeat
equipment, hosts, row = ready
original = runtime.enqueue(hosts, row["id"], "1" * 32, "position")
runtime.cancel(equipment, row["id"], original["id"])
repeated = repeat(hosts, row["id"], original["id"], "2" * 32)
assert repeated["state"] == "waiting" and repeated["id"] != original["id"]
assert repeat(hosts, row["id"], original["id"], "2" * 32) == repeated
with pytest.raises(EquipmentError, match="завершения"):
repeat(hosts, row["id"], repeated["id"], "3" * 32)
assert len(journal.listing(equipment, row["id"])["items"]) == 2
assert not {"guard", "digest", "network_intent"} & repeated.keys()
def test_repeat_missing_history_is_rejected(ready):
from k1link.fleet.equipment_command_repeat import repeat
_, hosts, row = ready
with pytest.raises(EquipmentError, match="не найдена"):
repeat(hosts, row["id"], "f" * 32, "a" * 32)
+1 -1
View File
@@ -739,7 +739,7 @@ def test_outbox_backoff_expiry_and_credentials_never_enter_public_history(contex
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
now[0] += 61
network.refresh(hosts, host)
assert sum(c.args[1] == "POST" for c in calls.call_args_list) == 1
now[0] += 40
+2 -9
View File
@@ -1,6 +1,5 @@
"""Core/VPS ownership survives lost HTTP, restarts and per-attempt timeouts."""
import ast
import json
import time
from pathlib import Path
@@ -16,14 +15,8 @@ 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)
)
source = Path(__file__).resolve().parent / "fixtures/arnavi_vps/client-v1.json"
return json.loads(source.read_text())["server_version"]
@pytest.fixture(params=sorted({"0.1.32", shipped_version()}))
-93
View File
@@ -1,93 +0,0 @@
"""B2 token receipts can return through either admitted monitoring connection."""
import struct
import time
import pytest
from test_vps_host import store # noqa: F401
def receipt(token, code=0):
data = struct.pack("<I", int(time.time())) + bytes((code,)) + token
return b"[\x01\x09\x05\0" + data + bytes([sum(data) % 256]) + b"]"
@pytest.fixture
def pending(store): # noqa: F811
from ndc_vps.commands import Commands
commands = Commands(store)
imei = "123456789012345"
other = "123456789012346"
store.set_devices(
[
{"imei": imei, "instance_id": "a" * 32},
{"imei": other, "instance_id": "b" * 32},
]
)
commands.sessions[imei] = {"primary", "secondary"}
commands.sessions[other] = {"another-tracker"}
body = {
"id": "c" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
commands.submit(body)
raw = commands.take(imei, "primary")
return commands, imei, other, body, raw[5:9]
def test_second_stream_receipt_confirms_once_without_resending(pending):
commands, imei, _, body, token = pending
commands.receive(imei, receipt(token), "secondary")
confirmed = commands.get(body["id"])
assert confirmed["state"] == "device_confirmed" and confirmed["device_code"] == 0
assert commands.take(imei, "secondary") is None
commands.receive(imei, receipt(token, 5), "primary")
assert commands.get(body["id"]) == confirmed
assert type(commands)(commands.store).get(body["id"]) == confirmed
def test_ack_is_not_completion_and_first_acceptance_survives_duplicate(pending):
commands, imei, _, body, token = pending
commands.receive(imei, receipt(token, 6), "secondary")
accepted = commands.get(body["id"])
assert accepted["state"] == "dispatched" and accepted["device_code"] == 6
assert accepted["device_accepted_at"] > 0
commands.receive(imei, receipt(token, 6), "primary")
assert commands.get(body["id"])["device_accepted_at"] == accepted["device_accepted_at"]
commands.receive(imei, receipt(token, 5), "secondary")
assert commands.get(body["id"])["state"] == "device_rejected"
@pytest.mark.parametrize("source", ["unknown-session", "wrong-token", "other-tracker", "closed"])
def test_unrelated_receipt_never_completes_command(pending, source):
commands, imei, other, body, token = pending
session = "secondary"
if source == "unknown-session":
session = "unadmitted"
elif source == "wrong-token":
token = bytes(value ^ 255 for value in token)
elif source == "other-tracker":
imei, session = other, "another-tracker"
else:
commands.sessions[imei].remove(session)
commands.receive(imei, receipt(token), session)
assert commands.get(body["id"])["state"] == "dispatched"
def test_new_connection_can_deliver_exact_receipt_without_replay(pending):
commands, imei, _, body, token = pending
commands.sessions[imei] = {"reconnected"}
commands.receive(imei, receipt(token), "reconnected")
assert commands.get(body["id"])["state"] == "device_confirmed"
assert commands.take(imei, "reconnected") is None
def test_revoked_device_receipt_is_not_accepted(pending):
commands, imei, _, body, token = pending
commands.store.set_devices([])
commands.receive(imei, receipt(token), "secondary")
assert commands.get(body["id"])["state"] == "dispatched"
File diff suppressed because it is too large Load Diff
-60
View File
@@ -1,60 +0,0 @@
"""The service account must traverse installer code under a restrictive umask."""
import importlib.util
import json
import os
import sys
from pathlib import Path
from types import SimpleNamespace
def test_clean_install_under_private_umask_keeps_code_accessible(tmp_path, monkeypatch):
source = Path(__file__).resolve().parents[1] / "apps/vps-host"
monkeypatch.syspath_prepend(str(source))
spec = importlib.util.spec_from_file_location("vps_install_permissions", source / "install.py")
installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)
root, state, unit = tmp_path / "product", tmp_path / "state", tmp_path / "service"
payload = tmp_path / "payload"
payload.mkdir()
(payload / "entry.py").write_text("# synthetic service payload\n")
for name, value in (("ROOT", root), ("STATE", state), ("UNIT", unit), ("SOURCE", payload)):
monkeypatch.setattr(installer, name, value)
# A clean install's credential generation is not relevant to access modes.
monkeypatch.setattr(installer.pwd, "getpwnam", lambda _: SimpleNamespace(pw_uid=1, pw_gid=1))
monkeypatch.setattr(installer.os, "chown", lambda *args: None)
monkeypatch.setattr(installer.ssl, "PEM_cert_to_DER_cert", lambda _: b"test cert")
monkeypatch.setattr(installer.firewall, "apply", lambda *args: False)
monkeypatch.setattr(installer, "healthy", lambda: None)
def run(*args, **kwargs):
if args[0] == "openssl":
(state / "tls.key").write_text("private test key")
(state / "tls.crt").write_text("test certificate")
if args[0] == "runuser":
for directory in (root, root / "releases", kwargs["cwd"]):
assert directory.stat().st_mode & 0o777 == 0o755
assert state.stat().st_mode & 0o777 == 0o700
assert (state / "tls.key").stat().st_mode & 0o777 == 0o600
(state / "connect.key").write_text("test invitation")
monkeypatch.setattr(installer, "run", run)
monkeypatch.setattr(installer.os, "geteuid", lambda: 0)
proposal = {
"previous": None,
"plan_sha256": "plan",
"artifact": "release",
"configuration": {"public_host": "test.example", "api_port": 19443},
"firewall": {"mode": "external"},
}
previous = os.umask(0o077)
try:
installer.apply(
SimpleNamespace(expect="plan", host="test.example", api_port=19443, tracker_port=9922),
proposal,
)
finally:
os.umask(previous)
sys.modules.pop("firewall", None)
assert json.loads((root / "installed.json").read_text())["status"] == "healthy"
assert (root / "installed.json").stat().st_mode & 0o777 == 0o600
-379
View File
@@ -1,379 +0,0 @@
"""Persistent maintenance intent recovery, isolated per tracker, no output actions."""
import json
import struct
import time
import pytest
from test_vps_host import full_context, store # noqa: F401
@pytest.fixture
def runtime(store, monkeypatch): # noqa: F811
from ndc_vps.commands import Commands
from ndc_vps.operations import Operations
now = [1800000000.0]
monkeypatch.setattr(time, "time", lambda: now[0])
monkeypatch.setattr(time, "monotonic", lambda: now[0] - 1700000000)
body = {
"id": "a" * 32,
"imei": "123456789012345",
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
store.set_devices([{"imei": body["imei"], "instance_id": "c" * 32}])
return Operations(store, Commands(store)), body, now
def connect(ops, body, session="live"):
ops.commands.sessions[body["imei"]] = {session}
ops.commands.session_activity[body["imei"], session] = time.monotonic()
ops.commands.session_started[body["imei"], session] = time.monotonic()
def reply(ops, body, raw, code=0):
payload = struct.pack("<I", int(time.time())) + bytes([code]) + raw[5:9]
ops.commands.receive(
body["imei"], b"[\x01\x09\x05\0" + payload + bytes([sum(payload) % 256]) + b"]", "live"
)
def restored(ops):
return type(ops)(ops.store, type(ops.commands)(ops.store))
def test_offline_intent_survives_time_restart_duplicate_submit_and_cancel(runtime):
ops, body, now = runtime
first = ops.submit(body)
now[0] += 86400
ops = restored(ops)
assert ops.submit(body)["id"] == first["id"]
assert ops.get(body["id"])["state"] == "queued"
assert ops.get(body["id"])["attempt_count"] == 0
with pytest.raises(ValueError, match="conflict"):
ops.submit({**body, "kind": "restart"})
assert ops.cancel(body["id"])["state"] == "stopped"
connect(ops, body)
assert restored(ops).get(body["id"])["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_late_transport_observation_is_visible_after_operation_completed(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
raw, _, ticket = ops.commands.take_delivery(body["imei"], "live", with_receipt=True)
reply(ops, body, raw)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert ops.get(body["id"])["transport"][0]["state"] == "prepared"
ops.commands.transport.record([
(ticket, "written", now[0], 0, None),
(ticket, "tcp_acknowledged", now[0] + .5, .5, None),
])
result = ops.get(body["id"])
assert result["state"] == "device_confirmed"
assert result["transport"][0]["tcp_ack_seconds"] == .5
assert ops.history(body["id"])["items"][0]["transport"] == result["transport"]
assert restored(ops).get(body["id"])["transport"] == result["transport"]
def test_lost_tracker_reply_has_new_attempt_same_intent_and_complete_history(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
first = ops.commands.take(body["imei"], "live")
now[0] += 31
assert ops.get(body["id"])["state"] == "queued"
assert ops.get(body["id"])["attempt_count"] == 1
ops = restored(ops)
now[0] += 5
connect(ops, body)
ops.advance(body["imei"])
second = ops.commands.take(body["imei"], "live")
assert first[5:9] != second[5:9]
reply(ops, body, first) # Old attempt cannot confirm the new one.
assert ops.get(body["id"])["state"] == "dispatched"
reply(ops, body, second)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert ops.get(body["id"])["attempt_count"] == 2
assert [x["state"] for x in ops.history(body["id"])["items"]] == [
"device_confirmed",
"unconfirmed",
]
assert restored(ops).get(body["id"])["state"] == "device_confirmed"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM operations").fetchone()[0] == 1
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 2
def test_vps_crash_after_dispatch_resumes_intent_not_old_attempt(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
assert ops.commands.take(body["imei"], "live")
ops = restored(ops)
assert ops.get(body["id"])["state"] == "queued"
now[0] += 5
connect(ops, body)
ops.advance(body["imei"])
raw = ops.commands.take(body["imei"], "live")
reply(ops, body, raw)
assert ops.get(body["id"])["state"] == "device_confirmed"
assert len(ops.history(body["id"])["items"]) == 2
def test_vps_crash_before_attempt_admission_and_cancellation_race(runtime, monkeypatch):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
def crash(*args):
raise RuntimeError("simulated process loss")
monkeypatch.setattr(ops.commands, "submit", crash)
with pytest.raises(RuntimeError):
ops.advance(body["imei"])
ops = restored(ops)
assert ops.cancel(body["id"])["state"] == "stopped"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 0
def test_cancel_before_lost_post_arrives_is_a_persisted_tombstone(runtime):
ops, body, _ = runtime
assert ops.cancel(body["id"], body["kind"])["state"] == "stopped"
ops = restored(ops)
connect(ops, body)
assert ops.submit(body)["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_offline_tracker_does_not_block_another_and_fifo_is_per_imei(runtime):
ops, first, _ = runtime
second = {**first, "id": "b" * 32, "imei": "123456789012346"}
ops.store.set_devices(
[
{"imei": first["imei"], "instance_id": "c" * 32},
{"imei": second["imei"], "instance_id": "d" * 32},
]
)
ops.submit(first)
ops.submit(second)
ops.submit({**second, "id": "e" * 32})
connect(ops, second)
ops.advance(first["imei"])
ops.advance(second["imei"])
raw = ops.commands.take(second["imei"], "live")
assert ops.get("e" * 32)["attempt_count"] == 0
reply(ops, second, raw)
assert ops.get(second["id"])["state"] == "device_confirmed"
assert ops.get(first["id"])["attempt_count"] == 0
assert ops.get("e" * 32)["attempt_count"] == 1
@pytest.mark.parametrize(
"code,expected", [(1, "device_rejected"), (5, "device_rejected"), (7, "queued")]
)
def test_permanent_rejection_and_device_queue_backpressure_differ(runtime, code, expected):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
reply(ops, body, ops.commands.take(body["imei"], "live"), code)
assert ops.get(body["id"])["state"] == expected
def test_restart_accepted_by_b2_never_replayed_when_return_evidence_missing(runtime):
ops, body, now = runtime
body["kind"] = "restart"
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
reply(ops, body, ops.commands.take(body["imei"], "live"))
now[0] += 181
assert ops.get(body["id"])["state"] == "accepted"
assert ops.get(body["id"])["attempt_count"] == 1
@pytest.mark.parametrize("observed", ["target", "before", "divergent"])
def test_uncertain_write_reads_state_before_any_retry(full_context, observed): # noqa: F811
from ndc_vps.operations import Operations
from ndc_vps.usb_protocol import Configuration, Setting
commands, body, before, target, wire, now = full_context
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
assert b"SERV*1.8" in commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 181
assert ops.get(body["id"])["runtime_phase"] == "retry-wait"
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
image = (
target
if observed == "target"
else before
if observed == "before"
else Configuration(
tuple(
Setting(r.number, b"\x00\x11" if r.number == 25 else r.value)
for r in before.records
)
)
)
commands.web_receive(wire(5, image.encode()), "192.0.2.1")
result = ops.get(body["id"])
assert (
result["state"]
== {"target": "verified", "before": "queued", "divergent": "rejected"}[observed]
)
assert result["attempt_count"] == 2
assert "123456" not in json.dumps(ops.history(body["id"]))
with commands.store.db() as db:
images = sum(
bool(json.loads(r[0]).get("write_reply_sent_at"))
for r in db.execute("SELECT body FROM commands")
)
assert images == 1
def test_cancelled_inflight_keeps_final_receipt_but_stops_unknown_retry(runtime):
ops, body, now = runtime
ops.submit(body)
connect(ops, body)
ops.advance(body["imei"])
wire = ops.commands.take(body["imei"], "live")
assert ops.cancel(body["id"])["stop_requested"]
now[0] += 31
result = ops.get(body["id"])
assert result["state"] == "stopped" and result["attempt_count"] == 1
connect(ops, body)
reply(ops, body, wire)
assert ops.get(body["id"])["state"] == "stopped"
assert ops.commands.take(body["imei"], "live") is None
def test_repeated_reads_crash_plan_after_admission_reuses_child(runtime, monkeypatch):
ops, body, _ = runtime
ops.submit(body)
connect(ops, body)
original = ops.commands.submit
def admitted(body):
original(body)
raise RuntimeError("crash after commit")
monkeypatch.setattr(ops.commands, "submit", admitted)
with pytest.raises(RuntimeError):
ops.advance(body["imei"])
ops = restored(ops)
connect(ops, body)
assert ops.get(body["id"])["attempt_count"] == 1
wire = ops.commands.take(body["imei"], "live")
reply(ops, body, wire)
assert ops.get(body["id"])["state"] == "device_confirmed"
with ops.store.db() as db:
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
def test_old_image_read_allows_fresh_preflight_before_second_write(full_context): # noqa: F811
from ndc_vps.operations import Operations
commands, body, before, target, wire, now = full_context
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 181
ops.get(body["id"])
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
assert ops.get(body["id"])["state"] == "queued"
now[0] += 15
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
assert b"SERV*1.8" in commands.take(body["imei"], "live")
assert commands.web_receive(wire(2), "192.0.2.1")
now[0] += 15
assert b"SERV*1.9" in commands.take(body["imei"], "live")
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
assert ops.get(body["id"])["state"] == "verified"
assert ops.get(body["id"])["attempt_count"] == 3
@pytest.mark.parametrize("both", [False, True])
def test_sim_recovery_reads_target_and_fresh_modem_without_second_restart(full_context, both): # noqa: F811
import hashlib
from ndc_vps.operations import Operations
from ndc_vps.usb_protocol import Configuration, Setting
from test_vps_host import sim_packet
commands, body, before, _, wire, now = full_context
before = Configuration(
before.records + (Setting(72, (2072 | (1 << 20) if both else 2072).to_bytes(4, "big")),)
)
target = Configuration(
tuple(
Setting(
r.number,
(2072 | (0 if both else 1 << 10)).to_bytes(4, "big") if r.number == 72 else r.value,
)
for r in before.records
)
)
body.update(
kind="select-sim",
sim_slot=2,
expected_sha256=hashlib.sha256(before.encode()).hexdigest(),
target_configuration=target.encode().hex(),
)
if both:
body.pop("sim_slot")
body["sim_policy"] = "both"
ops = Operations(commands.store, commands)
ops.submit(body)
ops.advance(body["imei"])
commands.take(body["imei"], "live")
commands.web_receive(wire(5, before.encode()), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
commands.web_receive(wire(2), "192.0.2.1")
now[0] += 15
commands.take(body["imei"], "live")
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
assert commands.take(body["imei"], "live")[-3:-1] == b"\x01\x07"
now[0] += 361
ops.get(body["id"])
now[0] += 5
commands.session_activity[body["imei"], "live"] = time.monotonic()
ops.advance(body["imei"])
assert b"SERV*1.9" in commands.take(body["imei"], "live")
ops.observe(body["imei"], sim_packet(now[0], slot=2))
ops.observe(
body["imei"], sim_packet(now[0] - 1, slot=1)
) # delayed older sample cannot downgrade
commands.web_receive(wire(5, target.encode()), "192.0.2.1")
result = ops.get(body["id"])
assert result["state"] == "sim_selected" and result["active_sim"] == 2
assert result["attempt_count"] == 2 and commands.take(body["imei"], "live") is None
-208
View File
@@ -1,208 +0,0 @@
"""A tracker packet and the command evidence it carries have one commit boundary."""
import asyncio
import sqlite3
import subprocess
import sys
import time
from pathlib import Path
import pytest
from test_vps_command_receipts import receipt
from test_vps_host import store # noqa: F401
@pytest.mark.parametrize("failure", ["before-receipt", "after-receipt", None])
def test_packet_command_and_ack_share_commit_boundary(store, monkeypatch, failure): # noqa: F811
from ndc_vps.commands import Commands
from ndc_vps.service import Service
service = Service(store)
commands = service.commands
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
commands.sessions[imei] = {"outbound"}
body = {
"id": "c" * 32,
"imei": imei,
"kind": "request-position",
"model": 231,
"firmware": "0.01",
}
commands.submit(body)
outgoing = commands.take(imei, "outbound")
raw = receipt(outgoing[5:9])
def failed(*args):
raise OSError("simulated failure inside receive pipeline")
if failure == "before-receipt":
monkeypatch.setattr(commands, "receive", failed)
elif failure == "after-receipt":
monkeypatch.setattr(service.operations, "observe", failed)
class Writer:
closed = False
def __init__(self):
self.writes = []
def get_extra_info(self, name):
return ("192.0.2.1", 12345)
def is_closing(self):
return self.closed
def write(self, data):
if data == b"{\x00\x01}":
# Check from a separate connection exactly when the ACK leaves.
assert commands.get(body["id"])["state"] == "device_confirmed"
assert len(store.fetch(0)["items"]) == 1
self.writes.append(data)
async def drain(self):
pass
def close(self):
self.closed = True
class Delivery:
def __init__(self, writer):
self.writer = writer
def ready(self):
return True
def write(self, data, *args):
self.writer.write(data)
def abort(self):
self.writer.close()
monkeypatch.setattr("ndc_vps.service.Delivery", Delivery)
async def exchange():
reader = asyncio.StreamReader()
reader.feed_data(b"\xff\x23" + int(imei).to_bytes(8, "little") + raw)
reader.feed_eof()
writer = Writer()
await service.tracker(reader, writer)
assert writer.closed and service.connections == 0
return writer.writes
writes = asyncio.run(exchange())
if failure:
assert b"{\x00\x01}" not in writes
assert store.fetch(0)["items"] == []
assert commands.get(body["id"])["state"] == "dispatched"
else:
assert writes[-1] == b"{\x00\x01}"
store.acknowledge(store.fetch(0)["items"][0]["id"])
assert store.fetch(0)["items"] == []
assert Commands(store).get(body["id"])["state"] == "device_confirmed"
def test_sqlite_failure_does_not_leave_partial_modem_or_command_evidence(store): # noqa: F811
from ndc_vps.service import Service
from test_vps_host import sim_packet
service = Service(store)
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
raw = sim_packet(time.time(), slot=2)
with pytest.raises(sqlite3.OperationalError), store.packet_transaction():
store.append(imei, raw, [])
service.operations.observe(imei, raw)
with store.db() as db:
db.execute("INSERT INTO missing_table VALUES(1)")
assert store.fetch(0)["items"] == []
with store.db() as db:
assert db.execute("SELECT count(*) FROM operation_modem").fetchone()[0] == 0
# The failed scope must not leak its connection into the next packet.
with store.packet_transaction():
store.append(imei, raw, [])
service.operations.observe(imei, raw)
assert len(store.fetch(0)["items"]) == 1
with store.db() as db:
assert db.execute("SELECT count(*) FROM operation_modem").fetchone()[0] == 1
@pytest.mark.parametrize("committed", [False, True])
def test_process_loss_cannot_split_packet_and_durable_operation_result(store, committed): # noqa: F811
from ndc_vps import store as store_module
from ndc_vps.service import Service
# os._exit skips Python context-manager cleanup, as a process crash would.
script = """
import os, sys, time, struct
sys.path.insert(0, sys.argv[1])
from ndc_vps.store import Store
from ndc_vps.service import Service
service = Service(Store(sys.argv[2]))
imei = '123456789012345'
service.store.set_devices([{'imei': imei, 'instance_id': 'a'*32}])
body = {'id':'c'*32, 'imei':imei, 'kind':'request-position', 'model':231, 'firmware':'0.01'}
commands = service.commands
commands.sessions[imei] = {'live'}
commands.session_activity[imei,'live'] = time.monotonic()
service.operations.submit(body)
service.operations.advance(imei)
outgoing = commands.take(imei, 'live')
data = struct.pack('<I', int(time.time())) + b'\\0' + outgoing[5:9]
raw = b'[\\x01\\x09\\x05\\0' + data + bytes([sum(data)%256]) + b']'
with service.store.packet_transaction():
service.store.append(imei, raw, [])
commands.receive(imei, raw, 'live')
service.operations.observe(imei, raw)
if sys.argv[3] == 'before':
os._exit(77)
os._exit(77)
"""
process = subprocess.run(
[
sys.executable,
"-c",
script,
str(Path(store_module.__file__).parents[1]),
str(store.root),
"after" if committed else "before",
],
capture_output=True,
timeout=10,
)
assert process.returncode == 77, process.stderr.decode()
recovered = Service(store)
result = recovered.operations.get("c" * 32)
assert result["state"] == ("device_confirmed" if committed else "queued")
assert result["attempt_count"] == 1
assert len(store.fetch(0)["items"]) == int(committed)
with store.db() as db:
assert db.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
assert db.execute("SELECT count(*) FROM commands").fetchone()[0] == 1
def test_other_worker_cannot_observe_uncommitted_packet(store): # noqa: F811
import threading
from concurrent.futures import ThreadPoolExecutor
from test_vps_host import package
imei = "123456789012345"
store.set_devices([{"imei": imei, "instance_id": "a" * 32}])
written, release = threading.Event(), threading.Event()
def ingest():
with store.packet_transaction():
store.append(imei, package(), [])
written.set()
assert release.wait(5)
with ThreadPoolExecutor(max_workers=1) as worker:
pending = worker.submit(ingest)
try:
assert written.wait(5)
assert store.fetch(0)["items"] == []
finally:
release.set()
pending.result(timeout=5)
assert len(store.fetch(0)["items"]) == 1
-284
View File
@@ -1,284 +0,0 @@
"""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-*"))