Add Edge printer gateway diagnostics

This commit is contained in:
Andrei Smaliak 2026-10-07 17:48:59 +02:00
parent f3b2f7e40b
commit 204b9d8e2b
6 changed files with 164 additions and 5 deletions

View File

@ -0,0 +1,7 @@
# Edge Console 3.1.21
- Allow authenticated platform gateway requests to the ONVIF probe endpoint. This fixes camera authorization failing with the misleading `Edge ONVIF service is unavailable` message while preview and PTZ routes remain available.
- Add local-network printer connectivity diagnostics for IPP, raw TCP, LPD and WSD ports. Raw document delivery is limited to TCP 9100 and 5 MB; WSD discovery alone is never reported as print readiness.
- Keep printer endpoints restricted to private or link-local addresses and trusted loopback gateway requests.
Validation: ONVIF and network-printer backend contract tests pass. Live deployment remains pending.

View File

@ -14,7 +14,7 @@
"version": "1.0.1"
},
"stage_ui": {
"version": "3.1.20"
"version": "3.1.21"
},
"stage_avahi": {
"version": "1.0.0"

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python3
import glob
import base64
import importlib.util
import ipaddress
import json
@ -55,7 +56,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 3.1.20"
UI_VERSION = "V 3.1.21"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo"
@ -347,6 +348,50 @@ def probe_onvif_camera(payload):
return result
def validate_printer_address(value):
try:
address = ipaddress.ip_address(str(value or "").strip())
except ValueError as error:
raise ValueError("Invalid printer IP address") from error
if not (address.is_private or address.is_link_local):
raise ValueError("Printer must use a local IP address")
return str(address)
def probe_network_printer(payload):
host = validate_printer_address((payload or {}).get("ip_address"))
protocols = []
for protocol, port in (("ipp", 631), ("raw", 9100), ("lpd", 515), ("wsd", 3911)):
try:
with socket.create_connection((host, port), timeout=1.5):
protocols.append({"protocol": protocol, "port": port})
except OSError:
continue
return {
"ok": True,
"reachable": bool(protocols),
"protocols": protocols,
"print_ready": any(item["protocol"] == "raw" for item in protocols),
}
def print_network_document(payload):
host = validate_printer_address((payload or {}).get("ip_address"))
if str((payload or {}).get("protocol", "raw")) != "raw":
raise ValueError("This version supports printing only through raw TCP port 9100")
encoded = str((payload or {}).get("document_base64", ""))
try:
document = base64.b64decode(encoded, validate=True)
except (ValueError, TypeError) as error:
raise ValueError("Invalid print document") from error
if not document or len(document) > 5 * 1024 * 1024:
raise ValueError("Print document must be between 1 byte and 5 MB")
with socket.create_connection((host, 9100), timeout=5) as printer_socket:
printer_socket.settimeout(15)
printer_socket.sendall(document)
return {"ok": True, "bytes_sent": len(document), "protocol": "raw", "port": 9100}
def control_onvif_camera(payload):
request = dict(payload) if isinstance(payload, dict) else {}
action = str(request.get("action", "")).strip()
@ -3311,7 +3356,13 @@ class Handler(BaseHTTPRequestHandler):
if (
(
parsed.path.startswith("/api/camera-preview/")
or parsed.path in {"/api/onvif/ptz", "/api/camera-stream/start"}
or parsed.path in {
"/api/onvif/probe",
"/api/onvif/ptz",
"/api/camera-stream/start",
"/api/printer/test",
"/api/printer/print",
}
)
and self.headers.get("X-Iomatex-Gateway-Authorized") == "1"
and self.client_address[0] in {"127.0.0.1", "::1"}
@ -3651,6 +3702,33 @@ class Handler(BaseHTTPRequestHandler):
except Exception:
self.send_json({"ok": False, "error": "ONVIF client is unavailable"}, code=503)
return
if parsed.path == "/api/printer/test":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
result = probe_network_printer(payload)
self.send_json(result)
except ValueError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=400)
except Exception:
self.send_json({"ok": False, "error": "Printer connectivity test failed"}, code=503)
return
if parsed.path == "/api/printer/print":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
self.send_json(print_network_document(payload))
except ValueError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=400)
except OSError:
self.send_json({"ok": False, "error": "Printer raw port 9100 is unavailable"}, code=424)
except Exception:
self.send_json({"ok": False, "error": "Print operation failed"}, code=503)
return
if parsed.path == "/api/onvif/ptz":
payload = self.read_json_body()
if payload is None:

View File

@ -0,0 +1,74 @@
import base64
import importlib.util
import pathlib
import sys
import unittest
from unittest import mock
BACKEND_DIR = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(BACKEND_DIR))
SPEC = importlib.util.spec_from_file_location("iomatex_console_printer_app", BACKEND_DIR / "app.py")
APP = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(APP)
class FakePrinterSocket:
def __init__(self):
self.payload = b""
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def settimeout(self, _timeout):
pass
def sendall(self, payload):
self.payload = payload
class NetworkPrinterContractTest(unittest.TestCase):
def test_rejects_public_printer_address(self):
with self.assertRaises(ValueError):
APP.probe_network_printer({"ip_address": "8.8.8.8"})
def test_reports_only_reachable_print_protocols(self):
def connect(address, timeout):
if address[1] in {9100, 3911}:
return FakePrinterSocket()
raise OSError("closed")
with mock.patch.object(APP.socket, "create_connection", side_effect=connect):
result = APP.probe_network_printer({"ip_address": "192.168.70.130"})
self.assertTrue(result["reachable"])
self.assertTrue(result["print_ready"])
self.assertEqual([item["protocol"] for item in result["protocols"]], ["raw", "wsd"])
def test_sends_bounded_document_to_raw_port(self):
printer = FakePrinterSocket()
with mock.patch.object(APP.socket, "create_connection", return_value=printer) as connect:
result = APP.print_network_document({
"ip_address": "192.168.70.130",
"protocol": "raw",
"document_base64": base64.b64encode(b"test page").decode("ascii"),
})
connect.assert_called_once_with(("192.168.70.130", 9100), timeout=5)
self.assertEqual(printer.payload, b"test page")
self.assertEqual(result["bytes_sent"], 9)
def test_printer_routes_are_gateway_authorized_and_local_only(self):
source = (BACKEND_DIR / "app.py").read_text(encoding="utf-8")
self.assertIn('"/api/printer/test"', source)
self.assertIn('"/api/printer/print"', source)
self.assertIn("address.is_private or address.is_link_local", source)
self.assertIn('(\"raw\", 9100)', source)
self.assertIn("5 * 1024 * 1024", source)
if __name__ == "__main__":
unittest.main()

View File

@ -113,7 +113,7 @@ class OnvifProbeTest(unittest.TestCase):
self.assertLess(auth_index, route_index)
self.assertLess(route_index, ptz_index)
self.assertLess(ptz_index, preview_index)
self.assertIn('or parsed.path in {"/api/onvif/ptz", "/api/camera-stream/start"}', source)
self.assertIn('"/api/onvif/probe",', source)
self.assertIn('"ONVIF client is unavailable"', source[route_index:ptz_index])
self.assertIn('"ONVIF PTZ client is unavailable"', source[ptz_index:preview_index])

View File

@ -1,3 +1,3 @@
{
"version": "3.1.20"
"version": "3.1.21"
}