366 lines
14 KiB
Python
366 lines
14 KiB
Python
"""Synthetic identity only. No USB, vendor service or actual vehicle access."""
|
|
|
|
import json
|
|
import threading
|
|
import time
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
from pydantic import ValidationError
|
|
|
|
from k1link.device_plugins.arnavi_b2.profiles import Policy, portable, prepare
|
|
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, ProtocolError, Setting
|
|
from k1link.fleet.independent_equipment import EquipmentError, EquipmentStore
|
|
from k1link.web.independent_equipment_api import CommandRequest, router
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"body",
|
|
[
|
|
{"kind": "set-output", "pin": 5, "enabled": "false"},
|
|
{"kind": "set-output", "pin": 5, "enabled": 1},
|
|
{"kind": "pulse-output", "pin": "5", "seconds": 2},
|
|
{"kind": "pulse-output", "pin": 5, "seconds": 6},
|
|
{"kind": "request-position", "password": "123456"},
|
|
],
|
|
)
|
|
def test_command_api_rejects_coercion_and_private_credentials(body):
|
|
with pytest.raises(ValidationError):
|
|
CommandRequest(expected_revision=1, **body)
|
|
|
|
|
|
def config():
|
|
return Configuration(
|
|
(
|
|
Setting(25, b"\x00\x0f"),
|
|
Setting(63, b"\x0a"),
|
|
Setting(1, b"example.test\x00"),
|
|
Setting(2, b"\x50\x8f"),
|
|
Setting(9, b"\x00"),
|
|
Setting(67, b"old.apn\x00"),
|
|
Setting(89, b""),
|
|
Setting(68, b"private-login"),
|
|
Setting(5, b"123456"),
|
|
Setting(135, b"unknown"),
|
|
Setting(243, (-100).to_bytes(2, "big", signed=True)),
|
|
)
|
|
)
|
|
|
|
|
|
class Adapter:
|
|
model_id = "arnavi-b2"
|
|
identity = "000000000000001"
|
|
|
|
def catalog(self):
|
|
return {"id": self.model_id}
|
|
|
|
def validate_policy(self, value):
|
|
return Policy.model_validate(value).model_dump()
|
|
|
|
def inspect(self, evidence):
|
|
return {
|
|
"identity_key": self.identity,
|
|
"model_id": self.model_id,
|
|
"observed": {"imei_suffix": self.identity[-5:]},
|
|
"evidence_id": "synthetic",
|
|
"settings": portable(config()),
|
|
}
|
|
|
|
def check_policy(self, candidate, evidence, settings):
|
|
prepare(config(), settings)
|
|
|
|
def apply(self, instance, evidence):
|
|
return {"policy_state": "applied", "operation": {"state": "applied"}}
|
|
|
|
|
|
@pytest.fixture
|
|
def store(tmp_path):
|
|
return EquipmentStore(tmp_path, {"arnavi-b2": Adapter()})
|
|
|
|
|
|
def test_apply_serializes_saved_policy_and_stale_revision_cannot_repeat_it(store):
|
|
candidate = store.inspect("arnavi-b2")
|
|
item = store.add(candidate["id"], "Tracker", "vehicle-a")
|
|
applied = store.apply(item["id"], item["revision"])
|
|
assert applied["policy_state"] == "applied"
|
|
assert applied["revision"] == item["revision"] + 1
|
|
assert applied["vehicle_id"] == "vehicle-a"
|
|
with pytest.raises(EquipmentError):
|
|
store.apply(item["id"], item["revision"])
|
|
changed = store.update(applied["id"], applied["revision"], "Tracker", "vehicle-a", {})
|
|
assert changed["policy_state"] == "saved"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"extra", ["imei", "sim", "operator", "vehicle_id", "password", "raw_configuration"]
|
|
)
|
|
def test_unique_data_and_unknown_fields_are_rejected(extra):
|
|
with pytest.raises(ValidationError):
|
|
Policy.model_validate({extra: "secret"})
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"params",
|
|
[
|
|
{"5": 123456},
|
|
{"68": 1},
|
|
{"25": True},
|
|
{"25": "15"},
|
|
{"25": 65536},
|
|
{"243": -10001},
|
|
{"243": 100, "244": 0},
|
|
],
|
|
)
|
|
def test_secret_fields_invalid_types_ranges_and_relations_rejected(params):
|
|
with pytest.raises(ValidationError):
|
|
Policy.model_validate({"parameters": params})
|
|
|
|
|
|
def test_portable_profile_is_not_config_clone():
|
|
value = portable(config())
|
|
assert value["parameters"] == {"25": 15, "63": 10, "243": -100}
|
|
text = json.dumps(value)
|
|
for secret in ["123456", "private-login", "old.apn", "unknown"]:
|
|
assert secret not in text
|
|
assert value["endpoint"] is None
|
|
assert value["connectivity"]["strategy"] == "preserve"
|
|
|
|
|
|
def test_overlay_preserves_unknown_identity_secrets_and_handles_explicit_zero():
|
|
before = config()
|
|
policy = {
|
|
"parameters": {"25": 0},
|
|
"endpoint": {"host": "track.example.test", "port": 9023, "slot": 1},
|
|
}
|
|
result = prepare(before, policy)
|
|
assert result.integer(25, 2) == 0
|
|
assert result.text(1) == "track.example.test"
|
|
for number in [5, 63, 67, 68, 135, 243]:
|
|
assert result.value(number) == before.value(number)
|
|
assert result.records[-1].number == 243
|
|
with pytest.raises(ProtocolError):
|
|
prepare(before, {"parameters": {"246": 70}})
|
|
|
|
|
|
def test_explicit_apn_only_and_no_carrier_guess():
|
|
with pytest.raises(ValidationError):
|
|
Policy.model_validate({"connectivity": {"strategy": "auto"}})
|
|
with pytest.raises(ValidationError):
|
|
Policy.model_validate({"connectivity": {"strategy": "manual"}})
|
|
after = prepare(config(), {"connectivity": {"strategy": "manual", "apn1": "iot.example"}})
|
|
assert after.text(67) == "iot.example"
|
|
assert after.text(68) == "private-login"
|
|
|
|
|
|
def test_operator_preset_replaces_complete_access_only_for_selected_sim():
|
|
before = Configuration(
|
|
config().records
|
|
+ (
|
|
Setting(69, b"private-password"),
|
|
Setting(90, b"other-login"),
|
|
Setting(91, b"other-password"),
|
|
)
|
|
)
|
|
policy = {
|
|
"connectivity": {
|
|
"strategy": "operator",
|
|
"preset_id": "ru-mts-public-v1",
|
|
"sim_slot": 2,
|
|
}
|
|
}
|
|
after = prepare(before, policy)
|
|
assert [after.text(n) for n in (89, 90, 91)] == ["internet.mts.ru", "mts", "mts"]
|
|
assert {r.number for r in before.records if r.value != after.value(r.number)} == {89, 90, 91}
|
|
# Portable policy carries a public preset reference, never old private access strings.
|
|
saved = json.dumps(Policy.model_validate(policy).model_dump())
|
|
assert "private-password" not in saved and "other-password" not in saved
|
|
assert portable(after)["connectivity"]["strategy"] == "preserve"
|
|
with pytest.raises(ProtocolError):
|
|
prepare(config(), policy) # Missing second-SIM credential fields fails before writing.
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"connection",
|
|
[
|
|
{"strategy": "operator"},
|
|
{"strategy": "operator", "preset_id": "guessed-carrier"},
|
|
{"strategy": "operator", "preset_id": "ru-mts-public-v1", "sim_slot": True},
|
|
{"strategy": "operator", "preset_id": "ru-mts-public-v1", "sim_slot": 3},
|
|
{"strategy": "operator", "preset_id": "ru-mts-public-v1", "apn1": "other.apn"},
|
|
{"strategy": "preserve", "preset_id": "ru-mts-public-v1"},
|
|
{"strategy": "operator", "preset_id": "ru-mts-public-v1", "phone": "+10000000000"},
|
|
{"strategy": "operator", "preset_id": "ru-mts-public-v1", "password": "secret"},
|
|
],
|
|
)
|
|
def test_carrier_preset_rejects_ambiguous_or_unique_settings(connection):
|
|
with pytest.raises(ValidationError):
|
|
Policy.model_validate({"connectivity": connection})
|
|
|
|
|
|
def test_profiles_are_immutable_copies_and_private_fields_do_not_escape(store):
|
|
candidate = store.inspect("arnavi-b2")
|
|
assert "identity_key" not in candidate and "evidence_id" not in candidate
|
|
profile = store.save_profile("Road", "arnavi-b2", {"parameters": {"25": 5}})
|
|
device = store.add(candidate["id"], "Tracker", "rover-a", profile["id"])
|
|
changed = store.update(device["id"], 1, "Tracker", "rover-a", {"parameters": {"25": 8}})
|
|
assert changed["settings"]["parameters"]["25"] == 8
|
|
assert store.profiles()[0]["settings"]["parameters"]["25"] == 5
|
|
assert changed["profile_id"] is None
|
|
assert changed["policy_state"] == "saved"
|
|
assert "identity_key" not in changed
|
|
reopened = EquipmentStore(store.root.parent, store.adapters)
|
|
assert reopened.listing() == store.listing()
|
|
|
|
|
|
def test_reassignment_many_per_vehicle_identity_dedup_and_stale_revision(store):
|
|
first = store.add(store.inspect("arnavi-b2")["id"], "First", "rover-a")
|
|
duplicate = store.inspect("arnavi-b2")
|
|
with pytest.raises(EquipmentError, match="уже добавлен"):
|
|
store.add(duplicate["id"], "Duplicate", "rover-b")
|
|
store.adapters["arnavi-b2"].identity = "000000000000002"
|
|
second = store.add(store.inspect("arnavi-b2")["id"], "Second", "rover-a")
|
|
assert len(store.listing("rover-a")) == 2
|
|
moved = store.update(first["id"], 1, "Moved", "rover-b", first["settings"])
|
|
assert moved["id"] == first["id"]
|
|
assert store.listing("rover-a")[0]["id"] == second["id"]
|
|
with pytest.raises(EquipmentError, match="другом окне"):
|
|
store.update(first["id"], 1, "Stale", "rover-a", first["settings"])
|
|
with store.db() as db:
|
|
old = json.loads(db.execute("SELECT body FROM history").fetchone()[0])
|
|
assert old["vehicle_id"] == "rover-a"
|
|
|
|
|
|
def test_expired_candidate_and_concurrent_usb_reader_rejected(store):
|
|
candidate = store.inspect("arnavi-b2")
|
|
with store.db() as db:
|
|
row = store._find(db, "candidates", candidate["id"])
|
|
row["expires_at"] = time.time() - 1
|
|
db.execute("UPDATE candidates SET body=? WHERE id=?", (json.dumps(row), candidate["id"]))
|
|
with pytest.raises(EquipmentError, match="устарела"):
|
|
store.add(candidate["id"], "Tracker", "rover-a")
|
|
with store.read_lock, pytest.raises(EquipmentError, match="уже выполняется"):
|
|
store.inspect("arnavi-b2")
|
|
|
|
|
|
def test_api_local_origin_policy_and_real_vehicle_check(store):
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
known = {"rover-a"}
|
|
|
|
def find(identifier):
|
|
if identifier not in known:
|
|
raise EquipmentError("Аппарат не найден.")
|
|
|
|
app.state.fleet = SimpleNamespace(
|
|
lock=threading.RLock(),
|
|
independent_equipment=store,
|
|
find=find,
|
|
events=SimpleNamespace(notify=lambda: None),
|
|
)
|
|
with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 12345)) as client:
|
|
base = "/api/v1/fleet/equipment"
|
|
assert client.get(base + "/catalog").status_code == 200
|
|
assert (
|
|
client.post(
|
|
base + "/inspect",
|
|
json={"model_id": "arnavi-b2"},
|
|
headers={"Origin": "https://bad.example"},
|
|
).status_code
|
|
== 403
|
|
)
|
|
assert client.get(base + "/catalog", headers={"Host": "bad.example"}).status_code == 403
|
|
invalid = client.post(
|
|
base + "/profiles",
|
|
json={"name": "Bad", "model_id": "arnavi-b2", "settings": {"imei": "secret"}},
|
|
)
|
|
assert invalid.status_code == 422 and "secret" not in invalid.text
|
|
candidate = client.post(base + "/inspect", json={"model_id": "arnavi-b2"}).json()
|
|
response = client.post(
|
|
base + "/instances",
|
|
json={"candidate_id": candidate["id"], "name": "Unit", "vehicle_id": "invented"},
|
|
)
|
|
assert response.status_code == 409
|
|
response = client.post(
|
|
base + "/instances",
|
|
json={"candidate_id": candidate["id"], "name": "Unit", "vehicle_id": "rover-a"},
|
|
)
|
|
assert response.status_code == 200
|
|
assert response.headers["cache-control"] == "no-store"
|
|
assert "identity_key" not in response.json()
|
|
|
|
|
|
def test_usb_reread_preserves_policy_and_rejects_wrong_tracker(store):
|
|
item = store.add(store.inspect("arnavi-b2")["id"], "Tracker", "rover-a")
|
|
same = store.refresh_observation(item["id"], 1)
|
|
assert same["revision"] == 2 and same["settings"] == item["settings"]
|
|
store.adapters["arnavi-b2"].identity = "000000000000003"
|
|
with pytest.raises(EquipmentError, match="другой трекер"):
|
|
store.refresh_observation(item["id"], 2)
|
|
assert store.listing()[0] == same
|
|
|
|
|
|
def test_single_sim_apn_edit_preserves_other_slot_and_credentials():
|
|
from k1link.device_plugins.arnavi_b2.profiles import prepare
|
|
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
|
|
|
|
source = Configuration(
|
|
tuple(
|
|
Setting(n, v)
|
|
for n, v in [
|
|
(67, b"first.apn"),
|
|
(68, b"first-user"),
|
|
(69, b"first-secret"),
|
|
(89, b"second.apn"),
|
|
(90, b"second-user"),
|
|
(91, b"second-secret"),
|
|
]
|
|
)
|
|
)
|
|
for slot, field in [(1, 67), (2, 89)]:
|
|
policy = {"connectivity": {"strategy": "sim", "sim_slot": slot, "apn": "new.apn"}}
|
|
target = prepare(source, policy)
|
|
assert target.text(field) == "new.apn"
|
|
assert all(r.value == source.value(r.number) for r in target.records if r.number != field)
|
|
with pytest.raises(ValueError):
|
|
prepare(source, {"connectivity": {"strategy": "sim", "sim_slot": 2}})
|
|
|
|
|
|
@pytest.mark.parametrize("slot", [1, 2])
|
|
def test_sim_selection_preserves_apns_credentials_and_unrelated_flags(slot):
|
|
from k1link.device_plugins.arnavi_b2.profiles import prepare
|
|
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration, Setting
|
|
|
|
source = Configuration(
|
|
tuple(
|
|
Setting(n, v)
|
|
for n, v in [
|
|
(72, (0x81000818).to_bytes(4, "big")),
|
|
(67, b"internet"),
|
|
(89, b"internet.mts.ru"),
|
|
(90, b"private-user"),
|
|
(91, b"private-secret"),
|
|
]
|
|
)
|
|
)
|
|
target = prepare(
|
|
source, {"connectivity": {"strategy": "sim", "sim_slot": slot, "activate": True}}
|
|
)
|
|
expected = (0x81000818 & ~((1 << 10) | (1 << 20))) | (1 << (20 if slot == 1 else 10))
|
|
assert target.integer(72, 4) == expected
|
|
assert all(target.value(n) == source.value(n) for n in (67, 89, 90, 91))
|
|
edited = prepare(
|
|
source,
|
|
{
|
|
"connectivity": {
|
|
"strategy": "sim",
|
|
"sim_slot": slot,
|
|
"activate": True,
|
|
"apn": "custom.apn",
|
|
}
|
|
},
|
|
)
|
|
assert edited.text(67 if slot == 1 else 89) == "custom.apn"
|
|
assert edited.integer(72, 4) == expected
|