Report remote access readiness in Console

This commit is contained in:
Andrei Smaliak 2026-10-03 12:39:53 +02:00
parent 54713d8266
commit bca9b4a689
8 changed files with 180 additions and 11 deletions

View File

@ -9,3 +9,6 @@
Install through Health → Edge Console → Update 3.1.2. This updates stage_ui;
it does not change the IT-Screen App binary or stage_itscreen revision. No
installation on the user's live device is performed as part of publication.
- Remote access diagnostics now distinguish the local autossh connection from the registration server receiver and public Web Gateway. A connected SSH tunnel is shown as degraded when browser access is unavailable or unverified; the Console never reports receiver-only health as end-to-end readiness.
- Switching registration environments clears the old tunnel target and stops its units before enrolling with the new server. If enrollment fails, enabled units cannot reconnect to the previous environment after reboot. Re-registering on the same server keeps the current tunnels until replacement succeeds.

View File

@ -4,3 +4,4 @@
- UAE gateway companion fix probes services concurrently within 2.5 seconds. An absent Zigbee service no longer makes healthy Cockpit and Console disappear behind the API's 3-second timeout.
- Gateway SSH configuration now expires unresponsive tunnel-user sessions using ClientAliveInterval=30 / ClientAliveCountMax=3, releasing stale forwarding ports after network loss. Existing sessions must reconnect to acquire this policy.
- Verified on BeMd_Showroom / g-box-c453df5f; Zigbee is not installed and remains unavailable.
- Console obtains receiver, gateway, device-registration and per-port status from the authenticated environment API, caches the check briefly and never returns stored credentials to the browser. This complements, but does not replace, the local systemd/autossh check.

View File

@ -24,7 +24,7 @@ from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from itscreen_registration import configure_reverse_tunnel, get_registration_status, register_device, reset_registration
from itscreen_registration import get_reverse_tunnel_diagnostics, configure_reverse_tunnel, get_registration_status, register_device, reset_registration
from modbus_backend import (
ApiError as ModbusApiError,
acquire_session as modbus_acquire_session,
@ -2303,6 +2303,7 @@ def build_provider_context():
"get_ap_status_card": ap_status_card,
"get_identity_payload": get_identity_payload,
"get_audio_diagnostics": get_audio_diagnostics,
"get_reverse_tunnel_diagnostics": get_reverse_tunnel_diagnostics,
}

View File

@ -473,6 +473,43 @@ def _reverse_tunnel_public_key(device_id):
raise RuntimeError("Reverse tunnel SSH public key was not found")
_reverse_diagnostics_cache = {}
_reverse_diagnostics_lock = threading.Lock()
def get_reverse_tunnel_diagnostics():
"""Check the registration server, independently of local autossh state."""
state = load_state()
stored = _read_simple_key_value_file(REGISTRATION_STORE_PATH)
host = _truncate_empty(state.get("host")) or _truncate_empty(stored.get("host"))
username = _truncate_empty(state.get("username")) or state.get("device_id", "")
password = _truncate_empty(state.get("password")) or _truncate_empty(stored.get("password"))
# Credentials are never returned to the browser or included in exceptions.
key = (host, username, password)
with _reverse_diagnostics_lock:
cached = _reverse_diagnostics_cache.get("value")
if cached and _reverse_diagnostics_cache.get("key") == key and time.monotonic() < _reverse_diagnostics_cache.get("expires", 0):
return dict(cached)
result = {"verified": False, "error": "Remote access diagnostics unavailable: device registration is required."}
if host and username and password:
try:
endpoint = _registration_base_url(validate_host(host)).rstrip("/") + "/v2/device/reverse-tunnel-status"
authorization = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
request = Request(endpoint, headers={"Authorization": f"Basic {authorization}", "Accept": "application/json"})
with urlopen(request, timeout=5) as response:
payload = json.loads(response.read(65536).decode("utf-8"))
data = payload.get("diagnostics") if isinstance(payload, dict) else None
if not isinstance(data, dict) or not isinstance(data.get("gateway"), dict) or not isinstance(data.get("receiver"), dict):
raise ValueError("invalid diagnostics")
result = dict(data, verified=True)
except HTTPError as exc:
result = {"verified": False, "error": f"Remote access diagnostics unavailable (HTTP {exc.code}). Check registration or update the platform."}
except (URLError, OSError, ValueError, TypeError):
result = {"verified": False, "error": "Remote access diagnostics unavailable: registration server did not return a valid response."}
_reverse_diagnostics_cache.update(key=key, value=result, expires=time.monotonic() + 60)
return dict(result)
def _enroll_reverse_tunnel(state):
host = validate_host(state.get("host", ""))
username = _truncate_empty(state.get("username")) or _device_identity()["device_id"]
@ -510,6 +547,18 @@ def _enroll_reverse_tunnel(state):
if not ssh_host or not 1 <= ssh_port <= 65535:
raise RuntimeError("Environment returned an invalid SSH gateway")
_write_reverse_tunnel_config(ssh_host, ssh_port, ssh_user)
subprocess.run([
"systemctl", "restart",
"iomatex-rt-cockpit.service",
"iomatex-rt-z2m.service",
"iomatex-rt-webui.service",
], check=True, timeout=20)
return tunnel
def _write_reverse_tunnel_config(ssh_host, ssh_port=22, ssh_user="iomatex-tunnel"):
directory = os.path.dirname(REVERSE_TUNNEL_CONFIG_PATH)
os.makedirs(directory, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix="reverse-tunnel.", suffix=".env", dir=directory, text=True)
@ -524,13 +573,19 @@ def _enroll_reverse_tunnel(state):
if os.path.exists(temporary):
os.unlink(temporary)
def _sync_registration_tunnels(state, previous):
"""Do not leave tunnels connected to the previous registration environment."""
if not _same_registration_host(previous.get("host", ""), state.get("host", "")):
# Empty host also prevents enabled units reconnecting after a reboot.
_write_reverse_tunnel_config("")
subprocess.run([
"systemctl", "restart",
"iomatex-rt-cockpit.service",
"iomatex-rt-z2m.service",
"iomatex-rt-webui.service",
"systemctl", "stop", "iomatex-rt-cockpit.service",
"iomatex-rt-z2m.service", "iomatex-rt-webui.service",
], check=True, timeout=20)
return tunnel
with _reverse_diagnostics_lock:
_reverse_diagnostics_cache.clear()
return _enroll_reverse_tunnel(state)
def _registration_base_url(host):
@ -1645,7 +1700,7 @@ def _register_device_once(host, token=""):
reverse_tunnel = None
if merged.get("registered"):
try:
reverse_tunnel = _enroll_reverse_tunnel(merged)
reverse_tunnel = _sync_registration_tunnels(merged, persisted)
except Exception as exc:
enrollment_warning = _truncate_empty(str(exc)) or "Reverse tunnel enrollment failed"
_debug(f"reverse-tunnel enrollment warning: {enrollment_warning}")

View File

@ -0,0 +1,42 @@
import json
import unittest
from unittest.mock import patch, MagicMock
import itscreen_registration as registration
from test_core_services import provider
class ReverseDiagnosticsTest(unittest.TestCase):
def setUp(self):
registration._reverse_diagnostics_cache.clear()
def test_remote_failure_is_retained_and_requests_are_cached(self):
payload = {'diagnostics': {'receiver': {'active': True}, 'gateway': {'active': False, 'error': 'Gateway missing'}, 'registered': False}}
response = MagicMock()
response.__enter__.return_value.read.return_value = json.dumps(payload).encode()
with patch.object(registration, 'load_state', return_value={'host': 'rest.example.com', 'username': 'edge', 'password': 'secret'}), patch.object(registration, '_read_simple_key_value_file', return_value={}), patch.object(registration, 'urlopen', return_value=response) as request:
result = registration.get_reverse_tunnel_diagnostics()
self.assertTrue(result['verified'])
self.assertFalse(result['gateway']['active'])
self.assertEqual(result, registration.get_reverse_tunnel_diagnostics())
self.assertEqual(1, request.call_count)
self.assertNotIn('secret', json.dumps(result))
def test_old_platform_does_not_look_healthy(self):
with patch.object(registration, 'load_state', return_value={'host': 'rest.example.com', 'username': 'edge', 'password': 'secret'}), patch.object(registration, '_read_simple_key_value_file', return_value={}), patch.object(registration, 'urlopen', side_effect=registration.HTTPError('url', 404, 'missing', {}, None)):
result = registration.get_reverse_tunnel_diagnostics()
self.assertFalse(result['verified'])
self.assertIn('HTTP 404', result['error'])
def test_connected_ssh_with_missing_gateway_is_degraded(self):
unit = dict(installed=True, active=True, active_state='active', sub_state='running', unit_file_state='enabled')
ctx = {'file_exists': lambda p: True, 'systemd_unit': lambda p: unit, 'read_env_file': lambda p: {},
'read_text': lambda p: '', 'run': lambda *a, **k: (1, '', ''),
'get_reverse_tunnel_diagnostics': lambda: {'verified': True, 'registered': True, 'receiver': {'active': True}, 'gateway': {'active': False, 'error': 'Gateway missing'}}}
with patch.object(provider, '_reverse_tunnel_connected', return_value=True):
card = provider.reverse_tunnel_card(ctx)
self.assertTrue(card['active'])
self.assertEqual('degraded', card['state'])
self.assertIn('Gateway missing', card['warnings'])
self.assertEqual(3, sum(t['active'] for t in card['tunnels']))
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,47 @@
import pathlib
import tempfile
import unittest
from unittest.mock import patch
import itscreen_registration as registration
class RegistrationTunnelSwitchTest(unittest.TestCase):
def test_new_server_disables_old_target_before_enrollment(self):
with tempfile.TemporaryDirectory() as directory:
path = pathlib.Path(directory) / 'reverse.env'
path.write_text('TUNNEL_HOST=old-gateway\n')
events = []
def stop(*args, **kwargs):
self.assertIn('TUNNEL_HOST=\n', path.read_text())
events.append('stop')
def enroll(state):
self.assertEqual('rest.new.example', state['host'])
self.assertEqual(['stop'], events)
registration._write_reverse_tunnel_config('new-gateway', 2200)
return {'ssh_host': 'new-gateway'}
with patch.object(registration, 'REVERSE_TUNNEL_CONFIG_PATH', str(path)), patch.object(registration.subprocess, 'run', side_effect=stop), patch.object(registration, '_enroll_reverse_tunnel', side_effect=enroll):
result = registration._sync_registration_tunnels({'host': 'rest.new.example'}, {'host': 'rest.old.example'})
self.assertEqual('new-gateway', result['ssh_host'])
self.assertIn('TUNNEL_HOST=new-gateway', path.read_text())
def test_failure_cannot_reconnect_to_previous_server_after_reboot(self):
with tempfile.TemporaryDirectory() as directory:
path = pathlib.Path(directory) / 'reverse.env'
path.write_text('TUNNEL_HOST=old-gateway\n')
with patch.object(registration, 'REVERSE_TUNNEL_CONFIG_PATH', str(path)), patch.object(registration.subprocess, 'run') as stop, patch.object(registration, '_enroll_reverse_tunnel', side_effect=RuntimeError('New server unavailable')):
with self.assertRaisesRegex(RuntimeError, 'New server unavailable'):
registration._sync_registration_tunnels({'host': 'rest.new.example'}, {'host': 'rest.old.example'})
self.assertIn('TUNNEL_HOST=\n', path.read_text())
self.assertNotIn('old-gateway', path.read_text())
self.assertEqual('stop', stop.call_args.args[0][1])
def test_same_server_does_not_stop_working_tunnels_before_retry(self):
with patch.object(registration, '_write_reverse_tunnel_config') as write, patch.object(registration.subprocess, 'run') as stop, patch.object(registration, '_enroll_reverse_tunnel', return_value={'ssh_host': 'gateway'}) as enroll:
state = {'host': 'rest.example.com'}
registration._sync_registration_tunnels(state, state)
write.assert_not_called()
stop.assert_not_called()
enroll.assert_called_once_with(state)
if __name__ == '__main__':
unittest.main()

View File

@ -1309,7 +1309,7 @@
}
function renderReverseTunnelCard(card) {
const tone = statusTone(card);
const tone = card.state === "degraded" ? "warn" : statusTone(card);
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
const errors = Array.isArray(card.errors) ? card.errors : [];
const tunnels = Array.isArray(card.tunnels) ? card.tunnels : [];
@ -1320,7 +1320,7 @@
{ label: t("Active"), value: String(activeTunnels.length) },
{ label: t("Failed"), value: String(failedTunnels.length) }
];
const overallRow = { label: t("Overall"), value: card.active ? t("OK") : t("Degraded") };
const overallRow = { label: t("Overall"), value: card.active && card.state !== "degraded" ? t("OK") : t("Degraded") };
const bootstrapCommand = textValue(card.bootstrap_command, "");
const bootstrapHost = textValue(card.bootstrap_host, "");
const bootstrapOpen = !!state.reverseTunnelUi.bootstrapOpen;

View File

@ -824,6 +824,25 @@ def reverse_tunnel_card(ctx):
if item["installed"] and not item["active"]
)
diagnose = ctx.get("get_reverse_tunnel_diagnostics")
remote = diagnose() if diagnose else {"verified": False}
remote_warnings = []
if not remote.get("verified"):
remote_warnings.append(remote.get("error") or "Remote access has not been verified by the registration server.")
else:
for component in ("receiver", "gateway"):
check = remote.get(component, {})
if check.get("active") is not True:
remote_warnings.append(check.get("error") or f"Remote {component} is unavailable or unverified.")
if not remote.get("registered"):
remote_warnings.append("Device registration at the tunnel receiver could not be confirmed. Check the tunnel host and configure remote access again.")
elif any(not item.get("available") for item in remote.get("ports", {}).values()):
remote_warnings.append("One or more service ports are unavailable at the tunnel receiver.")
if remote_warnings and active:
state = "degraded"
status_text = "SSH connected; browser access unavailable or unverified"
warnings = remote_warnings + warnings
tunnel_env = ctx["read_env_file"]("/etc/iomatex/reverse-tunnel.env")
tunnel_host = tunnel_env.get("TUNNEL_HOST", "").strip()
details = [
@ -845,6 +864,7 @@ def reverse_tunnel_card(ctx):
warnings[:3],
details=details,
tunnels=service_states,
remote_access=remote,
restartable=installed,
bootstrap_host=tunnel_host,
bootstrap_command=_reverse_tunnel_bootstrap_command(ctx, tunnel_host),