Files
NODEDC_MISSION_CORE/tests/test_arnavi_b2_usb.py
T

205 lines
7.5 KiB
Python

"""Synthetic-only B2 wire fixtures; never commit device dumps or credentials."""
import base64
import binascii
import json
from pathlib import Path
import pytest
from k1link.device_plugins.arnavi_b2.usb_protocol import (
READ_IDENTITY,
READ_SETTINGS,
Configuration,
ProtocolError,
Setting,
configuration_response,
decode_configuration,
parse_identity,
prepare_server_slot,
response_fields,
)
from k1link.device_plugins.arnavi_b2.usb_read import UsbPort, parse_ioreg
def wire(body: bytes) -> bytes:
return len(body).to_bytes(2, "big") + binascii.crc_hqx(body, 0xFFFF).to_bytes(2, "big") + body
def synthetic_config() -> Configuration:
records = [
Setting(1, b"old.example\0"),
Setting(2, b"\x50\x8f"),
Setting(9, b"\0"),
Setting(5, b"SYNTHETIC_SECRET"),
Setting(135, b"\xde\xad\x23\x00"),
]
for host, port, protocol in [(3, 4, 8), (111, 112, 7), (113, 114, 6)]:
records.extend([Setting(host, b""), Setting(port, b"\0\0"), Setting(protocol, b"\0")])
records.extend(
[
Setting(67, b"example.apn\0"),
Setting(89, b""),
Setting(70, b"vendor.example\0"),
Setting(71, (9231).to_bytes(2, "big")),
Setting(72, (2073).to_bytes(4, "big")),
Setting(62, b"\0\x96"),
]
)
return Configuration(tuple(records))
IDENTITY = (
b">DI=231;0;1\r\n>DN=123456\r\n>MN=123456789012345\r\n>SID0=8900000000000000001\r\n>SID1=0\r\n"
)
def test_config_wire_endianness_and_lossless_unknown_records():
original = wire(b"#\x02\x02\x50\x8f#\x87\x04\xde\xad#\x00")
config = decode_configuration(original)
assert config.integer(2, 2) == 20623
assert config.value(135) == b"\xde\xad#\x00"
assert config.encode() == original
@pytest.mark.parametrize(
"body,reason",
[
(b"#\x02\x02\x01", "truncated_setting_value"),
(b"#\x02\x00#\x02\x00", "invalid_or_duplicate_setting_number"),
(b"#\x02\x00#", "truncated_setting_header"),
(b"!\x02\x00", "unsupported_configuration_record_format"),
],
)
def test_invalid_records_fail_closed(body, reason):
with pytest.raises(ProtocolError, match=reason):
decode_configuration(wire(body))
def test_crc_and_length_rejected_before_use():
original = synthetic_config().encode()
damaged = bytearray(original)
damaged[-1] ^= 1
with pytest.raises(ProtocolError, match="crc_mismatch"):
decode_configuration(bytes(damaged))
with pytest.raises(ProtocolError, match="length_mismatch"):
decode_configuration(original + b"\0")
def test_sf_envelope_complete_lines_only_and_secret_redaction():
config = synthetic_config()
sf = b">SF=" + json.dumps(base64.b64encode(config.encode()).decode()).encode()
assert "SF" not in response_fields(sf)
result = configuration_response(response_fields(b"noise\r\n" + sf + b"\r\n"))
assert result.encode() == config.encode()
public = json.dumps(result.summary())
assert "SYNTHETIC_SECRET" not in public
assert "value_hex" not in public
assert result.summary()["web_configurator"]["check_at_start"] is True
def test_identity_and_sim_are_independent_of_usb_port():
result = parse_identity(response_fields(IDENTITY))
assert result.model_code == 231
assert result.imei == "123456789012345"
assert result.firmware == "0.01"
assert result.iccid2_reported is None
assert result.imei not in repr(result)
assert result.iccid1_reported not in repr(result)
partial_sim = parse_identity(
response_fields(IDENTITY.replace(b"8900000000000000001", b"000000000001"))
)
assert partial_sim.iccid1_reported == "000000000001"
with pytest.raises(ProtocolError, match="unsupported_device_model"):
parse_identity(response_fields(IDENTITY.replace(b"231;", b"230;")))
with pytest.raises(ProtocolError, match="identity_response_incomplete"):
parse_identity(response_fields(IDENTITY.split(b">SID0")[0]))
def test_console_prompt_prefix_does_not_hide_complete_identity_lines():
prompted = IDENTITY.replace(b">DI=", b"> >DI=")
assert parse_identity(response_fields(prompted)) == parse_identity(response_fields(IDENTITY))
assert response_fields(b"noise>DI=231;0;1\r\n") == {}
assert response_fields(b"> >DI=231;0;1") == {}
def test_offline_server_patch_changes_only_requested_slot():
original = synthetic_config()
planned = prepare_server_slot(original, slot=2, host="track.example", port=10001)
before = {r.number: r.value for r in original.records}
after = {r.number: r.value for r in decode_configuration(planned.encode()).records}
assert {key for key in before if before[key] != after[key]} == {3, 4}
assert planned.text(1) == "old.example"
assert planned.text(3) == "track.example"
assert planned.integer(4, 2) == 10001
assert planned.value(135) == original.value(135)
assert planned.value(5) == original.value(5)
@pytest.mark.parametrize(
"host,port",
[("https://track.example", 80), ("bad\r\ncmd", 1), ("a..example", 1), ("track.example", 65536)],
)
def test_invalid_server_plan_is_not_serialized(host, port):
with pytest.raises(ProtocolError):
prepare_server_slot(synthetic_config(), slot=2, host=host, port=port)
def test_discovery_filters_usb_profile_and_keeps_instances_separate():
def tree(port, session, vid=11836):
return (
f'+-o AT32 Virtual Com Port@00110000\n "sessionID" = {session}\n'
f' "idVendor" = {vid}\n "idProduct" = 22336\n'
f' "IOCalloutDevice" = "{port}"\n'
)
result = parse_ioreg(
tree("/dev/cu.usbmodemA", 1)
+ tree("/dev/cu.usbmodemB", 2)
+ tree("/dev/cu.usbmodemOther", 3, 999)
)
assert result == (UsbPort("/dev/cu.usbmodemA", "1"), UsbPort("/dev/cu.usbmodemB", "2"))
def test_snapshot_wrong_model_never_sends_settings_request(monkeypatch, tmp_path):
import fcntl
from k1link.device_plugins.arnavi_b2 import usb_read as reader
candidate = UsbPort("/dev/cu.usbmodemSYNTHETIC", "1")
monkeypatch.setattr(reader, "discover", lambda: (candidate,))
original_open, original_write, original_close = reader.os.open, reader.os.write, reader.os.close
monkeypatch.setattr(
reader.os, "open", lambda p, *a: 999 if p == candidate.path else original_open(p, *a)
)
monkeypatch.setattr(reader.os, "close", lambda fd: None if fd == 999 else original_close(fd))
monkeypatch.setattr(fcntl, "flock", lambda *a: None)
monkeypatch.setattr(reader.termios, "tcgetattr", lambda fd: [0, 0, 0, 0, 9600, 9600])
queue, sent = [], []
clock = [0.0]
def tick():
clock[0] += 0.05
return clock[0]
def write(fd, payload):
if fd != 999:
return original_write(fd, payload)
sent.append(payload)
queue.append(b">DI=999;0;1\r\n")
return len(payload)
monkeypatch.setattr(reader.time, "monotonic", tick)
monkeypatch.setattr(reader.os, "write", write)
monkeypatch.setattr(reader.os, "read", lambda fd, size: queue.pop(0))
monkeypatch.setattr(reader.select, "select", lambda *a: ([999] if queue else [], [], []))
with pytest.raises(reader.UsbReadError, match="unsupported_device_model"):
reader.read_snapshot(tmp_path)
assert sent == [READ_IDENTITY]
assert READ_SETTINGS not in sent
receipts = list(tmp_path.glob("*/receipt.json"))
assert len(receipts) == 1
assert json.loads(receipts[0].read_text())["status"] == "failed"
assert receipts[0].stat().st_mode & 0o777 == 0o600
assert Path(receipts[0].parent).stat().st_mode & 0o777 == 0o700