Fix environment-assigned reverse tunnel ports; Console 3.1.26

This commit is contained in:
Andrei Smaliak 2026-10-25 09:05:14 +01:00
parent f6dc3d94cc
commit 4cab7580a0
14 changed files with 165 additions and 16 deletions

View File

@ -0,0 +1,13 @@
# Edge Console 3.1.26
- Apply all three receiver-assigned reverse tunnel ports during registration,
server migration and the existing Configure action. Previously only the SSH
gateway/user changed, leaving old ports that the new receiver rejected.
- Validate complete, distinct TCP port assignments before changing local files.
- Migrate installed legacy wrappers to read assigned ports from the shared
environment file, preserving their SSH keys and local service endpoints.
- After a Console update, retry enrollment once using the existing client
registration. Offline/unregistered devices retain the manual Configure retry;
no client registration reset or client restart is required.
- Validation: 126 Console tests, 7 tunnel tests and 24 stage catalog tests pass.
Shell syntax checks pass for both installers.

View File

@ -0,0 +1,8 @@
# Reverse Tunnels 1.0.2
- Read remote cockpit, webui and z2m ports from the environment assigned by
Console enrollment, with legacy derived ports as the pre-enrollment fallback.
- Preserve enrolled port assignments when reinstalling/updating this stage.
- Works with Console 3.1.26 to restore remote access after environment migration.
- Validation: installer lifecycle and generated-wrapper tests pass, including
saved gateway/port preservation and shell syntax checks.

View File

@ -14,7 +14,7 @@
"version": "1.0.1" "version": "1.0.1"
}, },
"stage_ui": { "stage_ui": {
"version": "3.1.25" "version": "3.1.26"
}, },
"stage_avahi": { "stage_avahi": {
"version": "1.0.0" "version": "1.0.0"
@ -26,7 +26,7 @@
"version": "1.0.28" "version": "1.0.28"
}, },
"stage_reverse_tunnels": { "stage_reverse_tunnels": {
"version": "1.0.1" "version": "1.0.2"
} }
}, },
"optional_stages": { "optional_stages": {

View File

@ -111,8 +111,8 @@ load_environment_config() {
if [[ -f "$CONFIG_FILE" ]]; then if [[ -f "$CONFIG_FILE" ]]; then
while IFS='=' read -r name value || [[ -n "$name" ]]; do while IFS='=' read -r name value || [[ -n "$name" ]]; do
case "$name" in case "$name" in
TUNNEL_HOST|TUNNEL_PORT|TUNNEL_OPERATOR_USER|TUNNEL_SSH_USER) TUNNEL_HOST|TUNNEL_PORT|TUNNEL_OPERATOR_USER|TUNNEL_SSH_USER|TUNNEL_REMOTE_COCKPIT|TUNNEL_REMOTE_Z2M|TUNNEL_REMOTE_WEBUI)
[[ -n "${!name}" ]] || printf -v "$name" '%s' "$value" [[ -n "${!name:-}" ]] || printf -v "$name" '%s' "$value"
;; ;;
esac esac
done <"$CONFIG_FILE" done <"$CONFIG_FILE"
@ -170,6 +170,14 @@ TUNNEL_PORT=${TUNNEL_PORT}
TUNNEL_OPERATOR_USER=${TUNNEL_OPERATOR_USER} TUNNEL_OPERATOR_USER=${TUNNEL_OPERATOR_USER}
TUNNEL_SSH_USER=${TUNNEL_SSH_USER} TUNNEL_SSH_USER=${TUNNEL_SSH_USER}
EOF EOF
# Preserve the receiver-assigned ports across installer upgrades.
local name
for name in TUNNEL_REMOTE_COCKPIT TUNNEL_REMOTE_Z2M TUNNEL_REMOTE_WEBUI; do
if [[ -n "${!name:-}" ]]; then
validate_port "${!name}" "$name"
printf '%s=%s\n' "$name" "${!name}" >> "$CONFIG_FILE"
fi
done
chmod 0644 "$CONFIG_FILE" chmod 0644 "$CONFIG_FILE"
} }
@ -247,6 +255,7 @@ write_wrapper() {
local key="$5" local key="$5"
local edge_home="$6" local edge_home="$6"
local wrapper_path="${WRAPPER_DIR}/iomatex-rt-${name}.sh" local wrapper_path="${WRAPPER_DIR}/iomatex-rt-${name}.sh"
local port_variable="TUNNEL_REMOTE_${name^^}"
cat >"$wrapper_path" <<EOF cat >"$wrapper_path" <<EOF
#!/usr/bin/env bash #!/usr/bin/env bash
@ -260,7 +269,7 @@ exec autossh -M 0 -N \\
-o UserKnownHostsFile="${edge_home}/.ssh/known_hosts" \\ -o UserKnownHostsFile="${edge_home}/.ssh/known_hosts" \\
-i "${key}" \\ -i "${key}" \\
-p "\${TUNNEL_PORT}" \\ -p "\${TUNNEL_PORT}" \\
-R 127.0.0.1:${remote_port}:127.0.0.1:${local_port} \\ -R 127.0.0.1:\${${port_variable}:-${remote_port}}:127.0.0.1:${local_port} \\
"\${TUNNEL_SSH_USER}@\${TUNNEL_HOST}" "\${TUNNEL_SSH_USER}@\${TUNNEL_HOST}"
EOF EOF

View File

@ -69,6 +69,7 @@ main
wrapper = root / f"iomatex-rt-{name}.sh" wrapper = root / f"iomatex-rt-{name}.sh"
subprocess.run(["bash", "-n", str(wrapper)], check=True) subprocess.run(["bash", "-n", str(wrapper)], check=True)
self.assertIn('${TUNNEL_SSH_USER}@${TUNNEL_HOST}', wrapper.read_text()) self.assertIn('${TUNNEL_SSH_USER}@${TUNNEL_HOST}', wrapper.read_text())
self.assertIn('${TUNNEL_REMOTE_' + name.upper() + ':-', wrapper.read_text())
return config.read_text(), result.stdout return config.read_text(), result.stdout
def test_fresh_install_waits_for_registration(self): def test_fresh_install_waits_for_registration(self):
@ -82,6 +83,14 @@ main
config, _ = self.run_installer(saved, registration_host="app.example.test") config, _ = self.run_installer(saved, registration_host="app.example.test")
self.assertEqual(config, saved) self.assertEqual(config, saved)
def test_reinstall_preserves_server_ports(self):
saved = ("TUNNEL_HOST=ssh.example.test\nTUNNEL_PORT=2222\n"
"TUNNEL_OPERATOR_USER=operator\nTUNNEL_SSH_USER=custom-tunnel\n"
"TUNNEL_REMOTE_COCKPIT=34589\nTUNNEL_REMOTE_Z2M=34590\n"
"TUNNEL_REMOTE_WEBUI=34591\n")
config, _ = self.run_installer(saved)
self.assertEqual(saved, config)
def test_explicit_host_overrides_saved_gateway(self): def test_explicit_host_overrides_saved_gateway(self):
config, _ = self.run_installer("TUNNEL_HOST=old.example.test\n", config, _ = self.run_installer("TUNNEL_HOST=old.example.test\n",
explicit_host="new.example.test") explicit_host="new.example.test")

View File

@ -1,3 +1,3 @@
{ {
"version": "1.0.1" "version": "1.0.2"
} }

View File

@ -60,7 +60,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public") PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json" CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 3.1.25" UI_VERSION = "V 3.1.26"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health" STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo" ZONEINFO_ROOT = "/usr/share/zoneinfo"

View File

@ -39,6 +39,7 @@ SETTINGS_CATEGORY = "server"
ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf" 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" REGISTRATION_STORE_PATH = "/var/lib/itscreen/data/it-screen/it-screen/registration.ini"
REVERSE_TUNNEL_CONFIG_PATH = "/etc/iomatex/reverse-tunnel.env" REVERSE_TUNNEL_CONFIG_PATH = "/etc/iomatex/reverse-tunnel.env"
REVERSE_TUNNEL_WRAPPER_DIR = "/usr/local/sbin"
MQTT_BRIDGE_APPLY_PATH = "/usr/local/sbin/iomatex-mqtt-apply" MQTT_BRIDGE_APPLY_PATH = "/usr/local/sbin/iomatex-mqtt-apply"
MQTT_TOPIC_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._-]+$") MQTT_TOPIC_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._-]+$")
DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices") DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices")
@ -547,7 +548,11 @@ def _enroll_reverse_tunnel(state):
if not ssh_host or not 1 <= ssh_port <= 65535: if not ssh_host or not 1 <= ssh_port <= 65535:
raise RuntimeError("Environment returned an invalid SSH gateway") raise RuntimeError("Environment returned an invalid SSH gateway")
_write_reverse_tunnel_config(ssh_host, ssh_port, ssh_user) # Receiver-assigned ports belong to the registration environment, not the
# hardware identity. Never reuse the previous environment's port mapping.
ports = _validate_reverse_tunnel_ports(tunnel["ports"])
_migrate_reverse_tunnel_wrappers()
_write_reverse_tunnel_config(ssh_host, ssh_port, ssh_user, ports)
subprocess.run([ subprocess.run([
"systemctl", "restart", "systemctl", "restart",
@ -558,7 +563,54 @@ def _enroll_reverse_tunnel(state):
return tunnel return tunnel
def _write_reverse_tunnel_config(ssh_host, ssh_port=22, ssh_user="iomatex-tunnel"): def _validate_reverse_tunnel_ports(ports):
result = {}
for name in ("cockpit", "z2m", "webui"):
value = ports.get(name)
if isinstance(value, bool) or not re.fullmatch(r"[0-9]{1,5}", str(value or "")):
raise RuntimeError("Environment returned an invalid reverse tunnel port: " + name)
value = int(value)
if not 1 <= value <= 65535:
raise RuntimeError("Environment returned an invalid reverse tunnel port: " + name)
result[name] = value
if len(set(result.values())) != 3:
raise RuntimeError("Environment returned duplicate reverse tunnel ports")
return result
def _migrate_reverse_tunnel_wrappers():
"""Upgrade installed legacy wrappers without changing keys or local targets.
The fallback keeps the old environment working until the new env file is
atomically committed. Subsequent enrollments only replace that env file.
"""
updates = []
for name in ("cockpit", "z2m", "webui"):
path = os.path.join(REVERSE_TUNNEL_WRAPPER_DIR, "iomatex-rt-" + name + ".sh")
with open(path, encoding="utf-8") as stream:
source = stream.read()
variable = "TUNNEL_REMOTE_" + name.upper()
if "${" + variable in source:
continue
pattern = r"(-R 127\.0\.0\.1:)([0-9]+)(:127\.0\.0\.1:[0-9]+)"
updated, count = re.subn(pattern, lambda m: m[1] + "${" + variable + ":-" + m[2] + "}" + m[3], source)
if count != 1:
raise RuntimeError("Cannot migrate reverse tunnel wrapper: " + name)
updates.append((path, updated))
# Validate all wrappers before modifying any; preserve the existing modes.
for path, updated in updates:
fd, temporary = tempfile.mkstemp(prefix=".tunnel-", dir=REVERSE_TUNNEL_WRAPPER_DIR)
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(updated)
os.chmod(temporary, os.stat(path).st_mode & 0o777)
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def _write_reverse_tunnel_config(ssh_host, ssh_port=22, ssh_user="iomatex-tunnel", ports=None):
directory = os.path.dirname(REVERSE_TUNNEL_CONFIG_PATH) directory = os.path.dirname(REVERSE_TUNNEL_CONFIG_PATH)
os.makedirs(directory, exist_ok=True) os.makedirs(directory, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix="reverse-tunnel.", suffix=".env", dir=directory, text=True) fd, temporary = tempfile.mkstemp(prefix="reverse-tunnel.", suffix=".env", dir=directory, text=True)
@ -567,6 +619,9 @@ def _write_reverse_tunnel_config(ssh_host, ssh_port=22, ssh_user="iomatex-tunnel
stream.write(f"TUNNEL_HOST={ssh_host}\nTUNNEL_PORT={ssh_port}\n") stream.write(f"TUNNEL_HOST={ssh_host}\nTUNNEL_PORT={ssh_port}\n")
stream.write("TUNNEL_OPERATOR_USER=builder\n") stream.write("TUNNEL_OPERATOR_USER=builder\n")
stream.write(f"TUNNEL_SSH_USER={ssh_user}\n") stream.write(f"TUNNEL_SSH_USER={ssh_user}\n")
if ports is not None:
for name, port in ports.items():
stream.write(f"TUNNEL_REMOTE_{name.upper()}={port}\n")
os.chmod(temporary, 0o644) os.chmod(temporary, 0o644)
os.replace(temporary, REVERSE_TUNNEL_CONFIG_PATH) os.replace(temporary, REVERSE_TUNNEL_CONFIG_PATH)
finally: finally:

View File

@ -112,15 +112,19 @@ class ReverseTunnelConfigurationTest(unittest.TestCase):
def test_enrollment_writes_gateway_and_restarts_existing_units_once(self): def test_enrollment_writes_gateway_and_restarts_existing_units_once(self):
config_path = pathlib.Path(self.directory.name) / "reverse-tunnel.env" config_path = pathlib.Path(self.directory.name) / "reverse-tunnel.env"
for name, port in (("cockpit", 22589), ("z2m", 22590), ("webui", 22591)):
wrapper = pathlib.Path(self.directory.name) / ("iomatex-rt-" + name + ".sh")
wrapper.write_text("#!/bin/bash\nexec autossh -R 127.0.0.1:%s:127.0.0.1:9090\n" % port)
response = Mock() response = Mock()
response.read.return_value = json.dumps({"reverse_tunnel": { response.read.return_value = json.dumps({"reverse_tunnel": {
"ssh_host": "gateway.example.com", "ssh_port": 2222, "ssh_host": "gateway.example.com", "ssh_port": 2222,
"ssh_user": "iomatex-tunnel", "ports": {"webui": 23000}, "ssh_user": "iomatex-tunnel", "ports": {"cockpit": 34589, "z2m": 34590, "webui": 34591},
}}).encode() }}).encode()
context = Mock() context = Mock()
context.__enter__ = Mock(return_value=response) context.__enter__ = Mock(return_value=response)
context.__exit__ = Mock(return_value=False) context.__exit__ = Mock(return_value=False)
with patch.object(registration, "REVERSE_TUNNEL_CONFIG_PATH", str(config_path)), \ with patch.object(registration, "REVERSE_TUNNEL_WRAPPER_DIR", self.directory.name), \
patch.object(registration, "REVERSE_TUNNEL_CONFIG_PATH", str(config_path)), \
patch.object(registration, "_reverse_tunnel_public_key", return_value="ssh-ed25519 test-key"), \ patch.object(registration, "_reverse_tunnel_public_key", return_value="ssh-ed25519 test-key"), \
patch.object(registration, "urlopen", return_value=context) as request, \ patch.object(registration, "urlopen", return_value=context) as request, \
patch.object(registration.subprocess, "run") as command: patch.object(registration.subprocess, "run") as command:
@ -130,6 +134,10 @@ class ReverseTunnelConfigurationTest(unittest.TestCase):
self.assertEqual(8, request.call_args.kwargs["timeout"]) self.assertEqual(8, request.call_args.kwargs["timeout"])
self.assertEqual("https://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()) self.assertIn("TUNNEL_HOST=gateway.example.com\nTUNNEL_PORT=2222\n", config_path.read_text())
self.assertIn("TUNNEL_REMOTE_COCKPIT=34589", config_path.read_text())
self.assertIn("TUNNEL_REMOTE_WEBUI=34591", config_path.read_text())
self.assertIn("${TUNNEL_REMOTE_COCKPIT:-22589}",
(pathlib.Path(self.directory.name) / "iomatex-rt-cockpit.sh").read_text())
command.assert_called_once_with([ command.assert_called_once_with([
"systemctl", "restart", "iomatex-rt-cockpit.service", "systemctl", "restart", "iomatex-rt-cockpit.service",
"iomatex-rt-z2m.service", "iomatex-rt-webui.service", "iomatex-rt-z2m.service", "iomatex-rt-webui.service",

View File

@ -1,3 +1,5 @@
import os
import subprocess
import pathlib import pathlib
import tempfile import tempfile
import unittest import unittest
@ -6,6 +8,35 @@ import itscreen_registration as registration
class RegistrationTunnelSwitchTest(unittest.TestCase): class RegistrationTunnelSwitchTest(unittest.TestCase):
def test_migrated_wrapper_uses_new_ports_and_keeps_local_target(self):
with tempfile.TemporaryDirectory() as directory:
root = pathlib.Path(directory)
for name, local in (("cockpit", 9090), ("z2m", 8081), ("webui", 8099)):
wrapper = root / ("iomatex-rt-" + name + ".sh")
wrapper.write_text("#!/bin/bash\nexec autossh -R 127.0.0.1:22589:127.0.0.1:%s\n" % local)
wrapper.chmod(0o755)
stub = root / "autossh"
stub.write_text('#!/bin/sh\nprintf "%s\\n" "$@"\n')
stub.chmod(0o755)
with patch.object(registration, "REVERSE_TUNNEL_WRAPPER_DIR", directory):
registration._migrate_reverse_tunnel_wrappers()
before = (root / "iomatex-rt-cockpit.sh").read_text()
registration._migrate_reverse_tunnel_wrappers()
self.assertEqual(before, (root / "iomatex-rt-cockpit.sh").read_text())
for name, local, remote in (("cockpit", 9090, 34589), ("z2m", 8081, 34590), ("webui", 8099, 34591)):
env = dict(os.environ, PATH=directory + ":" + os.environ["PATH"])
env["TUNNEL_REMOTE_" + name.upper()] = str(remote)
output = subprocess.check_output([str(root / ("iomatex-rt-" + name + ".sh"))], env=env, text=True)
self.assertIn("127.0.0.1:%s:127.0.0.1:%s" % (remote, local), output)
def test_invalid_server_ports_are_rejected(self):
valid = {"cockpit": 34589, "z2m": 34590, "webui": 34591}
for bad in (None, True, 0, 65536, "12; reboot", 34590):
with self.subTest(port=bad), self.assertRaises(RuntimeError):
registration._validate_reverse_tunnel_ports(dict(valid, cockpit=bad))
with self.assertRaises(RuntimeError):
registration._validate_reverse_tunnel_ports({"webui": 34591})
def test_new_server_disables_old_target_before_enrollment(self): def test_new_server_disables_old_target_before_enrollment(self):
with tempfile.TemporaryDirectory() as directory: with tempfile.TemporaryDirectory() as directory:
path = pathlib.Path(directory) / 'reverse.env' path = pathlib.Path(directory) / 'reverse.env'

View File

@ -49,7 +49,7 @@
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" }, { mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" } { mode: "custom", label: "Custom", host: "" }
]; ];
const UI_VERSION = "V 3.1.25"; const UI_VERSION = "V 3.1.26";
const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250; const ITSCREEN_LOG_BATCH_MS = 250;

View File

@ -23,7 +23,7 @@
} catch (error) {} } catch (error) {}
})(); })();
</script> </script>
<link rel="stylesheet" href="/console.css?v=3.1.25&amp;rev=edge-runtime-profile-1"> <link rel="stylesheet" href="/console.css?v=3.1.26&amp;rev=edge-runtime-profile-1">
</head> </head>
<body> <body>
<main class="shell"> <main class="shell">
@ -109,7 +109,7 @@
</main> </main>
<div id="menuBackdrop" class="menuBackdrop" hidden></div> <div id="menuBackdrop" class="menuBackdrop" hidden></div>
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div> <div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
<script src="/console.i18n.js?v=3.1.25&amp;rev=edge-runtime-profile-1"></script> <script src="/console.i18n.js?v=3.1.26&amp;rev=edge-runtime-profile-1"></script>
<script src="/console.js?v=3.1.25&amp;rev=edge-runtime-profile-1"></script> <script src="/console.js?v=3.1.26&amp;rev=edge-runtime-profile-1"></script>
</body> </body>
</html> </html>

View File

@ -388,6 +388,22 @@ if [ -x /usr/local/sbin/iomatex-ap-refresh-landing ]; then
/usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true /usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true
fi fi
# Refresh enrollment once after an update; use the same owner as the Console
# Configure action. Offline/unregistered devices can retry from that action.
step "Refresh reverse tunnel registration"
if ! PYTHONPATH="$BACKEND_DIR" timeout 40 python3 - <<'PYTUNNEL'
from itscreen_registration import configure_reverse_tunnel
try:
configure_reverse_tunnel()
print("Reverse tunnel gateway and assigned ports refreshed.")
except Exception as exc:
print("Reverse tunnel refresh deferred: " + str(exc))
raise SystemExit(1)
PYTUNNEL
then
echo "Console installed; retry reverse tunnel Configure when registration/server is available."
fi
step "Summary" step "Summary"
echo "Web UI: http://<EDGE-IP>" echo "Web UI: http://<EDGE-IP>"
echo "Web UI (extra): http://<EDGE-IP>:${APP_EXTRA_PORT}" echo "Web UI (extra): http://<EDGE-IP>:${APP_EXTRA_PORT}"

View File

@ -1,3 +1,3 @@
{ {
"version": "3.1.25" "version": "3.1.26"
} }