diff --git a/adn-server.example.yaml b/adn-server.example.yaml index 5ff7fde..7308c4c 100644 --- a/adn-server.example.yaml +++ b/adn-server.example.yaml @@ -49,6 +49,14 @@ REPORTS: # QOS: 0 # Wire: state (retained), voice_event (live) +# Optional: send this server's state (version, ports, OBP links) to the ADN panel. +# Generate the token on your server's page in the panel; it also shows the ENDPOINT. +# ADN_PANEL: +# ENDPOINT: "" # https:// only +# TOKEN: "" +# REPORT_INTERVAL: 300 # seconds, 60-86400 +# ODTP_PORT: 54006 # optional: port of the ODTP gateway (its own service) + LOGGER: # ENABLED: false # omit or true = normal; false = no console/file logs (NullHandler) LOG_FILE: /var/log/adn-server/adn-server.log diff --git a/docs/en/server/user-guide/monitoring.md b/docs/en/server/user-guide/monitoring.md index b057db1..bc5dff9 100644 --- a/docs/en/server/user-guide/monitoring.md +++ b/docs/en/server/user-guide/monitoring.md @@ -121,21 +121,23 @@ Look up the same stream ID in the server log: The server can send the ADN panel its own state: version, uptime, the HBP port hotspots connect to, the ODTP and OBP proxy ports, how many peers are connected, its OpenBridge links with their keepalive state, and the plugins loaded. The panel shows it on the server's page and uses the ports in the public server list (so apps learn the ODTP port from there). -It is off unless the sysop sets it up, and it is **not** in `adn-server.example.yaml`: generate a token on your server's page in the panel (the *Server report* action), then add the section by hand: +It is off unless the sysop sets it up (`adn-server.example.yaml` has the section commented out): generate a token on your server's page in the panel (the *Server report* action), which also shows the endpoint, then add the section by hand: ```yaml ADN_PANEL: ENDPOINT: TOKEN: adn_xxxxxxxxxxxx # belongs to this server only - REPORT_INTERVAL: 300 # seconds, minimum 60 (default 300) + REPORT_INTERVAL: 300 # seconds, 60-86400 (default 300) ODTP_PORT: 54006 # optional: the ODTP gateway runs as its own service ``` -- Without `ENDPOINT` and `TOKEN` nothing is sent. +- Without `ENDPOINT` and `TOKEN` nothing is sent. The endpoint must be `https://` (plain `http://` only for localhost), and a redirect is treated as a failure, never followed, so the token cannot leak to another host. - The token says which server the report is from; a new token from the panel replaces the old one. - The report carries no IP addresses, passphrases or user IDs. - The first report goes out one minute after start, then every `REPORT_INTERVAL`. The POST runs off the reactor with a 10 s timeout, so a slow or unreachable panel never delays traffic. - A failure is logged once as `(ADN_PANEL) Could not send the report: ...` (HTTP 401/403 means the token is wrong or was revoked), and again when it works. +- A config reload applies at once: a new token, a different `REPORT_INTERVAL`, or removing the section (which stops the reports). +- Without the integrated proxy, `hbp_ports` lists the enabled MASTER ports except those bound to loopback (internal). ## Requirements diff --git a/docs/es/server/user-guide/monitoring.md b/docs/es/server/user-guide/monitoring.md index 83069a0..6066558 100644 --- a/docs/es/server/user-guide/monitoring.md +++ b/docs/es/server/user-guide/monitoring.md @@ -121,21 +121,23 @@ Busca el mismo stream ID en el log del servidor: El servidor puede enviar al panel de ADN su propio estado: versión, tiempo encendido, el puerto HBP al que se conectan los hotspots, los puertos de ODTP y del proxy OBP, cuántos peers hay conectados, sus enlaces OpenBridge con el estado del keepalive y los plugins cargados. El panel lo muestra en la ficha del servidor y usa los puertos en la lista pública de servidores (de ahí sacan las apps el puerto ODTP). -Está apagado salvo que el sysop lo configure, y **no** viene en `adn-server.example.yaml`: genera un token en la ficha de tu servidor en el panel (la acción *Informe del servidor*) y añade la sección a mano: +Está apagado salvo que el sysop lo configure (`adn-server.example.yaml` trae la sección comentada): genera un token en la ficha de tu servidor en el panel (la acción *Informe del servidor*), que también muestra el endpoint, y añade la sección a mano: ```yaml ADN_PANEL: ENDPOINT: TOKEN: adn_xxxxxxxxxxxx # solo vale para este servidor - REPORT_INTERVAL: 300 # segundos, mínimo 60 (300 por defecto) + REPORT_INTERVAL: 300 # segundos, 60-86400 (300 por defecto) ODTP_PORT: 54006 # opcional: la pasarela ODTP es un servicio aparte ``` -- Sin `ENDPOINT` y `TOKEN` no se envía nada. +- Sin `ENDPOINT` y `TOKEN` no se envía nada. El endpoint tiene que ser `https://` (`http://` solo para localhost), y una redirección cuenta como fallo y no se sigue, así que el token no puede acabar en otro host. - El token dice de qué servidor es el informe; un token nuevo generado en el panel sustituye al anterior. - El informe no lleva direcciones IP, passphrases ni IDs de usuarios. - El primer informe sale un minuto después de arrancar y luego cada `REPORT_INTERVAL`. El envío va fuera del reactor con un timeout de 10 s, así que un panel lento o caído nunca retrasa el tráfico. - Un fallo se registra una sola vez como `(ADN_PANEL) Could not send the report: ...` (HTTP 401/403 = token incorrecto o revocado), y otra vez cuando vuelve a funcionar. +- Una recarga de la config se aplica al momento: un token nuevo, otro `REPORT_INTERVAL` o quitar la sección (que detiene los informes). +- Sin el proxy integrado, `hbp_ports` lista los puertos de los MASTER activos salvo los atados a loopback (internos). ## Requisitos diff --git a/src/adn_server/application/report/panel_report.py b/src/adn_server/application/report/panel_report.py index 0fab7d3..650cf63 100644 --- a/src/adn_server/application/report/panel_report.py +++ b/src/adn_server/application/report/panel_report.py @@ -26,9 +26,11 @@ it is not in the config template. Without ENDPOINT and TOKEN nothing is sent. from __future__ import annotations +import ipaddress from collections.abc import Iterable from dataclasses import dataclass from typing import Any +from urllib.parse import urlsplit from adn_server.application.proxy.deployment import ( obp_proxy_enabled, @@ -51,6 +53,26 @@ class PanelReportSettings: odtp_port: int | None +def is_loopback_host(host: str | None) -> bool: + if not host: + return False + if host.lower() == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +def endpoint_allowed(endpoint: str) -> bool: + """https only: the bearer token must not travel in cleartext. http is accepted for + localhost, where tests or a local relay may listen.""" + parts = urlsplit(endpoint) + if parts.scheme == "https": + return bool(parts.hostname) + return parts.scheme == "http" and is_loopback_host(parts.hostname) + + def panel_report_settings(config: dict[str, Any]) -> PanelReportSettings | None: """``ADN_PANEL`` settings, or None when the server does not report to the panel.""" block = config.get("ADN_PANEL") @@ -58,7 +80,7 @@ def panel_report_settings(config: dict[str, Any]) -> PanelReportSettings | None: return None endpoint = str(block.get("ENDPOINT") or "").strip().rstrip("/") token = str(block.get("TOKEN") or "").strip() - if not endpoint or not token: + if not endpoint or not token or not endpoint_allowed(endpoint): return None interval = max(int(block.get("REPORT_INTERVAL") or DEFAULT_INTERVAL), MIN_INTERVAL) odtp_port = block.get("ODTP_PORT") @@ -71,7 +93,8 @@ def panel_report_settings(config: dict[str, Any]) -> PanelReportSettings | None: def _hbp_ports(config: dict[str, Any]) -> list[int]: - """Ports hotspots connect to: the integrated proxy's, else each enabled MASTER's.""" + """Ports hotspots connect to: the integrated proxy's, else each enabled MASTER's + except those bound to loopback (internal, e.g. a local gateway's master).""" if proxy_target_system(config) is not None: return [int(config.get("PROXY", {}).get("LISTEN_PORT", 62031))] ports = { @@ -81,6 +104,7 @@ def _hbp_ports(config: dict[str, Any]) -> list[int]: and cfg.get("ENABLED", True) and cfg.get("MODE") == "MASTER" and cfg.get("PORT") + and not is_loopback_host(str(cfg.get("IP") or "")) } return sorted(ports) diff --git a/src/adn_server/infrastructure/bootstrap/peer_server.py b/src/adn_server/infrastructure/bootstrap/peer_server.py index 7529282..07cfbd3 100644 --- a/src/adn_server/infrastructure/bootstrap/peer_server.py +++ b/src/adn_server/infrastructure/bootstrap/peer_server.py @@ -518,15 +518,19 @@ def run_peer_server( start_loop(reporting_loop, report_interval, logger) # ADN panel report (ADN_PANEL, added by hand with the token from the panel). Settings - # are read on every tick, so a config reload can add, change or remove them. - # The payload is built on the reactor; the HTTP POST runs in a thread. + # are read on every tick, so a config reload can add, change or remove them, and + # the loop follows REPORT_INTERVAL. The payload is built on the reactor; the HTTP + # POST runs in a thread. panel_log = PanelReportLog(logger) panel_user_agent = f"adn-server/{__version__}" + panel_loop: list[Any] = [] def panel_report_loop() -> None: settings = panel_report_settings(config) if settings is None: return + if panel_loop and panel_loop[0].interval != settings.interval: + panel_loop[0].interval = settings.interval payload = build_panel_report( config, version=__version__, @@ -543,7 +547,9 @@ def run_peer_server( if panel_settings is not None: logger.info("(ADN_PANEL) Reporting to %s every %s s", panel_settings.url, panel_interval) # First report once hotspots and OBP links had time to connect. - reactor.callLater(60, lambda: start_loop(panel_report_loop, panel_interval, logger)) + reactor.callLater( + 60, lambda: panel_loop.append(start_loop(panel_report_loop, panel_interval, logger)) + ) # LoopingCalls (legacy intervals). rule_timer / stat_trimmer mutate SubscriptionStore on reactor # Timer loops run on the reactor thread (no deferToThread — avoids races with dmrd_received). diff --git a/src/adn_server/infrastructure/config_validator.py b/src/adn_server/infrastructure/config_validator.py index 5bc0b8b..597fa0c 100644 --- a/src/adn_server/infrastructure/config_validator.py +++ b/src/adn_server/infrastructure/config_validator.py @@ -25,6 +25,7 @@ from typing import Any from adn_server.application.odtp.ports import SMS_FORMATS from adn_server.application.proxy.deployment import config_has_enabled_openbridge +from adn_server.application.report.panel_report import endpoint_allowed from adn_server.application.routing.loop_guard import MAX_LOOP_GUARD_HOLD_S from ..domain.errors import ConfigError @@ -465,8 +466,10 @@ def _validate_adn_panel(panel_cfg: Any, errors: list[str]) -> None: if key in panel_cfg: _expect_str(f"ADN_PANEL.{key}", panel_cfg[key], errors) endpoint = panel_cfg.get("ENDPOINT") - if isinstance(endpoint, str) and endpoint.strip() and not endpoint.strip().startswith(("https://", "http://")): - errors.append(f"ADN_PANEL.ENDPOINT: {endpoint!r}, expected an http(s):// URL.") + if isinstance(endpoint, str) and endpoint.strip() and not endpoint_allowed(endpoint.strip()): + errors.append( + f"ADN_PANEL.ENDPOINT: {endpoint!r}, expected an https:// URL (http only for localhost)." + ) for key, (low, high) in (("REPORT_INTERVAL", (60, 86400)), ("ODTP_PORT", (1, 65535))): value = panel_cfg.get(key) if _is_empty(value): diff --git a/src/adn_server/infrastructure/panel/report_client.py b/src/adn_server/infrastructure/panel/report_client.py index cf97696..6310c35 100644 --- a/src/adn_server/infrastructure/panel/report_client.py +++ b/src/adn_server/infrastructure/panel/report_client.py @@ -26,13 +26,24 @@ import json import logging from typing import Any from urllib.error import HTTPError, URLError -from urllib.request import Request, urlopen +from urllib.request import HTTPRedirectHandler, Request, build_opener from adn_server.application.report.panel_report import PanelReportSettings TIMEOUT_S = 10 +class _NoRedirect(HTTPRedirectHandler): + """A 3xx is a failure: following it would send the Authorization header to + whatever host the redirect names.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +_opener = build_opener(_NoRedirect()) + + def send_panel_report(settings: PanelReportSettings, payload: dict[str, Any], user_agent: str) -> int: """Send the report; returns the HTTP status. Raises on network errors.""" request = Request( @@ -46,7 +57,7 @@ def send_panel_report(settings: PanelReportSettings, payload: dict[str, Any], us }, ) try: - with urlopen(request, timeout=TIMEOUT_S) as response: + with _opener.open(request, timeout=TIMEOUT_S) as response: return response.status except HTTPError as exc: return exc.code @@ -67,7 +78,12 @@ class PanelReportLog: self._logger.debug("(ADN_PANEL) Report sent (HTTP %s)", status) self._failing = False return - hint = " (check ADN_PANEL.TOKEN in the panel)" if status in (401, 403) else "" + if status in (401, 403): + hint = " (check ADN_PANEL.TOKEN in the panel)" + elif 300 <= status < 400: + hint = " (redirect not followed; check ADN_PANEL.ENDPOINT)" + else: + hint = "" self._fail(f"HTTP {status}{hint}") def error(self, exc: BaseException) -> None: diff --git a/tests/application/test_panel_report.py b/tests/application/test_panel_report.py index 541a625..6471ba0 100644 --- a/tests/application/test_panel_report.py +++ b/tests/application/test_panel_report.py @@ -29,6 +29,7 @@ from adn_server.application.report.panel_report import ( panel_report_settings, ) from adn_server.domain.errors import ConfigError +from adn_server.infrastructure.config_reload import merge_top_level_config from adn_server.infrastructure.config_validator import validate_config from tests.conftest import minimal_valid_config @@ -94,6 +95,7 @@ def test_report_has_ports_peers_and_links_but_no_secrets(): assert report["hbp_ports"] == [62031] assert report["odtp_port"] == 54006 assert report["obp_proxy_port"] == 62032 + assert report["peers"] == 1 assert report["plugins"] == ["voice-announcements"] assert report["obp_links"] == [ {"name": "OBP-2141", "network_id": 21410, "enhanced": False, "connected": None} @@ -137,3 +139,36 @@ def test_config_validation_of_the_section(): ) assert "ADN_PANEL.ENDPOINT" in str(exc.value) assert "ADN_PANEL.REPORT_INTERVAL" in str(exc.value) + + +def test_endpoint_must_be_https_except_on_localhost(): + for endpoint in ("http://panel.example/api", "ftp://panel.example", "https://"): + assert panel_report_settings(_config(ENDPOINT=endpoint, TOKEN="adn_x")) is None + assert panel_report_settings(_config(ENDPOINT="http://127.0.0.1:8000/api", TOKEN="adn_x")) + assert panel_report_settings(_config(ENDPOINT="http://localhost/api", TOKEN="adn_x")) + with pytest.raises(ConfigError) as exc: + validate_config( + minimal_valid_config(ADN_PANEL={"ENDPOINT": "http://panel.example/api", "TOKEN": "adn_x"}) + ) + assert "https://" in str(exc.value) + + +def test_masters_bound_to_loopback_are_not_reported(): + config = _config(ENDPOINT="https://panel.example/api", TOKEN="adn_x") + del config["PROXY"] + config["SYSTEMS"]["GATEWAY"] = {"MODE": "MASTER", "ENABLED": True, "IP": "127.0.0.1", "PORT": 54100} + report = build_panel_report( + config, version="2.6.1", uptime_s=0, settings=panel_report_settings(config), now=2000.0 + ) + assert report["hbp_ports"] == [54000] + + +def test_reload_follows_the_section_and_removing_it_stops_the_reports(): + config = _config(ENDPOINT="https://panel.example/api", TOKEN="adn_old", REPORT_INTERVAL=300) + + merge_top_level_config(config, {"ADN_PANEL": {"ENDPOINT": "https://panel.example/api", "TOKEN": "adn_new", "REPORT_INTERVAL": 120}}) + settings = panel_report_settings(config) + assert (settings.token, settings.interval) == ("adn_new", 120) + + merge_top_level_config(config, {}) + assert panel_report_settings(config) is None diff --git a/tests/infrastructure/test_panel_report_client.py b/tests/infrastructure/test_panel_report_client.py index 10777d2..ec84095 100644 --- a/tests/infrastructure/test_panel_report_client.py +++ b/tests/infrastructure/test_panel_report_client.py @@ -42,6 +42,11 @@ def panel(): class Handler(BaseHTTPRequestHandler): def do_POST(self): + if self.path == "/moved": + self.send_response(302) + self.send_header("Location", "/api/ingest/server-report") + self.end_headers() + return body = self.rfile.read(int(self.headers["Content-Length"])) received.append({"auth": self.headers["Authorization"], "body": json.loads(body)}) self.send_response(200 if self.headers["Authorization"] == "Bearer adn_ok" else 401) @@ -81,3 +86,10 @@ def test_failures_are_logged_once_and_the_recovery(caplog): "(ADN_PANEL) Could not send the report: HTTP 401 (check ADN_PANEL.TOKEN in the panel)", "(ADN_PANEL) Report sent again (HTTP 200)", ] + + +def test_redirect_is_a_failure_and_is_not_followed(panel): + url, received = panel + moved = url.replace("/api/ingest/server-report", "/moved") + assert send_panel_report(PanelReportSettings(moved, "adn_ok", 300, None), {}, "adn-server/test") == 302 + assert received == [] # the token never reached the redirect target