255 lines
10 KiB
Python
255 lines
10 KiB
Python
"""Synthetic SIMs only; regression cases derived from qualified B2 0.01 reads."""
|
|
|
|
import hashlib
|
|
import json
|
|
import uuid
|
|
from dataclasses import asdict, replace
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import pytest
|
|
|
|
from k1link.device_plugins.arnavi_b2.enrollment import B2Enrollment
|
|
from k1link.device_plugins.arnavi_b2.sim_identity import (
|
|
capture_from_read,
|
|
modem_observations,
|
|
reported_state,
|
|
)
|
|
from k1link.device_plugins.arnavi_b2.sim_observation_store import (
|
|
SimObservationStore,
|
|
load_capture,
|
|
snapshot_details,
|
|
)
|
|
from k1link.device_plugins.arnavi_b2.usb_protocol import (
|
|
Configuration,
|
|
Identity,
|
|
ProtocolError,
|
|
Setting,
|
|
)
|
|
from k1link.fleet.independent_equipment import EquipmentStore
|
|
|
|
CARD_A = ("89000000000000000010", "89000000000000000010", "250010000000001", "25001")
|
|
CARD_B = ("890000000000000002ff", "89000000000000000273", "250020000000002", "25002")
|
|
SHORT = "100000000007"
|
|
IMEI = "000000000000001"
|
|
|
|
|
|
def exchange(slot, card):
|
|
raw, sid, imsi, home = card
|
|
return (
|
|
f"AT+CCID\r\r\n{raw}\r\n\r\nOK\r\n>SID{slot - 1}={sid}\r\n"
|
|
f"AT+CIMI\r\r\n{imsi}\r\n\r\nOK\r\nHC{slot - 1}={home}\r\n"
|
|
).encode()
|
|
|
|
|
|
def sample(raw=b"", reports=(SHORT, CARD_B[1]), second=0, tracker=IMEI):
|
|
start = datetime(2026, 1, 1, tzinfo=UTC) + timedelta(seconds=second)
|
|
identity = Identity(231, "1", tracker, "0.01", *reports)
|
|
raw += (
|
|
f">DI=231;0;1\r\n>DN=1\r\n>MN={tracker}\r\n"
|
|
f">SID0={reports[0] or ''}\r\n>SID1={reports[1] or ''}\r\n"
|
|
).encode()
|
|
receipt = {
|
|
"session_id": "arnavi-read-" + uuid.uuid4().hex,
|
|
"started_at_utc": start.isoformat(),
|
|
"completed_at_utc": (start + timedelta(seconds=1)).isoformat(),
|
|
"usb_before": {"path": "/dev/cu.synthetic", "session": str(second)},
|
|
"usb_after": {"path": "/dev/cu.synthetic", "session": str(second)},
|
|
"status": "settings_read",
|
|
"raw_sha256": hashlib.sha256(raw).hexdigest(),
|
|
}
|
|
return identity, raw, receipt
|
|
|
|
|
|
def capture(*args, **kwargs):
|
|
return capture_from_read(*sample(*args, **kwargs))
|
|
|
|
|
|
def snapshot(evidence, source):
|
|
identity, raw, receipt = source
|
|
directory = evidence / receipt["session_id"]
|
|
directory.mkdir(mode=0o700, parents=True)
|
|
(directory / "identity.json").write_text(json.dumps(asdict(identity)))
|
|
(directory / "response.bin").write_bytes(raw)
|
|
(directory / "receipt.json").write_text(json.dumps(receipt))
|
|
(directory / "configuration.bin").write_bytes(
|
|
Configuration((Setting(25, b"\x00\x0f"), Setting(20, b"\x01"))).encode()
|
|
)
|
|
return directory
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"value,state",
|
|
[
|
|
(None, "not_reported"),
|
|
(SHORT, "incomplete"),
|
|
(CARD_B[1], "unverified"),
|
|
(CARD_A[0], "unverified"),
|
|
],
|
|
)
|
|
def test_i7_length_never_confirms_canonical_iccid(value, state):
|
|
assert reported_state(value) == state
|
|
|
|
|
|
def test_modem_sources_remain_distinct_and_private():
|
|
value = modem_observations(exchange(2, CARD_B))[0]
|
|
assert value.slot == 2 and value.qualified
|
|
assert value.raw_ccid == CARD_B[0] and value.firmware_sid == CARD_B[1]
|
|
assert value.public()["ccid_format"] == "vendor_ff"
|
|
assert value.public()["ccid_equals_sid"] is False
|
|
for secret in CARD_B[:3]:
|
|
assert secret not in repr(value) and secret not in json.dumps(value.public())
|
|
assert modem_observations(exchange(1, CARD_A))[0].public()["ccid_equals_sid"] is True
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"raw",
|
|
[
|
|
exchange(1, CARD_A).replace(b"HC0=", b"HC1="),
|
|
exchange(1, CARD_A).replace(b"AT+CIMI", b"ERROR\r\nAT+CIMI"),
|
|
exchange(1, CARD_A).replace(b"AT+CIMI", b"AT+CDSDS=2,0\r\nAT+CIMI"),
|
|
exchange(1, CARD_A)[:-1],
|
|
exchange(1, CARD_A).replace(b"OK", b"ERROR", 1),
|
|
],
|
|
)
|
|
def test_incomplete_interleaved_or_failed_exchange_cannot_bind_card(raw):
|
|
assert modem_observations(raw) == ()
|
|
|
|
|
|
def test_inconsistent_home_code_and_unknown_ccid_format_are_not_qualified():
|
|
for card in [
|
|
(CARD_A[0], CARD_A[1], CARD_A[2], "25002"),
|
|
("a" * 20, CARD_A[1], CARD_A[2], CARD_A[3]),
|
|
]:
|
|
value = capture(exchange(1, card))
|
|
assert value.unique_for_slot(1) is None
|
|
slot = value.public()["slots"][0]
|
|
assert slot["modem_state"] == "unresolved"
|
|
assert slot["modem_observations"][0]["home_network"] is None
|
|
|
|
|
|
def test_repetition_is_ok_but_different_cards_in_one_slot_are_ambiguous():
|
|
assert capture(exchange(1, CARD_A) * 2).unique_for_slot(1) is not None
|
|
assert capture(exchange(1, CARD_A) + exchange(1, CARD_B)).unique_for_slot(1) is None
|
|
duplicate = capture(exchange(1, CARD_A) + exchange(2, CARD_A))
|
|
assert all(s["modem_state"] == "unresolved" for s in duplicate.public()["slots"])
|
|
|
|
|
|
def test_swap_retains_card_refs_and_short_reads_do_not_replace_history(tmp_path):
|
|
journal = SimObservationStore(tmp_path)
|
|
first = capture(exchange(1, CARD_B) + exchange(2, CARD_A), reports=(SHORT, CARD_A[1]))
|
|
a = journal.record(first)["slots"]
|
|
swapped = capture(exchange(1, CARD_A) + exchange(2, CARD_B), second=10)
|
|
b = journal.record(swapped)["slots"]
|
|
assert a[0]["captured_card_ref"] == b[1]["captured_card_ref"]
|
|
assert a[1]["captured_card_ref"] == b[0]["captured_card_ref"]
|
|
assert b[0]["reported"]["state"] == "incomplete"
|
|
assert b[0]["readback_matches_modem_sid"] is False
|
|
assert b[1]["readback_matches_modem_sid"] is True
|
|
# Reopen, then arbitrarily many incomplete observations: no last-value overwrite.
|
|
journal = SimObservationStore(tmp_path)
|
|
for i in range(40):
|
|
latest = journal.record(capture(reports=(SHORT, None), second=20 + i * 2))
|
|
for slot in latest["slots"]:
|
|
previous = slot["previous_modem_observation"]
|
|
assert previous["capture_id"] == swapped.capture_id
|
|
assert previous["historical"] is True and previous["current_slot_binding"] is False
|
|
assert slot["captured_card_ref"] is None and slot["modem_state"] == "not_observed"
|
|
assert latest["automatic_write_authorized"] is False
|
|
assert journal.record(first)["slots"] == a # Retry idempotence + no future history leakage.
|
|
assert journal.path.stat().st_mode & 0o077 == 0
|
|
assert journal.path.parent.stat().st_mode & 0o077 == 0
|
|
public = json.dumps(latest) + json.dumps(a) + json.dumps(b)
|
|
for secret in (*CARD_A[:3], *CARD_B[:3], SHORT, IMEI):
|
|
assert secret not in public
|
|
|
|
|
|
def test_conflicting_capture_id_cannot_mutate_or_leak_evidence(tmp_path):
|
|
journal = SimObservationStore(tmp_path)
|
|
value = capture(exchange(1, CARD_A))
|
|
original = journal.record(value)
|
|
with pytest.raises(ProtocolError, match="^sim_capture_id_conflict$"):
|
|
journal.record(replace(value, reported=(CARD_B[1], None)))
|
|
with pytest.raises(ProtocolError, match="^sim_capture_id_conflict$"):
|
|
journal.public(replace(value, reported=(CARD_B[1], None)))
|
|
assert journal.public(value) == original
|
|
|
|
|
|
def test_same_card_on_different_tracker_has_no_shared_reference_or_history(tmp_path):
|
|
journal = SimObservationStore(tmp_path)
|
|
first = journal.record(capture(exchange(1, CARD_A)))["slots"][0]
|
|
second = journal.record(capture(exchange(1, CARD_A), tracker="000000000000002", second=10))
|
|
assert second["slots"][0]["captured_card_ref"] != first["captured_card_ref"]
|
|
assert second["slots"][0]["previous_modem_observation"] is None
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"change",
|
|
[
|
|
{"raw_sha256": "0" * 64},
|
|
{"status": "failed"},
|
|
{"usb_after": {"session": "other"}},
|
|
{"started_at_utc": "2026-01-01T00:00:00"},
|
|
{"completed_at_utc": "2025-12-31T00:00:00+00:00"},
|
|
],
|
|
)
|
|
def test_failed_changed_or_unattributable_capture_is_rejected(change):
|
|
identity, raw, receipt = sample()
|
|
with pytest.raises(ProtocolError, match="^sim_capture_unqualified$"):
|
|
capture_from_read(identity, raw, {**receipt, **change})
|
|
|
|
|
|
def test_unqualified_firmware_does_not_inherit_modem_parser_qualification():
|
|
identity, raw, receipt = sample(exchange(1, CARD_A))
|
|
result = capture_from_read(replace(identity, firmware="0.02"), raw, receipt)
|
|
assert result.exchanges == () and result.reported == (SHORT, CARD_B[1])
|
|
|
|
|
|
def test_missing_or_tampered_evidence_is_unavailable_not_empty_sim(tmp_path):
|
|
directory = snapshot(tmp_path, sample(exchange(1, CARD_A)))
|
|
assert load_capture(directory).for_slot(1)
|
|
(directory / "response.bin").write_bytes(b"tampered")
|
|
public = snapshot_details(directory, record=True)
|
|
assert public == {"sim_identity": {"state": "unavailable", "automatic_write_authorized": False}}
|
|
assert not SimObservationStore(tmp_path).path.exists()
|
|
|
|
|
|
def test_symlink_store_is_rejected_without_touching_target(tmp_path):
|
|
target = tmp_path / "foreign"
|
|
target.mkdir()
|
|
(tmp_path / "sim-identity").symlink_to(target, target_is_directory=True)
|
|
with pytest.raises(ProtocolError, match="sim_store_unavailable"):
|
|
SimObservationStore(tmp_path).record(capture())
|
|
assert list(target.iterdir()) == []
|
|
|
|
|
|
def test_product_refresh_keeps_identity_history_out_of_profiles(tmp_path, monkeypatch):
|
|
from k1link.device_plugins.arnavi_b2 import enrollment
|
|
|
|
sources = iter(
|
|
[
|
|
sample(exchange(1, CARD_A), reports=(CARD_A[1], None)),
|
|
sample(reports=(SHORT, None), second=10),
|
|
]
|
|
)
|
|
|
|
def reader(evidence):
|
|
directory = snapshot(evidence, next(sources))
|
|
return {"evidence_directory": str(directory), **snapshot_details(directory, record=True)}
|
|
|
|
monkeypatch.setattr(enrollment, "read_snapshot", reader)
|
|
store = EquipmentStore(tmp_path, {"arnavi-b2": B2Enrollment()})
|
|
item = store.add(store.inspect("arnavi-b2")["id"], "Test B2", "rover-a")
|
|
original = item["observed"]["sim_identity"]["slots"][0]
|
|
current = store.refresh_observation(item["id"], item["revision"])
|
|
reopened = EquipmentStore(tmp_path, {"arnavi-b2": B2Enrollment()}).listing()[0]
|
|
assert reopened == current
|
|
slot = current["observed"]["sim_identity"]["slots"][0]
|
|
assert slot["reported"]["state"] == "incomplete"
|
|
assert slot["previous_modem_observation"]["card_ref"] == original["captured_card_ref"]
|
|
assert current["settings"] == item["settings"]
|
|
assert (
|
|
"sim_identity" not in store.save_profile("Test", "arnavi-b2", item["settings"])["settings"]
|
|
)
|
|
for secret in (*CARD_A[:3], SHORT, IMEI):
|
|
assert secret not in json.dumps(current)
|