Skip to content

The agent that grows with you

fix(webapp): Web Access shows and saves only a public URL the gateway serves

emozilla7e064a62ce0a
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index 87420a8a672..c064038a0f6 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -21,7 +21,7 @@ import os
import re
import secrets
import sys
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
from urllib.parse import urlsplit
@@ -75,13 +75,16 @@ def _config_document(home: Path) -> dict:
def webapp_settings(home) -> WebappSettings:
"""``webapp:`` from *home*'s config. A missing, unreadable or malformed block reads as off, so a
- typo never exposes the listener; a block that cannot be used carries the reason in ``reason``."""
+ typo never exposes the listener; a block that cannot be used carries the reason in ``reason``.
+ A present block's valid ``host``, ``port`` and ``public_url`` are read whether or not it turns
+ the Webapp on (an invalid one reads as the default), so Web Access shows and registers the
+ address the gateway will bind."""
path = Path(home) / "config.yaml"
from ruamel.yaml.error import YAMLError
- def off(reason: str) -> WebappSettings:
+ def off(reason: str, configured: WebappSettings = WebappSettings()) -> WebappSettings:
logger.warning("Webapp stays off: %s", reason)
- return WebappSettings(reason=reason)
+ return replace(configured, reason=reason)
try:
document = _config_document(Path(home))
@@ -92,23 +95,33 @@ def webapp_settings(home) -> WebappSettings:
return WebappSettings()
if not isinstance(block, dict):
return off(f"webapp in {path} must be a mapping")
+ host, port, public_url = _configured_address(block)
+ configured = WebappSettings(host=host or DEFAULT_HOST, port=port or DEFAULT_PORT, public_url=public_url or "")
enabled = block.get("enabled", False)
if enabled is False:
- return WebappSettings()
+ return configured
if enabled is not True:
- return off(f"webapp.enabled must be true or false in {path}")
- host = block.get("host", DEFAULT_HOST)
- port = block.get("port", DEFAULT_PORT)
- host = _canonical_host(_bare_host(host)) if isinstance(host, str) else None
- if host is None or not (_local_only(host) or _is_wildcard(host)):
- return off(f"webapp.host must be 127.0.0.1, ::1, localhost, 0.0.0.0 or :: in {path}")
- if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
- return off(f"webapp.port must be a port number (1-65535) in {path}")
- public_url = _public_url(block.get("public_url"))
+ return off(f"webapp.enabled must be true or false in {path}", configured)
+ if host is None:
+ return off(f"webapp.host must be 127.0.0.1, ::1, localhost, 0.0.0.0 or :: in {path}", configured)
+ if port is None:
+ return off(f"webapp.port must be a port number (1-65535) in {path}", configured)
if public_url is None:
return off(f"webapp.public_url must be an http:// or https:// address with no credentials, "
- f"query or fragment in {path}")
- return WebappSettings(enabled=True, host=host, port=port, public_url=public_url)
+ f"query or fragment in {path}", configured)
+ return replace(configured, enabled=True)
+
+
+def _configured_address(block: dict) -> tuple[str | None, int | None, str | None]:
+ """The block's ``(host, port, public_url)``, each None when invalid (``public_url`` is "" when
+ unset): the host canonical and local-only or a wildcard, the port 1-65535, the URL as
+ :func:`_public_url` reads it."""
+ host = block.get("host", DEFAULT_HOST)
+ host = _canonical_host(_bare_host(host)) if isinstance(host, str) else None
+ port = block.get("port", DEFAULT_PORT)
+ valid_port = isinstance(port, int) and not isinstance(port, bool) and 1 <= port <= 65535
+ return (host if host is not None and (_local_only(host) or _is_wildcard(host)) else None,
+ port if valid_port else None, _public_url(block.get("public_url")))
def _bare_host(host: str) -> str:
diff --git a/hermes_cli/webapp_access.py b/hermes_cli/webapp_access.py
index ccd0f5703ba..b475f832d06 100644
--- a/hermes_cli/webapp_access.py
+++ b/hermes_cli/webapp_access.py
@@ -26,8 +26,6 @@ from pathlib import Path
from typing import Optional
from urllib.parse import urlsplit
-from gateway.webapp_listener import DEFAULT_PORT
-
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})
# Web Access's portal client: its id, the Portal it lives on and the callback last registered on it.
_REGISTRATION_PATH = Path("webapp") / "sign-in-registration.json"
@@ -50,14 +48,19 @@ def lan_address() -> Optional[str]:
def _public_url(raw: Optional[str]) -> str:
- """``https://host[:port][/prefix]`` without a trailing slash, or WebappAccessError."""
- value = (raw or "").strip().rstrip("/")
- parsed = urlsplit(value)
- if parsed.scheme != "https" or not parsed.hostname or parsed.hostname in _LOOPBACK_HOSTS:
- raise WebappAccessError("The public URL must be an https:// address other devices use.")
- if parsed.query or parsed.fragment or parsed.username or parsed.password:
+ """``https://host[:port][/prefix]`` without a trailing slash, or WebappAccessError: a
+ ``webapp.public_url`` the gateway reads (``gateway.webapp_listener._public_url``) that is also an
+ https address other devices reach."""
+ from gateway.webapp_listener import _public_url as read_public_url
+
+ value = (raw or "").strip()
+ url = read_public_url(value)
+ if url is None and any(c in value for c in "?#@"):
raise WebappAccessError("The public URL cannot carry credentials, a query or a fragment.")
- return value
+ parsed = urlsplit(url or "")
+ if parsed.scheme != "https" or parsed.hostname in _LOOPBACK_HOSTS:
+ raise WebappAccessError("The public URL must be an https:// address other devices use.")
+ return url
def gateway_home() -> Path:
@@ -153,11 +156,13 @@ def plan(mode: str, public_url: Optional[str] = None) -> tuple[str, str, str]:
"""Check that *mode* can be served and signed in to; returns ``(host, public_url, callback)``:
the bind host and the URL to pin for :func:`serve`, and the sign-in callback for
:func:`register`. Changes nothing, so Start runs it before any slow or lasting step."""
+ from gateway.webapp_listener import webapp_settings
+
if mode == "lan":
address = lan_address()
if address is None:
raise WebappAccessError("This machine has no network address other devices can reach.")
- host, url, pinned = "0.0.0.0", f"http://{address}:{_configured_port(gateway_home())}", ""
+ host, url, pinned = "0.0.0.0", f"http://{address}:{webapp_settings(gateway_home()).port}", ""
elif mode == "public":
host, url = "127.0.0.1", _public_url(public_url)
pinned = url
@@ -216,35 +221,6 @@ def _write_config(*, enabled: bool, host: str = "", public_url: str = "") -> Non
save_config(cfg)
-def _configured_block(home: Path) -> dict:
- """The ``webapp:`` block of *home*'s config, or ``{}`` (``webapp_settings`` reports an unreadable
- config)."""
- from ruamel.yaml.error import YAMLError
-
- from gateway.webapp_listener import _config_document
-
- try:
- document = _config_document(home)
- except (OSError, ValueError, YAMLError):
- return {}
- block = document.get("webapp") if isinstance(document, dict) else None
- return block if isinstance(block, dict) else {}
-
-
-def _configured_public_url(home: Path) -> str:
- """``webapp.public_url`` from *home*'s config, or ``""``."""
- value = _configured_block(home).get("public_url")
- return value.strip().rstrip("/") if isinstance(value, str) else ""
-
-
-def _configured_port(home: Path) -> int:
- """``webapp.port`` from *home*'s config, whether or not the Webapp is on (the default when unset
- or invalid): the address Web Access shows and registers is the one the gateway will bind."""
- port = _configured_block(home).get("port", DEFAULT_PORT)
- valid = isinstance(port, int) and not isinstance(port, bool) and 1 <= port <= 65535
- return port if valid else DEFAULT_PORT
-
-
def _gateway_state(home: Path) -> dict:
"""What *home*'s gateway serves now (``serving``, ``off``, ``unavailable`` with a ``reason``, or
``stopped`` when none answers). It reads the config at start, so it can lag until a restart."""
@@ -259,7 +235,7 @@ def _gateway_state(home: Path) -> dict:
return dict(response["result"])
-def _mode(settings, public_url: str) -> Optional[str]:
+def _mode(settings) -> Optional[str]:
"""Who the configured Webapp serves: ``public`` (its own URL pins the callback and Host),
``lan`` (a wildcard bind), ``local`` (a loopback bind, as ``hermes webapp`` sets it up), or None
when it is off."""
@@ -267,24 +243,25 @@ def _mode(settings, public_url: str) -> Optional[str]:
if not settings.enabled:
return None
- if public_url:
+ if settings.public_url:
return "public"
return "lan" if _is_wildcard(settings.host) else "local"
def access_status() -> dict:
- """Everything the Web Access pane shows, read for the gateway home in scope."""
+ """Everything the Web Access pane shows, read for the gateway home in scope. The ``webapp:``
+ block is read once, by the gateway's own reader, so the pane shows the address and port the
+ gateway will serve, and no public URL it would refuse."""
from gateway.webapp_listener import webapp_settings
home = gateway_home()
settings = webapp_settings(home)
- public_url = _configured_public_url(home)
return {
"enabled": settings.enabled,
- "mode": _mode(settings, public_url),
- "port": _configured_port(home),
+ "mode": _mode(settings),
+ "port": settings.port,
"gateway": _gateway_state(home),
"lan_address": lan_address(),
- "public_url": public_url,
+ "public_url": settings.public_url,
"nous_signed_in": nous_signed_in(),
}
diff --git a/tests/gateway/test_webapp_settings.py b/tests/gateway/test_webapp_settings.py
index f17d1c831de..44a77eb2c16 100644
--- a/tests/gateway/test_webapp_settings.py
+++ b/tests/gateway/test_webapp_settings.py
@@ -43,6 +43,22 @@ def test_a_webapp_block_that_is_off_or_valid_has_no_reason(tmp_path, block):
assert webapp.webapp_settings(_home(tmp_path, block)).reason is None
+def test_a_webapp_block_that_is_off_still_reads_its_address(tmp_path):
+ """Web Access shows and registers the address the gateway will bind, so a block that is off, or
+ asks for the Webapp but cannot be used, still reads its valid host, port and public URL (an
+ invalid one reads as the default). The listener stays main's private one either way."""
+ off = webapp.webapp_settings(_home(tmp_path / "off", (
+ "webapp:\n enabled: false\n host: 0.0.0.0\n port: 9333\n public_url: https://webapp.example.net/\n")))
+ assert (off.enabled, off.host, off.port, off.public_url, off.reason) == (
+ False, "0.0.0.0", 9333, "https://webapp.example.net", None)
+ assert off.bind == ("127.0.0.1", 0)
+ unusable = webapp.webapp_settings(_home(tmp_path / "unusable", (
+ "webapp:\n enabled: true\n host: 192.168.1.20\n port: 9333\n public_url: https://u:[email protected]\n")))
+ assert (unusable.enabled, unusable.host, unusable.port, unusable.public_url) == (False, "127.0.0.1", 9333, "")
+ assert unusable.bind == ("127.0.0.1", 0)
+ assert "webapp.host" in unusable.reason
+
+
@pytest.mark.parametrize(("host", "bind_host"), [("'[::1]'", "::1"), ("'[::]'", "::"), ("' ::1 '", "::1")])
def test_a_bracketed_ipv6_host_is_read_as_the_address(tmp_path, host, bind_host):
# Brackets belong to URLs; the bind address and the address native clients dial carry none.
diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.py
index fe0fde2604f..fe862482514 100644
--- a/tests/hermes_cli/test_webapp_access.py
+++ b/tests/hermes_cli/test_webapp_access.py
@@ -160,6 +160,50 @@ def test_start_keeps_a_custom_port_and_builds_the_addresses_on_it(client, restar
assert response.json()["port"] == 9333
[email protected]("enabled", [True, False])
[email protected]("public_url", [
+ "https://user:[email protected]",
+ "https://hermes.example.test/?next=x",
+ "https://hermes.example.test:99999",
+ "hermes.example.test",
+])
+def test_status_never_shows_a_public_url_the_gateway_refuses(client, public_url, enabled):
+ """The pane shows the ``webapp:`` block as the gateway reads it, with the gateway's own reader: a
+ ``webapp.public_url`` the gateway refuses shows as none, whether the Webapp is on or off, and
+ the port the user chose still shows."""
+ from hermes_cli.config import save_config
+
+ save_config({**_config(), "webapp": {"enabled": enabled, "port": 9333, "public_url": public_url}})
+
+ status = client.get("/api/webapp-access/status").json()
+ assert (status["enabled"], status["mode"], status["public_url"], status["port"]) == (False, None, "", 9333)
+
+
[email protected]("public_url", [
+ "https://hermes.example.test:99999",
+ "https://hermes.example.test:0",
+ "https://hermes.example.test/a@b",
+ "https://hermes.example.test/a b",
+])
+def test_start_refuses_a_public_url_the_gateway_would_refuse(client, restarts, nous, public_url):
+ """Start checks the URL with the gateway's own ``webapp.public_url`` reader (plus https on a host
+ other devices reach), so it never registers, saves and restarts onto a Webapp the gateway then
+ keeps off."""
+ response = client.post("/api/webapp-access/start", json={"mode": "public", "public_url": public_url})
+ assert response.status_code == 400, response.text
+ assert nous == []
+ assert restarts == []
+ assert not _config().get("webapp", {}).get("enabled")
+
+
+def test_start_takes_the_public_url_as_typed(client, restarts, nous):
+ """Spaces around the URL and a trailing slash are not part of the address."""
+ response = client.post("/api/webapp-access/start", json={"mode": "public", "public_url": " https://hermes.example.test/ "})
+ assert response.status_code == 200, response.text
+ assert nous == ["https://hermes.example.test/auth/callback"]
+ assert _config()["webapp"]["public_url"] == "https://hermes.example.test"
+
+
@pytest.fixture()
def lan_browser(monkeypatch):
"""This listener on all interfaces behind password sign-in, and a browser on the LAN signed in