Make Edge cloud registration switching reliable

This commit is contained in:
Andrei Smaliak 2026-09-19 11:45:41 +02:00
parent 443f35f86f
commit f074188b21
4 changed files with 556 additions and 43 deletions

View File

@ -303,6 +303,7 @@ Setters:
--set-tls 0|1
--set-user USER
--set-pass PASS
--set-pass-stdin
--set-clientid ID
--set-base-topic TOPIC
--legacy-itscreen 0|1
@ -509,7 +510,7 @@ main(){
load_env
local WANT_PRINT=0 WANT_DISABLE=0 WANT_ENABLE=0 ALLOW_ANON=0 DO_CHECK=0 DO_CHECKPASS=0
local SET_HOST=0 SET_PORT=0 SET_TLS=0 SET_USER=0 SET_PASS=0 SET_CID=0 SET_LEG=0 SET_BASE=0
local SET_HOST=0 SET_PORT=0 SET_TLS=0 SET_USER=0 SET_PASS=0 SET_PASS_STDIN=0 SET_CID=0 SET_LEG=0 SET_BASE=0
local V_HOST="" V_PORT="" V_TLS="" V_USER="" V_PASS="" V_CID="" V_LEG="" V_BASE=""
while [[ $# -gt 0 ]]; do
@ -525,6 +526,7 @@ main(){
--set-tls) SET_TLS=1; V_TLS="${2-}"; shift 2;;
--set-user) SET_USER=1; V_USER="${2-}"; shift 2;;
--set-pass) SET_PASS=1; V_PASS="${2-}"; shift 2;;
--set-pass-stdin) SET_PASS=1; SET_PASS_STDIN=1; shift;;
--set-clientid)
SET_CID=1
if [[ $# -ge 2 && "${2-}" != --* ]]; then
@ -542,6 +544,11 @@ main(){
esac
done
if [[ "$SET_PASS_STDIN" == "1" ]]; then
IFS= read -r -s V_PASS || true
[[ -n "$V_PASS" ]] || die "Empty password received on stdin"
fi
[[ "$SET_HOST" == "1" ]] && set_kv REMOTE_HOST "$V_HOST"
[[ "$SET_PORT" == "1" ]] && set_kv REMOTE_PORT "$V_PORT"
[[ "$SET_TLS" == "1" ]] && set_kv REMOTE_TLS "$V_TLS"

View File

@ -2,6 +2,7 @@
import json
import ipaddress
import base64
import configparser
import os
import queue
import re
@ -38,6 +39,7 @@ SETTINGS_CATEGORY = "server"
ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf"
REGISTRATION_STORE_PATH = "/var/lib/itscreen/data/it-screen/it-screen/registration.ini"
REVERSE_TUNNEL_CONFIG_PATH = "/etc/iomatex/reverse-tunnel.env"
MQTT_BRIDGE_APPLY_PATH = "/usr/local/sbin/iomatex-mqtt-apply"
MQTT_TOPIC_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._-]+$")
DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices")
_REGISTRATION_LOCK = threading.Lock()
@ -140,10 +142,28 @@ def _build_server_contract_topics(device_id, mqtt_config):
def get_candidate_settings_topics(device_id, preferred_contract=None, server_host_hint=None):
# Compatibility is configured explicitly through MQTT_ENVIRONMENT. Never
# probe alternate topic trees: a timeout there can hide the real response
# from the authoritative server contract.
return [_build_contract_topics(device_id)]
# Old Edge releases derived the control root from the server generation
# (it-screen or iomatex), while newer images receive an explicit prefix.
# Keep the configured contract first, then try only the two known legacy
# roots. Logical responses (401, validation errors, etc.) never fall
# through to another root; only a transport timeout does.
configured = _build_contract_topics(device_id)
roots = [configured["contract_prefix"]]
hint = " ".join((str(preferred_contract or ""), str(server_host_hint or ""))).lower()
roots.extend(("iomatex", "it-screen") if "iomatex" in hint else ("it-screen", "iomatex"))
contracts = []
seen = set()
for root in roots:
root = str(root or "").strip().strip("/").split("/", 1)[0]
if not root or root in seen:
continue
if not MQTT_TOPIC_SEGMENT_RE.fullmatch(root):
raise RuntimeError("MQTT_ENVIRONMENT has an invalid head namespace")
seen.add(root)
contracts.append(_build_server_contract_topics(
device_id, {"prefix": root, "contract_version": 1}
))
return contracts
def validate_host(host):
@ -384,15 +404,48 @@ def _load_registration_from_itscreen_config(device_id, persisted=None):
def _active_contract_meta(device_id, persisted=None):
persisted = persisted or {}
raw = _read_simple_key_value_file(ITSCREEN_CONFIG_PATH)
registration = _read_simple_key_value_file(REGISTRATION_STORE_PATH)
configured_prefix = _truncate_empty(raw.get("mqttPrefix"))
mqtt_config = {
"prefix": _truncate_empty(raw.get("mqttPrefix")) or _truncate_empty(persisted.get("mqtt_prefix")),
# A present client config is authoritative even when its prefix is
# empty: old QML then derives a legacy root from `server`. Falling
# back to cached console state here would address the wrong topic.
"prefix": configured_prefix if raw else _truncate_empty(persisted.get("mqtt_prefix")),
"contract_version": raw.get("mqttContractVersion") or persisted.get("contract_version") or 1,
}
if mqtt_config["prefix"]:
return _build_server_contract_topics(device_id, mqtt_config)
legacy_prefix = _legacy_client_mqtt_prefix(
_truncate_empty(registration.get("server"))
or _truncate_empty(raw.get("server"))
or _truncate_empty(persisted.get("host"))
)
if legacy_prefix:
return _build_server_contract_topics(
device_id, {"prefix": legacy_prefix, "contract_version": 1}
)
return _build_contract_topics(device_id)
def _legacy_client_mqtt_prefix(server):
"""Reproduce the pre-contract QML prefix used by older Edge clients."""
value = _truncate_empty(server)
if not value:
return ""
try:
parsed = urlparse(value if "://" in value else f"//{value}")
hostname = str(parsed.hostname or "").strip().rstrip(".")
except ValueError:
return ""
parts = hostname.split(".")
if len(parts) < 3:
return ""
prefix = f"{parts[2]}/{parts[1]}"
if all(MQTT_TOPIC_SEGMENT_RE.fullmatch(part) for part in prefix.split("/")):
return prefix
return ""
def _candidate_login_passwords(device_id, persisted=None):
return [LOGIN_PASSWORD]
@ -430,7 +483,7 @@ def _enroll_reverse_tunnel(state):
if not password:
raise RuntimeError("Device registration password is unavailable")
base_url = host if "://" in host else f"http://{host}"
base_url = _registration_base_url(host)
endpoint = base_url.rstrip("/") + "/v2/device/reverse-tunnel"
body = urlencode({"public_key": _reverse_tunnel_public_key(state.get("device_id", ""))}).encode("utf-8")
authorization = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
@ -480,6 +533,173 @@ def _enroll_reverse_tunnel(state):
return tunnel
def _registration_base_url(host):
value = validate_host(host)
if "://" in value:
return value.rstrip("/")
parsed = urlparse(f"//{value}")
hostname = str(parsed.hostname or "").lower()
scheme = "http"
if hostname != "localhost":
try:
ipaddress.ip_address(hostname)
except ValueError:
scheme = "https"
return f"{scheme}://{value}".rstrip("/")
def _cloud_json_request(url, data=None, authorization=""):
headers = {"Accept": "application/json"}
if data is not None:
headers["Content-Type"] = "application/x-www-form-urlencoded"
if authorization:
headers["Authorization"] = authorization
request = Request(url, data=data, method="POST" if data is not None else "GET", headers=headers)
try:
with urlopen(request, timeout=20) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as exc:
raise RuntimeError(f"Registration server rejected request (HTTP {exc.code})") from exc
except (URLError, OSError, ValueError, json.JSONDecodeError) as exc:
raise RuntimeError("Registration server request failed") from exc
if not isinstance(payload, dict):
raise RuntimeError("Registration server returned an invalid response")
return payload
def _write_client_registration(state, mqtt_config):
"""Commit cloud credentials and MQTT settings as one local operation."""
registration = configparser.RawConfigParser()
registration.optionxform = str
registration["meta"] = {"version": "1"}
registration["registration"] = {
"device_name": state["username"],
"is_logged": "true",
"is_registered": "true",
"password": state["password"],
"server": state["host"],
}
config = configparser.RawConfigParser(strict=False)
config.optionxform = str
config.read(ITSCREEN_CONFIG_PATH, encoding="utf-8")
section = "%General"
if not config.has_section(section):
config.add_section(section)
values = {
"mqttHost": mqtt_config["host_name"],
"mqttPort": str(mqtt_config["port"]),
"mqttUsername": mqtt_config["username"],
"mqttPassword": mqtt_config["password"],
"mqttTls": "1" if _bool_value(mqtt_config.get("ssl"), False) else "0",
"mqttPrefix": mqtt_config["prefix"],
"mqttContractVersion": str(mqtt_config.get("contract_version") or 1),
}
for key, value in values.items():
config.set(section, key, str(value))
for path, parser, mode in (
(REGISTRATION_STORE_PATH, registration, 0o600),
(ITSCREEN_CONFIG_PATH, config, 0o644),
):
directory = os.path.dirname(path)
try:
existing_stat = os.stat(path)
except OSError:
existing_stat = None
directory_stat = os.stat(directory)
fd, temporary = tempfile.mkstemp(prefix="registration-switch.", dir=directory, text=True)
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
parser.write(stream, space_around_delimiters=False)
os.chmod(temporary, existing_stat.st_mode & 0o777 if existing_stat else mode)
os.chown(temporary, directory_stat.st_uid, directory_stat.st_gid)
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def _direct_cloud_registration(host, token=""):
"""Compatibility path for clients that cannot confirm an existing Edge."""
base_url = _registration_base_url(host)
username = _device_identity()["device_id"]
form = {"username": username}
if _truncate_empty(token):
form["token"] = _truncate_empty(token)
created = _cloud_json_request(
base_url + "/v2/device",
urlencode(form).encode("utf-8"),
)
password = _truncate_empty(created.get("password"))
if not password:
raise RuntimeError(_truncate_empty(created.get("error")) or "Registration password was not returned")
authorization = "Basic " + base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
confirmed = _cloud_json_request(
base_url + "/v2/device/confirm",
b"",
authorization,
)
if not _bool_value(confirmed.get("result"), False):
raise RuntimeError("Registration confirmation failed")
device = _cloud_json_request(
base_url + "/v2/device?expand=mqtt,organization",
authorization=authorization,
)
mqtt_config = device.get("mqtt") if isinstance(device.get("mqtt"), dict) else {}
required = ("host_name", "port", "username", "password", "prefix")
if any(mqtt_config.get(key) in (None, "") for key in required):
raise RuntimeError("Registration server returned an incomplete MQTT configuration")
state = {
"host": validate_host(host),
"username": username,
"password": password,
"token": _truncate_empty(token),
"organization": _truncate_empty((device.get("organization") or {}).get("title")),
"device_name": username,
"device_id": username,
"registered": True,
"local_registered": True,
"logged": True,
}
_write_client_registration(state, mqtt_config)
if not _apply_persisted_mqtt_bridge(host):
raise RuntimeError("Failed to apply the destination MQTT configuration")
subprocess.run(["systemctl", "restart", "itscreen-x11.service"], check=True, timeout=30)
contract_meta = _build_server_contract_topics(username, mqtt_config)
state.update(contract_meta)
return contract_meta, state
def _client_registration_snapshot(device_id):
state = _load_registration_from_itscreen_config(device_id)
raw = _read_simple_key_value_file(ITSCREEN_CONFIG_PATH)
mqtt_config = {
"host_name": _truncate_empty(raw.get("mqttHost")),
"port": raw.get("mqttPort"),
"username": _truncate_empty(raw.get("mqttUsername")),
"password": _truncate_empty(raw.get("mqttPassword")),
"ssl": _bool_value(raw.get("mqttTls"), False),
"prefix": _truncate_empty(raw.get("mqttPrefix")),
"contract_version": raw.get("mqttContractVersion") or 1,
}
required_state = state and state.get("host") and state.get("username") and state.get("password")
required_mqtt = all(mqtt_config.get(key) not in (None, "") for key in (
"host_name", "port", "username", "password", "prefix"
))
return (state, mqtt_config) if required_state and required_mqtt else (None, None)
def _restore_client_registration(snapshot):
state, mqtt_config = snapshot
if not state or not mqtt_config:
return False
_write_client_registration(state, mqtt_config)
if not _apply_persisted_mqtt_bridge(state["host"]):
return False
subprocess.run(["systemctl", "restart", "itscreen-x11.service"], check=True, timeout=30)
return True
def configure_reverse_tunnel():
"""Retry enrollment once from the client's current registration, without registering again."""
if not _REGISTRATION_LOCK.acquire(blocking=False):
@ -521,7 +741,20 @@ def _recover_dispatched_registration(device_id, persisted, target_host, timeout=
"""
deadline = time.time() + timeout
last_error = None
bridge_target_applied = False
while time.time() < deadline:
# Registration makes the display client download and persist the new
# MQTT endpoint before it reconnects. The console talks to that client
# through the local Mosquitto bridge, so the bridge must follow the
# client to the new broker as part of the same operation. Do not rely
# only on the display client's asynchronous bridge helper: an older or
# busy client can otherwise leave the console on the previous server
# forever and recovery ends with "Login response timeout".
if not bridge_target_applied:
try:
bridge_target_applied = _apply_persisted_mqtt_bridge(target_host)
except Exception as exc:
last_error = exc
contract_meta = _active_contract_meta(device_id, persisted)
try:
with MqttSettingsSession(device_id, contract_meta) as session:
@ -541,6 +774,69 @@ def _recover_dispatched_registration(device_id, persisted, target_host, timeout=
raise RuntimeError("Registration result is unavailable after MQTT reconnect") from last_error
def _apply_persisted_mqtt_bridge(target_host):
"""Move the local bridge to MQTT settings persisted by the display client.
Return False while the client has not persisted the target registration
yet. Once the target host and a complete MQTT configuration are visible,
apply them synchronously so subsequent recovery messages use the same
broker as the display client.
"""
raw = _read_simple_key_value_file(ITSCREEN_CONFIG_PATH)
registration = _read_simple_key_value_file(REGISTRATION_STORE_PATH)
persisted_host = _truncate_empty(registration.get("server")) or _truncate_empty(raw.get("server"))
if not persisted_host or not _same_registration_host(persisted_host, target_host):
return False
mqtt_host = _truncate_empty(raw.get("mqttHost"))
mqtt_username = _truncate_empty(raw.get("mqttUsername"))
mqtt_password = _truncate_empty(raw.get("mqttPassword"))
mqtt_prefix = _truncate_empty(raw.get("mqttPrefix"))
mqtt_client_id = (
_truncate_empty(registration.get("device_name"))
or _truncate_empty(raw.get("deviceName"))
or _device_identity()["device_id"]
)
try:
mqtt_port = int(raw.get("mqttPort") or 0)
mqtt_tls = 1 if int(raw.get("mqttTls") or 0) else 0
except (TypeError, ValueError) as exc:
raise RuntimeError("The new MQTT configuration contains an invalid port or TLS mode") from exc
if not mqtt_host or not mqtt_username or not mqtt_password or not 1 <= mqtt_port <= 65535:
return False
if not os.path.isfile(MQTT_BRIDGE_APPLY_PATH):
raise RuntimeError("MQTT bridge apply tool is unavailable")
command = [
"sudo", MQTT_BRIDGE_APPLY_PATH,
"--set-host", mqtt_host,
"--set-port", str(mqtt_port),
"--set-tls", str(mqtt_tls),
"--set-user", mqtt_username,
"--set-pass-stdin",
"--set-clientid", mqtt_client_id,
"--set-base-topic", mqtt_prefix or "iomatex",
"--legacy-itscreen", "1",
"--enable", "--check",
]
try:
subprocess.run(
command,
input=mqtt_password,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
timeout=35,
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError("Timed out while switching the local MQTT bridge") from exc
except subprocess.CalledProcessError as exc:
detail = _truncate_empty(exc.stderr)
raise RuntimeError(detail or "Failed to switch the local MQTT bridge") from exc
return True
def _extract_response_payload(response_text):
raw = str(response_text or "").strip()
if not raw:
@ -1098,10 +1394,30 @@ def _read_device_registration_snapshot(session, device_id, server_host_hint=""):
return last_payload
def _with_settings_contract(device_id, persisted, operation_name, callback, server_host_hint=""):
contract_meta = _active_contract_meta(device_id, persisted)
def _with_settings_contract(
device_id,
persisted,
operation_name,
callback,
server_host_hint="",
stop_fallback=None,
):
active = _active_contract_meta(device_id, persisted)
candidates = [active]
candidates.extend(get_candidate_settings_topics(
device_id,
preferred_contract=active.get("contract_prefix"),
server_host_hint=server_host_hint,
))
seen = set()
last_error = None
for contract_meta in candidates:
fingerprint = (contract_meta.get("request_topic"), contract_meta.get("response_topic"))
if fingerprint in seen:
continue
seen.add(fingerprint)
_debug(
f"{operation_name}: using configured contract={contract_meta['contract_prefix']} "
f"{operation_name}: trying contract={contract_meta['contract_prefix']} "
f"request={contract_meta['request_topic']} response={contract_meta['response_topic']}"
)
try:
@ -1109,11 +1425,20 @@ def _with_settings_contract(device_id, persisted, operation_name, callback, serv
result = callback(session, contract_meta)
return contract_meta, result
except Exception as exc:
last_error = exc
_debug(
f"{operation_name}: contract={contract_meta['contract_prefix']} failed: "
f"{_truncate_empty(str(exc)) or exc.__class__.__name__}"
)
# Registration is not idempotent. Confirmation can repoint and
# restart the Edge MQTT bridge, disconnecting this old session.
# Once dispatched, recover on the destination instead of sending
# the registration command again through another legacy contract.
if (callable(stop_fallback) and stop_fallback()) or not _registration_transport_interrupted(exc):
raise
if last_error is not None:
raise last_error
raise RuntimeError("Device settings service is unavailable")
def get_registration_status():
@ -1215,6 +1540,7 @@ def _register_device_once(host, token=""):
validated_host = validate_host(host)
validated_token = _normalize_registration_token(token)
persisted = load_state()
rollback_snapshot = _client_registration_snapshot(_device_identity()["device_id"])
working = dict(persisted)
working["host"] = validated_host
working["token"] = validated_token
@ -1272,10 +1598,23 @@ def _register_device_once(host, token=""):
"register",
_register_flow,
server_host_hint=validated_host,
stop_fallback=lambda: registration_dispatched,
)
except Exception as exc:
if not registration_dispatched or not _registration_transport_interrupted(exc):
if "Registration failed (401)" in str(exc):
contract_meta, recovered_state = _direct_cloud_registration(
validated_host, validated_token
)
flow = {
"event": {"action": "registered", "operation": "compatibility", "status": 200},
"event_payload": {"result": True},
"server_state": recovered_state,
"contract_meta": contract_meta,
"recovered_after_legacy_401": True,
}
elif not registration_dispatched or not _registration_transport_interrupted(exc):
raise
else:
contract_meta, recovered_state = _recover_dispatched_registration(
working["device_id"], persisted, validated_host
)
@ -1327,12 +1666,22 @@ def _register_device_once(host, token=""):
result["warning"] = enrollment_warning
return result
except TimeoutError as exc:
working["status"] = "error"
save_state(working)
try:
_restore_client_registration(rollback_snapshot)
except Exception as rollback_exc:
_debug(f"registration rollback failed: {rollback_exc}")
failed = dict(persisted)
failed["status"] = "error"
save_state(failed)
raise RuntimeError(str(exc)) from exc
except Exception as exc:
working["status"] = "error"
save_state(working)
try:
_restore_client_registration(rollback_snapshot)
except Exception as rollback_exc:
_debug(f"registration rollback failed: {rollback_exc}")
failed = dict(persisted)
failed["status"] = "error"
save_state(failed)
raise

View File

@ -12,7 +12,21 @@ from itscreen_registration import validate_host
class ServerAddressValidationTest(unittest.TestCase):
def test_settings_contract_uses_only_environment_head_namespace(self):
def test_registration_base_url_uses_https_for_dns_and_http_for_local_targets(self):
self.assertEqual(
"https://rest.tth.iomatex.com",
itscreen_registration._registration_base_url("rest.tth.iomatex.com"),
)
self.assertEqual(
"http://192.168.0.102:8081",
itscreen_registration._registration_base_url("192.168.0.102:8081"),
)
self.assertEqual(
"http://localhost:8000",
itscreen_registration._registration_base_url("localhost:8000"),
)
def test_settings_contract_keeps_configured_root_first_and_supports_iomatex_legacy(self):
with patch.object(itscreen_registration, "MQTT_ENVIRONMENT", "it-screen/its-docker"):
contracts = itscreen_registration.get_candidate_settings_topics(
"g-box-deadbeef",
@ -20,8 +34,9 @@ class ServerAddressValidationTest(unittest.TestCase):
server_host_hint="uae.iomatex.com",
)
self.assertEqual(1, len(contracts))
self.assertEqual(2, len(contracts))
self.assertEqual("it-screen", contracts[0]["contract_prefix"])
self.assertEqual("iomatex", contracts[1]["contract_prefix"])
self.assertEqual(
"it-screen/$devices/settings/g-box-deadbeef/sub",
contracts[0]["request_topic"],
@ -58,7 +73,7 @@ class ServerAddressValidationTest(unittest.TestCase):
self.assertIn('MQTT_ENVIRONMENT="${MQTT_ENVIRONMENT:-it-screen/its-docker}"', installer)
self.assertIn('Environment="MQTT_ENVIRONMENT=${MQTT_ENVIRONMENT}"', installer)
def test_contract_error_is_returned_without_fallback_probe(self):
def test_logical_contract_error_is_returned_without_fallback_probe(self):
opened_contracts = []
class Session:
@ -83,6 +98,67 @@ class ServerAddressValidationTest(unittest.TestCase):
self.assertEqual(["it-screen"], opened_contracts)
def test_transport_timeout_falls_back_to_legacy_iomatex_root(self):
opened_contracts = []
class Session:
def __init__(self, _device_id, contract_meta):
self.contract = contract_meta["contract_prefix"]
opened_contracts.append(self.contract)
def __enter__(self):
return self
def __exit__(self, _exc_type, _exc, _traceback):
return False
def respond(_session, contract_meta):
if contract_meta["contract_prefix"] == "it-screen":
raise RuntimeError("Login response timeout")
return {"registered": True}
with patch.object(itscreen_registration, "MQTT_ENVIRONMENT", "it-screen/its-docker"), \
patch.object(itscreen_registration, "MqttSettingsSession", Session):
contract, result = itscreen_registration._with_settings_contract(
"g-box-deadbeef", {}, "register", respond, server_host_hint="rest.tth.iomatex.com"
)
self.assertEqual(["it-screen", "iomatex"], opened_contracts)
self.assertEqual("iomatex", contract["contract_prefix"])
self.assertTrue(result["registered"])
def test_transport_timeout_does_not_fallback_after_non_idempotent_dispatch(self):
opened_contracts = []
dispatched = {"value": False}
class Session:
def __init__(self, _device_id, contract_meta):
opened_contracts.append(contract_meta["contract_prefix"])
def __enter__(self):
return self
def __exit__(self, _exc_type, _exc, _traceback):
return False
def disconnect_after_dispatch(_session, _contract_meta):
dispatched["value"] = True
raise RuntimeError("Device settings service is unavailable")
with patch.object(itscreen_registration, "MQTT_ENVIRONMENT", "it-screen/its-docker"), \
patch.object(itscreen_registration, "MqttSettingsSession", Session):
with self.assertRaisesRegex(RuntimeError, "service is unavailable"):
itscreen_registration._with_settings_contract(
"g-box-deadbeef",
{},
"register",
disconnect_after_dispatch,
server_host_hint="rest.tth.iomatex.com",
stop_fallback=lambda: dispatched["value"],
)
self.assertEqual(["it-screen"], opened_contracts)
def test_console_state_does_not_persist_registration_secrets(self):
state = itscreen_registration._default_state()
state.update({"password": "mqtt-secret", "token": "registration-secret"})
@ -232,7 +308,8 @@ class ServerAddressValidationTest(unittest.TestCase):
"g-box-deadbeef", {"prefix": "it-screen/its-docker", "contract_version": 2}
)
def shared_flow(_device_id, _persisted, _operation, callback, server_host_hint=""):
def shared_flow(_device_id, _persisted, _operation, callback, server_host_hint="", stop_fallback=None):
self.assertTrue(callable(stop_fallback))
return contract, callback(Session(), contract)
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
@ -410,7 +487,15 @@ class ServerAddressValidationTest(unittest.TestCase):
def wait_registered_event(self, expected_operation=None):
raise RuntimeError("Device settings service is unavailable")
def interrupted_flow(_device_id, _persisted, _operation, callback, server_host_hint=""):
def interrupted_flow(
_device_id,
_persisted,
_operation,
callback,
server_host_hint="",
stop_fallback=None,
):
self.assertTrue(callable(stop_fallback))
return contract, callback(Session(), contract)
recovered_state = {
@ -431,6 +516,66 @@ class ServerAddressValidationTest(unittest.TestCase):
self.assertEqual("registered", response["status"])
self.assertTrue(response["data"]["registered"])
def test_recovery_moves_local_bridge_to_persisted_target_before_mqtt_retry(self):
address = "rest.tth.iomatex.com"
target_state = {
"server": address,
"mqttHost": "tth.iomatex.com",
"mqttPort": "11883",
"mqttUsername": "broadcaster",
"mqttPassword": "broker-secret",
"mqttTls": "0",
"deviceName": "g-box-deadbeef",
}
session_state = {
"host": address,
"registered": True,
"logged": True,
}
class Session:
def __enter__(self):
return self
def __exit__(self, *_args):
return None
def login(self, _passwords):
return True
def get_server_state(self):
return session_state
with patch.object(itscreen_registration, "_read_simple_key_value_file", side_effect=(target_state, target_state)), \
patch.object(itscreen_registration.os.path, "isfile", return_value=True), \
patch.object(itscreen_registration.subprocess, "run") as run, \
patch.object(itscreen_registration, "_active_contract_meta", return_value={"response_topic": "response"}), \
patch.object(itscreen_registration, "MqttSettingsSession", return_value=Session()):
contract, recovered = itscreen_registration._recover_dispatched_registration(
"g-box-deadbeef", {}, address, timeout=0.5
)
self.assertEqual(session_state, recovered)
self.assertEqual("response", contract["response_topic"])
command = run.call_args.args[0]
self.assertIn("tth.iomatex.com", command)
self.assertIn("11883", command)
self.assertIn("--set-pass-stdin", command)
self.assertNotIn("broker-secret", command)
self.assertEqual("broker-secret", run.call_args.kwargs["input"])
self.assertTrue(run.call_args.kwargs["check"])
def test_bridge_switch_waits_until_target_configuration_is_persisted(self):
with patch.object(
itscreen_registration,
"_read_simple_key_value_file",
side_effect=({"server": "rest.dev.it-screen.com"}, {"server": "rest.dev.it-screen.com"}),
), patch.object(itscreen_registration.subprocess, "run") as run:
applied = itscreen_registration._apply_persisted_mqtt_bridge("rest.tth.iomatex.com")
self.assertFalse(applied)
run.assert_not_called()
def test_current_server_is_reported_as_already_active_without_register_publish(self):
address = "rest.dev.it-screen.com"
persisted = itscreen_registration._default_state()
@ -449,7 +594,8 @@ class ServerAddressValidationTest(unittest.TestCase):
def register_device(self, _host, _token):
raise AssertionError("already-active server must not receive register")
def existing_flow(_device_id, _persisted, _operation, callback, server_host_hint=""):
def existing_flow(_device_id, _persisted, _operation, callback, server_host_hint="", stop_fallback=None):
self.assertTrue(callable(stop_fallback))
return contract, callback(Session(), contract)
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
@ -471,6 +617,17 @@ class ServerAddressValidationTest(unittest.TestCase):
self.assertEqual("iomatex/eva", contract["contract_prefix"])
self.assertEqual("iomatex/eva/$devices/settings/g-box-deadbeef/sub", contract["request_topic"])
def test_active_contract_reproduces_legacy_prefix_for_ip_registration(self):
with patch.object(
itscreen_registration,
"_read_simple_key_value_file",
side_effect=({"mqttPrefix": "", "mqttContractVersion": "1"}, {"server": "192.168.0.102:8081"}),
):
contract = itscreen_registration._active_contract_meta("g-box-deadbeef")
self.assertEqual("0", contract["contract_prefix"])
self.assertEqual("0/$devices/settings/g-box-deadbeef/sub", contract["request_topic"])
def test_cached_unregistered_status_is_reverified_through_mqtt(self):
persisted = itscreen_registration._default_state()
persisted.update({"status": "not_registered", "app_version": "4.410.109"})

View File

@ -126,7 +126,7 @@ class ReverseTunnelConfigurationTest(unittest.TestCase):
self.assertTrue(result["ok"])
request.assert_called_once()
self.assertEqual(8, request.call_args.kwargs["timeout"])
self.assertEqual("http://rest.example.com/v2/device/reverse-tunnel", request.call_args.args[0].full_url)
self.assertEqual("https://rest.example.com/v2/device/reverse-tunnel", request.call_args.args[0].full_url)
self.assertIn("TUNNEL_HOST=gateway.example.com\nTUNNEL_PORT=2222\n", config_path.read_text())
command.assert_called_once_with([
"systemctl", "restart", "iomatex-rt-cockpit.service",