feat(arnavi): add qualified B2 protocols, USB provisioning and SIM evidence
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
"""Offline audits cannot promote schema defaults or disclose device values."""
|
||||
|
||||
import json
|
||||
|
||||
from k1link.device_plugins.arnavi_b2.configuration_audit import audit
|
||||
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
|
||||
|
||||
|
||||
def sample():
|
||||
raw = Configuration(
|
||||
tuple(
|
||||
Setting(n, value)
|
||||
for n, value in (
|
||||
(1, b"owner.example"),
|
||||
(2, (9922).to_bytes(2, "big")),
|
||||
(3, b"owner.example"),
|
||||
(4, (9922).to_bytes(2, "big")),
|
||||
(111, b""),
|
||||
(112, b"\0\0"),
|
||||
(113, b""),
|
||||
(114, b"\0\0"),
|
||||
(70, b"owner.example"),
|
||||
(71, (9922).to_bytes(2, "big")),
|
||||
(5, b"234567"),
|
||||
(25, b"\0\x0f"),
|
||||
(52, b"private-phone"),
|
||||
(72, b"\0\x10\0\0"),
|
||||
(250, b"unknown-secret"),
|
||||
)
|
||||
)
|
||||
).encode()
|
||||
metadata = {
|
||||
"data": {
|
||||
"settingViewList": [
|
||||
{"alias": f"231_{n}_1", "defaultValue": "schema-only", "setting": {"number": n}}
|
||||
for n in (5, 25, 52, 72, 241)
|
||||
],
|
||||
"sectionList": [
|
||||
{
|
||||
"id": "test",
|
||||
"subSectionList": [
|
||||
{"settingViewAliasList": [f"231_{n}_1" for n in (5, 25, 52, 72, 241)]}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
return raw, metadata
|
||||
|
||||
|
||||
def test_audit_separates_presence_overlay_and_unknown_fields_without_values():
|
||||
raw, metadata = sample()
|
||||
result = audit(raw, metadata, ("owner.example", 9922))
|
||||
assert result["record_count"] == 15 and result["portable_scalar_count"] == 1
|
||||
assert result["portable_noop_exact"] and result["owner_channels_only"]
|
||||
assert 250 in result["unknown_to_metadata"]
|
||||
assert 241 in result["portable_catalog_missing"]
|
||||
section = result["sections"][0]
|
||||
assert section["portable_scalars"] == [25]
|
||||
assert section["specialized_records"] == [72]
|
||||
assert section["preserved_only"] == [5, 52]
|
||||
assert section["absent_records"] == [241]
|
||||
for secret in ("234567", "private-phone", "unknown-secret", "owner.example", "schema-only"):
|
||||
assert secret not in json.dumps(result)
|
||||
|
||||
|
||||
def test_other_optional_destination_prevents_owner_only_claim():
|
||||
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
|
||||
|
||||
raw, metadata = sample()
|
||||
cfg = decode_configuration(raw)
|
||||
changed = Configuration(
|
||||
tuple(
|
||||
Setting(
|
||||
r.number,
|
||||
{
|
||||
111: b"third-party.example",
|
||||
112: (1234).to_bytes(2, "big"),
|
||||
}.get(r.number, r.value),
|
||||
)
|
||||
for r in cfg.records
|
||||
)
|
||||
).encode()
|
||||
result = audit(changed, metadata, ("owner.example", 9922))
|
||||
assert result["channels"]["monitoring_3"] == "other"
|
||||
assert not result["owner_channels_only"]
|
||||
assert "third-party.example" not in json.dumps(result)
|
||||
|
||||
|
||||
def test_wrong_width_is_not_synthesized_from_a_schema_default():
|
||||
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
|
||||
|
||||
raw, metadata = sample()
|
||||
config = decode_configuration(raw)
|
||||
raw = Configuration(
|
||||
tuple(Setting(r.number, b"\x0f" if r.number == 25 else r.value) for r in config.records)
|
||||
).encode()
|
||||
result = audit(raw, metadata, ("owner.example", 9922))
|
||||
assert result["portable_scalar_count"] == 0
|
||||
assert result["portable_catalog_incompatible"] == [25]
|
||||
assert result["portable_noop_exact"]
|
||||
@@ -0,0 +1,204 @@
|
||||
"""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
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Transaction failure cases with synthetic configurations; no physical USB."""
|
||||
|
||||
import base64
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.device_plugins.arnavi_b2.usb_protocol import (
|
||||
Configuration,
|
||||
Identity,
|
||||
ProtocolError,
|
||||
Setting,
|
||||
)
|
||||
from k1link.device_plugins.arnavi_b2.usb_read import UsbReadError
|
||||
from k1link.device_plugins.arnavi_b2.usb_write import envelope, transact, write_all
|
||||
|
||||
IDENTITY = Identity(231, "123456", "123456789012345", "0.01", None, "89000000000000000001")
|
||||
BEFORE = Configuration((Setting(5, b"123456"), Setting(25, b"\0\x0f"), Setting(135, b"opaque")))
|
||||
|
||||
|
||||
class Fake:
|
||||
def __init__(self, outcome="apply"):
|
||||
self.outcome, self.current, self.commands = outcome, BEFORE, []
|
||||
|
||||
def identity(self):
|
||||
return IDENTITY
|
||||
|
||||
def settings(self):
|
||||
return self.current
|
||||
|
||||
def write(self, command):
|
||||
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
|
||||
|
||||
self.commands.append(command)
|
||||
if self.outcome == "lost":
|
||||
raise OSError("lost")
|
||||
if self.outcome == "unchanged":
|
||||
return False
|
||||
target = decode_configuration(base64.b64decode(command[12:-2]))
|
||||
self.current = (
|
||||
Configuration((Setting(5, b"123456"), Setting(25, b"\0\x07"), Setting(135, b"opaque")))
|
||||
if self.outcome == "partial" and len(self.commands) == 1
|
||||
else target
|
||||
)
|
||||
return self.outcome != "no_ack"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"outcome,state,writes",
|
||||
[
|
||||
("apply", "applied", 1),
|
||||
("no_ack", "applied", 1),
|
||||
("unchanged", "not_applied", 1),
|
||||
("lost", "uncertain", 1),
|
||||
("partial", "rolled_back", 2),
|
||||
],
|
||||
)
|
||||
def test_readback_not_ack_is_authoritative_and_writes_are_bounded(outcome, state, writes):
|
||||
transport = Fake(outcome)
|
||||
backups = []
|
||||
|
||||
def backup(before, target):
|
||||
assert not transport.commands
|
||||
backups.append((before, target))
|
||||
|
||||
result = transact(transport, IDENTITY, BEFORE, {"parameters": {"25": 30}}, backup)
|
||||
assert result["state"] == state
|
||||
assert len(transport.commands) == writes
|
||||
assert result["changed_fields"] == [25]
|
||||
assert backups[0][0] == BEFORE
|
||||
if state == "rolled_back":
|
||||
assert transport.current == BEFORE
|
||||
|
||||
|
||||
def test_changed_sim_or_settings_or_unsupported_firmware_never_writes():
|
||||
for expected, before in [
|
||||
(replace(IDENTITY, iccid2_reported="89000000000000000002"), BEFORE),
|
||||
(replace(IDENTITY, firmware="0.02"), BEFORE),
|
||||
(IDENTITY, Configuration((Setting(5, b"123456"),))),
|
||||
]:
|
||||
transport = Fake()
|
||||
with pytest.raises(ProtocolError):
|
||||
transact(transport, expected, before, {"parameters": {"25": 30}}, lambda *_: None)
|
||||
assert not transport.commands
|
||||
|
||||
|
||||
def test_backup_failure_prevents_write_and_noop_does_not_rewrite_flash():
|
||||
transport = Fake()
|
||||
|
||||
def fail(*_):
|
||||
raise OSError("disk full")
|
||||
|
||||
with pytest.raises(OSError):
|
||||
transact(transport, IDENTITY, BEFORE, {"parameters": {"25": 30}}, fail)
|
||||
assert not transport.commands
|
||||
assert transact(transport, IDENTITY, BEFORE, {}, lambda *_: None)["state"] == "unchanged"
|
||||
assert not transport.commands
|
||||
|
||||
|
||||
def test_envelope_has_only_qualified_command_and_rejects_password_change():
|
||||
assert envelope(BEFORE, BEFORE) == b"123456*CONF*" + base64.b64encode(BEFORE.encode()) + b"\r\n"
|
||||
with pytest.raises(ProtocolError):
|
||||
envelope(BEFORE, Configuration((Setting(5, b"654321"),)))
|
||||
|
||||
|
||||
def test_nonblocking_tty_completes_short_write_without_repeating_prefix(monkeypatch):
|
||||
from k1link.device_plugins.arnavi_b2 import usb_write
|
||||
|
||||
payload = bytes(range(256)) * 5 + b"\r\n"
|
||||
received = bytearray()
|
||||
calls = []
|
||||
|
||||
def send(fd, suffix):
|
||||
calls.append(suffix)
|
||||
if len(calls) == 2:
|
||||
raise BlockingIOError()
|
||||
count = min(1024, len(suffix))
|
||||
received.extend(suffix[:count])
|
||||
return count
|
||||
|
||||
monkeypatch.setattr(usb_write.os, "write", send)
|
||||
monkeypatch.setattr(usb_write.select, "select", lambda *args: ([], [42], []))
|
||||
progress = []
|
||||
write_all(42, payload, progress.append)
|
||||
assert bytes(received) == payload
|
||||
assert calls == [payload, payload[1024:], payload[1024:]]
|
||||
assert progress == [1024, len(payload)]
|
||||
|
||||
|
||||
def test_write_deadline_preserves_prefix_and_never_restarts_frame(monkeypatch):
|
||||
from k1link.device_plugins.arnavi_b2 import usb_write
|
||||
|
||||
ticks = iter([0, 0, 9])
|
||||
calls = []
|
||||
monkeypatch.setattr(usb_write.time, "monotonic", lambda: next(ticks))
|
||||
monkeypatch.setattr(usb_write.select, "select", lambda *args: ([], [42], []))
|
||||
monkeypatch.setattr(usb_write.os, "write", lambda fd, b: calls.append(b) or 2)
|
||||
progress = []
|
||||
with pytest.raises(UsbReadError, match="usb_write_timeout"):
|
||||
write_all(42, b"synthetic-frame\r\n", progress.append)
|
||||
assert calls == [b"synthetic-frame\r\n"]
|
||||
assert progress == [2]
|
||||
|
||||
|
||||
def test_mts_readback_is_exact_and_preserves_unmodified_null_terminated_strings():
|
||||
from k1link.device_plugins.arnavi_b2.profiles import prepare
|
||||
|
||||
before = Configuration(
|
||||
(
|
||||
Setting(5, b"123456"),
|
||||
Setting(67, b"internet\0"),
|
||||
Setting(89, b""),
|
||||
Setting(90, b""),
|
||||
Setting(91, b""),
|
||||
)
|
||||
)
|
||||
policy = {
|
||||
"connectivity": {
|
||||
"strategy": "operator",
|
||||
"preset_id": "ru-mts-public-v1",
|
||||
"sim_slot": 2,
|
||||
}
|
||||
}
|
||||
target = prepare(before, policy)
|
||||
assert target.value(89) == b"internet.mts.ru"
|
||||
assert target.value(90) == target.value(91) == b"mts"
|
||||
assert target.value(67) == before.value(67)
|
||||
assert prepare(target, policy).encode() == target.encode()
|
||||
|
||||
|
||||
def test_configuration_service_bootstrap_preserves_every_other_record():
|
||||
from k1link.device_plugins.arnavi_b2.usb_write import configuration_service_target
|
||||
|
||||
before = Configuration(
|
||||
BEFORE.records + (Setting(70, b"vendor.example"), Setting(71, b"\x24\x0f"))
|
||||
)
|
||||
target = configuration_service_target(before, {"host": "owner.example", "port": 9922})
|
||||
assert target.text(70) == "owner.example"
|
||||
assert target.integer(71, 2) == 9922
|
||||
assert [(r.number, r.value) for r in target.records if r.number not in (70, 71)] == [
|
||||
(r.number, r.value) for r in BEFORE.records
|
||||
]
|
||||
for value in ("https://owner.example/", "bad\r\ncommand"):
|
||||
with pytest.raises(ValueError):
|
||||
configuration_service_target(before, {"host": value, "port": 9922})
|
||||
|
||||
|
||||
def test_initial_provisioning_sets_monitoring_and_configuration_channel_together():
|
||||
from k1link.device_plugins.arnavi_b2.usb_write import bootstrap_target
|
||||
|
||||
before = Configuration(
|
||||
BEFORE.records
|
||||
+ tuple(
|
||||
Setting(n, v)
|
||||
for n, v in (
|
||||
(1, b"vendor.example"),
|
||||
(2, b"\x24\x0f"),
|
||||
(9, b"\0"),
|
||||
(3, b""),
|
||||
(4, b"\0\0"),
|
||||
(8, b"\0"),
|
||||
(70, b"vendor.example"),
|
||||
(71, b"\x24\x0f"),
|
||||
(72, b"\x80\x00\x08\x19"),
|
||||
(62, b"\x00\x96"),
|
||||
)
|
||||
)
|
||||
)
|
||||
policy = {
|
||||
"endpoint": {"slot": 1, "host": "owner.example", "port": 9922},
|
||||
"parameters": {"25": 16},
|
||||
}
|
||||
target = bootstrap_target(before, policy)
|
||||
assert all(target.text(n) == "owner.example" for n in (1, 3, 70))
|
||||
assert all(target.integer(n, 2) == 9922 for n in (2, 4, 71))
|
||||
assert target.integer(25, 2) == 16
|
||||
assert target.integer(72, 4) == before.integer(72, 4) & ~1
|
||||
assert target.value(62) == before.value(62)
|
||||
assert [r.number for r in target.records if r.value != before.value(r.number)] == [
|
||||
25,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
70,
|
||||
71,
|
||||
72,
|
||||
]
|
||||
assert target.value(135) == before.value(135) and target.value(5) == before.value(5)
|
||||
assert bootstrap_target(target, policy).encode() == target.encode()
|
||||
with pytest.raises(ProtocolError):
|
||||
bootstrap_target(before, {"parameters": {"25": 16}})
|
||||
# An absent or malformed bitset must fail before backing up/sending a write.
|
||||
for value in (None, b"\x01", b"\x00" * 5):
|
||||
records = tuple(r for r in before.records if r.number != 72)
|
||||
if value is not None:
|
||||
records += (Setting(72, value),)
|
||||
transport = Fake()
|
||||
transport.current = Configuration(records)
|
||||
backups = []
|
||||
with pytest.raises(ProtocolError):
|
||||
transact(
|
||||
transport,
|
||||
IDENTITY,
|
||||
transport.current,
|
||||
policy,
|
||||
lambda *args, backups=backups: backups.append(args),
|
||||
prepare_target=bootstrap_target,
|
||||
)
|
||||
assert not transport.commands and not backups
|
||||
|
||||
|
||||
def test_bootstrap_uses_one_backed_up_verified_usb_transaction():
|
||||
from k1link.device_plugins.arnavi_b2.usb_write import bootstrap_target
|
||||
|
||||
before = Configuration(
|
||||
BEFORE.records
|
||||
+ tuple(
|
||||
Setting(n, v)
|
||||
for n, v in (
|
||||
(1, b"vendor.example"),
|
||||
(2, b"\x24\x0f"),
|
||||
(9, b"\0"),
|
||||
(3, b""),
|
||||
(4, b"\0\0"),
|
||||
(8, b"\0"),
|
||||
(70, b"vendor.example"),
|
||||
(71, b"\x24\x0f"),
|
||||
(72, b"\x00\x00\x08\x19"),
|
||||
)
|
||||
)
|
||||
)
|
||||
t = Fake()
|
||||
t.current = before
|
||||
backups = []
|
||||
result = transact(
|
||||
t,
|
||||
IDENTITY,
|
||||
before,
|
||||
{"endpoint": {"slot": 1, "host": "owner.example", "port": 9922}},
|
||||
lambda a, b: backups.append((a, b)),
|
||||
prepare_target=bootstrap_target,
|
||||
)
|
||||
assert result["state"] == "applied" and len(t.commands) == len(backups) == 1
|
||||
assert t.current == backups[0][1] and backups[0][0] == before
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Bounded configuration HTTP framing, independent from monitoring packets."""
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, ProtocolError, Setting
|
||||
from k1link.device_plugins.arnavi_b2.web_protocol import (
|
||||
decode_request,
|
||||
decode_settings_reply,
|
||||
settings_reply,
|
||||
time_reply,
|
||||
)
|
||||
|
||||
|
||||
def request(command, payload=b""):
|
||||
body = int("123456789012345").to_bytes(8, "little") + bytes.fromhex("0001e7020000")
|
||||
body += bytes([command]) + payload
|
||||
return b"[\x01" + len(body).to_bytes(2, "big") + body + b"]"
|
||||
|
||||
|
||||
def test_upload_preserves_unknown_records_and_read_request_has_no_settings():
|
||||
config = Configuration((Setting(62, b"\x00\x96"), Setting(222, b"opaque\x00\xff")))
|
||||
imei, cmd, payload = decode_request(request(5, config.encode()))
|
||||
assert imei == "123456789012345" and cmd == 5
|
||||
assert payload == config.encode()
|
||||
assert decode_request(request(2))[1:] == (2, b"")
|
||||
assert decode_request(request(6, b"\x02"))[1:] == (6, b"\x02")
|
||||
reply = settings_reply(config)
|
||||
assert decode_settings_reply(reply).encode() == config.encode()
|
||||
assert reply[3:5] == b"\x00\x02"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
[
|
||||
request(1, b"extra"),
|
||||
request(2, b"extra"),
|
||||
request(6, b"\x01"),
|
||||
request(5, b"no-crc"),
|
||||
request(2).replace(bytes.fromhex("e702"), bytes.fromhex("e703")),
|
||||
request(2)[:-1],
|
||||
request(2) + b"extra",
|
||||
b"\xff\x23" + b"x" * 18,
|
||||
],
|
||||
)
|
||||
def test_unqualified_requests_fail_closed(raw):
|
||||
with pytest.raises(ProtocolError):
|
||||
decode_request(raw)
|
||||
|
||||
|
||||
def test_reply_wrong_size_status_command_and_crc_fail_closed():
|
||||
raw = settings_reply(Configuration((Setting(62, b"\x00\x96"),)))
|
||||
for position in (0, 1, 2, 3, 4, 7, 8, 10, len(raw) - 1):
|
||||
changed = bytearray(raw)
|
||||
changed[position] ^= 1
|
||||
with pytest.raises(ProtocolError):
|
||||
decode_settings_reply(bytes(changed))
|
||||
|
||||
|
||||
def test_engineering_empty_check_admission_never_accepts_images_or_unknown_opcodes():
|
||||
assert decode_request(request(1), observe_empty_check=True)[1:] == (1, b"")
|
||||
for raw in (request(1, b"image"), request(3), request(4), request(1) + b"extra"):
|
||||
with pytest.raises(ProtocolError):
|
||||
decode_request(raw, observe_empty_check=True)
|
||||
|
||||
|
||||
def test_empty_time_request_and_big_endian_utc_reply():
|
||||
assert decode_request(request(7))[1:] == (7, b"")
|
||||
assert time_reply(1700000000) == bytes.fromhex("5b000600076553f1005d")
|
||||
for raw in (request(7, b"extra"), request(7).replace(b"\xe7\x02", b"\xe7\x03")):
|
||||
with pytest.raises(ProtocolError):
|
||||
decode_request(raw)
|
||||
for value in (True, 0, -1, 2**32, 1700000000.0, "1700000000"):
|
||||
with pytest.raises(ProtocolError):
|
||||
time_reply(value)
|
||||
Reference in New Issue
Block a user