3c5cc831c0
* feat: configurable bind host for WebUI and langgraph dev (refs #400) WebUI mode was only reachable from the machine running it: the front-end got no bind interface, and `start_langgraph_dev(...)` was called without a host, so both servers stayed on loopback with no way to widen them. Adds two config fields with deliberately different defaults: webui_host = 0.0.0.0 front-end serves the app shell, no secrets langgraph_dev_host = 127.0.0.1 unauthenticated API, agent can run shell The design hinges on separating bind address from client address. Only bind() uses the configured interface; every consumer that *connects* (health probes, occupancy checks, async sub-agent self-dispatch) goes through the new `_probe_host`, which maps a wildcard bind back to loopback and honors a pinned interface verbatim. `_can_bind_port` is the one exception and binds the literal host, since it must replicate the bind the server itself will attempt. - manager.py: `_probe_host`, `_is_loopback_host`, `_format_hostport`; host kwarg threaded through the probes and `start_langgraph_dev`, which now emits `--host` and propagates EVOSCIENTIST_LANGGRAPH_DEV_HOST to the subprocess - sdk.py: `langgraph_dev_url` tracks host as well as port; EvoScientist.py reuses it instead of an inline f-string - server.py: `--host` flag mirroring `--port`, plus a red PUBLIC BIND banner whenever the bind is not provably loopback - webui.py: forwards both hosts; the front-end is widened via HOSTNAME because @evoscientist/webui ships no --host flag — its bin launcher does `HOSTNAME: process.env.HOSTNAME || "127.0.0.1"`. The warning is gated on the backend host only, so the shipped front-end default doesn't print a banner on every launch Verified end to end against a live server: requesting 0.0.0.0 yields a socket listening on 0.0.0.0 with the health probe correctly resolved to 127.0.0.1, while the default still binds 127.0.0.1 only. Note: webui_host defaulting to 0.0.0.0 is a behavior change — upgrading users will find the front-end reachable from the LAN. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat: default both bind hosts to 0.0.0.0, add --host and wizard host rendering (closes #400) Completes the remaining items from #400. - `langgraph_dev_host` now defaults to 0.0.0.0, matching `webui_host`. Remote WebUI use needs both anyway (the UI reaches the backend from the browser, not server-side), so a loopback backend default just meant every remote user hit a silently failing UI. `_DEFAULT_HOST` and sdk's `DEFAULT_LANGGRAPH_DEV_HOST` follow, so there is one story about where these servers listen. SECURITY: this exposes an unauthenticated API whose agent can run shell commands. The red PUBLIC BIND banner consequently fires on every launch while exposed — kept deliberately, since the exposure is real and the escape hatch (`--host 127.0.0.1` / `config set langgraph_dev_host`) is only discoverable if we say so. READMEs now lead with the warning and document the SSH-tunnel alternative. - `EvoSci --host <ip>` on the WebUI launch path, driving both servers. In WebUI mode they are two halves of one surface; moving only one leaves the UI loading but unable to reach the agent. Blank values are dropped rather than written as an empty override that would beat the config file. - Onboarding wizard no longer prints hard-coded `http://127.0.0.1:{port}` / `http://localhost:{port}` (steps.py:160, :223) — both render the configured bind through `_base_url` / `_format_hostport`, so a pinned interface is reported honestly and a wildcard still shows loopback. Verified against a live server: with no host argument at all, resolution through EvoScientistConfig yields a socket listening on 0.0.0.0, a client URL of http://127.0.0.1, and the warning gate returning True. Still open and tracked separately: the front-end takes its backend URL from browser input: `@evoscientist/webui` reads only HOSTNAME, PORT and EVOSCIENTIST_LANGGRAPH_DEV_PORT, so advertising a backend URL needs a change in that repo. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * ci: bump setup-uv v6 -> v9.0.0 to drop the deprecated node20 runtime GitHub now warns that setup-uv@v6 targets Node.js 20 and is being forced onto Node.js 24. v7.0.0 is the release that made that switch, so anything >= v7 clears the warning; v9.0.0 is current. Pinned to the full tag deliberately: setup-uv stopped publishing major and minor tags in v8.0.0 as supply-chain hardening, so `@v9` and `@v8` return 404 and would fail the job outright. Releases are immutable from v8 on, so the full tag is as tamper-proof as a SHA. Comment left in lint.yml because "simplifying" this back to `@v9` is an easy and CI-breaking mistake. actions/checkout@v5 is already node24 and needs no change. Note: v9.0.0 flips the `prune-cache` default to false (upstream did this to ease load on PyPI infrastructure). None of these workflows set it, so they follow the new default and Actions cache usage may grow. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(cli): correct --host help text and warn on public bind in non-WebUI modes The --host help claimed "WebUI mode only", which is wrong in a way that matters for security. `--host` writes `langgraph_dev_host` unconditionally, and `_ensure_async_subagent_server` auto-starts that backend for tui / cli / serve as well — the langgraph dev server is shared across UI modes. So the flag narrows or widens the agent API in every mode, and only `webui_host` is actually WebUI-specific. Reported against cli/commands.py. The documentation error hid a real gap: the PUBLIC BIND banner lived only in deploy/server.py and deploy/webui.py, so a plain `EvoSci` session bound 0.0.0.0 with no runtime signal whatsoever — and `--help` is opt-in, so fixing the text alone would not surface it. Added the same banner to the shared CLI path, gated on `is_async_subagents_available()`: ensure_langgraph_dev fails soft (async degrades to in-process delegation), and warning about a bind that never happened would be worse than staying quiet. READMEs (EN + zh-CN) get the same correction — the warning block sat inside the Desktop WebUI section and read as WebUI-scoped. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(deploy): strip the config-derived bind host, not just the CLI one `deploy()` only stripped the `--host` branch. When the flag was omitted, `getattr(config, "langgraph_dev_host", ...)` flowed unstripped into `_is_port_occupied`, `is_langgraph_dev_running`, `start_langgraph_dev` and the banner. `run_webui` already strips unconditionally; this aligns the two. Reachable because `deploy()` reads through `getattr` and is routinely handed duck-typed config objects (tests, embedders) that never run `EvoScientistConfig.__post_init__`, which is what normally normalizes these fields. Worst case was not just a bad bind: `_is_loopback_host(" 127.0.0.1 ")` is False, so a padded loopback value would print a false PUBLIC BIND warning while binding a string socket.bind() rejects outright — a security banner saying the opposite of the truth. Three regression tests added, each verified to fail against the old code. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * style: apply ruff format to the bind-host changes The Lint workflow runs both `ruff check` and `ruff format --check`; I had only been running the former locally, so five files landed unformatted and failed CI. Whitespace and line-wrapping only — no semantic change. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(security): keep the langgraph dev backend on loopback by default The backend is an unauthenticated API whose agent can run shell commands, and it is auto-started in every UI mode (tui/cli/webui/serve/deploy) — so a 0.0.0.0 default put it on the network for users who never asked. Restore 127.0.0.1 as the default and make 0.0.0.0 an explicit opt-in. webui_host keeps its 0.0.0.0 default: the front-end serves the app shell only and holds no credentials. run_webui already prints a remote-backend hint when the front-end is exposed and the backend is not. Help text and both READMEs are reframed around widening rather than narrowing; the escape-hatch tests are inverted to assert the public-bind opt-in survives into argv. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
272 lines
9.2 KiB
Python
272 lines
9.2 KiB
Python
"""Tests for ``run_webui`` bind-host wiring.
|
|
|
|
The front-end is an external npm package (``@evoscientist/webui``) with no
|
|
``--host`` flag: its bin launcher does
|
|
``HOSTNAME: process.env.HOSTNAME || "127.0.0.1"`` and hands that to the Next
|
|
standalone server. Setting ``HOSTNAME`` on the npx env is therefore the *only*
|
|
supported way to widen the front-end's interface — these tests pin that
|
|
contract so a refactor can't quietly drop it and silently re-narrow the bind.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import subprocess
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from EvoScientist.deploy import webui as webui_mod
|
|
|
|
|
|
def _make_config(
|
|
*,
|
|
default_workdir: str = "",
|
|
langgraph_dev_port: int = 6174,
|
|
langgraph_dev_host: str = "127.0.0.1",
|
|
webui_port: int = 4716,
|
|
webui_host: str = "0.0.0.0",
|
|
):
|
|
return SimpleNamespace(
|
|
default_workdir=default_workdir,
|
|
langgraph_dev_port=langgraph_dev_port,
|
|
langgraph_dev_host=langgraph_dev_host,
|
|
webui_port=webui_port,
|
|
webui_host=webui_host,
|
|
langgraph_dev_jobs_per_worker=10,
|
|
langgraph_dev_file_persistence=True,
|
|
)
|
|
|
|
|
|
class _RecordingConsole:
|
|
"""A real Rich console rendering to a buffer.
|
|
|
|
Rendering for real (rather than stringifying the arguments) matters here:
|
|
the remote-backend hint lives *inside* a ``Panel``, so a naive ``str(arg)``
|
|
would only ever see ``<rich.panel.Panel object at ...>`` and the assertion
|
|
would pass or fail for the wrong reason. Width is pinned wide so the
|
|
strings under test don't wrap mid-token.
|
|
"""
|
|
|
|
def __init__(self, sink: list):
|
|
import io
|
|
|
|
from rich.console import Console
|
|
|
|
self._sink = sink
|
|
self._buf = io.StringIO()
|
|
self._console = Console(file=self._buf, width=200, no_color=True)
|
|
|
|
def print(self, *args, **kwargs):
|
|
self._buf.seek(0)
|
|
self._buf.truncate()
|
|
self._console.print(*args, **kwargs)
|
|
self._sink.append(self._buf.getvalue())
|
|
|
|
def status(self, *args, **kwargs):
|
|
class _Ctx:
|
|
def __enter__(self_inner):
|
|
return self_inner
|
|
|
|
def __exit__(self_inner, *a):
|
|
return False
|
|
|
|
return _Ctx()
|
|
|
|
|
|
class _ImmediateEvent:
|
|
"""Exits ``run_webui``'s block loop after a single iteration."""
|
|
|
|
def __init__(self):
|
|
self._called = 0
|
|
|
|
def is_set(self) -> bool:
|
|
self._called += 1
|
|
return self._called > 1
|
|
|
|
def wait(self, timeout: float | None = None):
|
|
return None
|
|
|
|
def set(self):
|
|
self._called = 99
|
|
|
|
|
|
def _run_webui_once(monkeypatch, config, *, backend_port_occupied: bool = False):
|
|
"""Run ``run_webui`` with every external dependency mocked."""
|
|
import atexit
|
|
import os
|
|
import shutil
|
|
import signal
|
|
import threading
|
|
|
|
import EvoScientist.config as config_mod
|
|
from EvoScientist.langgraph_dev import manager as lgm
|
|
|
|
captured: dict[str, Any] = {"printed": [], "npx_env": {}, "npx_args": []}
|
|
|
|
monkeypatch.setattr(config_mod, "apply_config_to_env", lambda _cfg: None)
|
|
monkeypatch.setattr(webui_mod, "console", _RecordingConsole(captured["printed"]))
|
|
monkeypatch.setattr(os, "makedirs", lambda *a, **k: None)
|
|
monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/npx")
|
|
|
|
monkeypatch.setattr(
|
|
lgm, "_is_port_occupied", lambda _p, *_a, **_kw: backend_port_occupied
|
|
)
|
|
monkeypatch.setattr(lgm, "is_langgraph_dev_running", lambda **_kw: False)
|
|
monkeypatch.setattr(lgm, "_read_workspace_sidecar", lambda: None)
|
|
|
|
def _fake_start_langgraph_dev(workspace_dir=None, *, port=None, host=None, **_kw):
|
|
captured["backend_port"] = port
|
|
captured["backend_host"] = host
|
|
return SimpleNamespace(pid=99999)
|
|
|
|
monkeypatch.setattr(lgm, "start_langgraph_dev", _fake_start_langgraph_dev)
|
|
monkeypatch.setattr(lgm, "stop_langgraph_dev", lambda *_a, **_kw: None)
|
|
|
|
class _FakeProc:
|
|
pid = 12345
|
|
|
|
def poll(self):
|
|
return None
|
|
|
|
def wait(self, timeout=None):
|
|
return 0
|
|
|
|
def kill(self):
|
|
return None
|
|
|
|
def terminate(self):
|
|
return None
|
|
|
|
def _fake_popen(args, **kwargs):
|
|
captured["npx_args"] = args
|
|
captured["npx_env"] = kwargs.get("env", {})
|
|
return _FakeProc()
|
|
|
|
monkeypatch.setattr(subprocess, "Popen", _fake_popen)
|
|
# _stop_webui shells out to taskkill on Windows — neutralize it.
|
|
monkeypatch.setattr(webui_mod, "_stop_webui", lambda _proc: None)
|
|
monkeypatch.setattr(atexit, "register", lambda fn, *a, **k: fn)
|
|
monkeypatch.setattr(signal, "signal", lambda _sig, _handler: lambda *a: None)
|
|
monkeypatch.setattr(threading, "Event", _ImmediateEvent)
|
|
|
|
webui_mod.run_webui(config, workspace_dir="/tmp/ws")
|
|
return captured
|
|
|
|
|
|
# =============================================================================
|
|
# Front-end bind interface (HOSTNAME)
|
|
# =============================================================================
|
|
|
|
|
|
def test_hostname_env_carries_webui_host(monkeypatch):
|
|
config = _make_config(webui_host="0.0.0.0")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert captured["npx_env"].get("HOSTNAME") == "0.0.0.0", (
|
|
"HOSTNAME is the package's only bind knob — without it the front-end "
|
|
"falls back to its own 127.0.0.1 default"
|
|
)
|
|
|
|
|
|
def test_hostname_env_honors_loopback_opt_out(monkeypatch):
|
|
config = _make_config(webui_host="127.0.0.1")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert captured["npx_env"].get("HOSTNAME") == "127.0.0.1"
|
|
|
|
|
|
def test_port_env_and_flag_still_set(monkeypatch):
|
|
config = _make_config(webui_port=4800)
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert captured["npx_env"].get("PORT") == "4800"
|
|
assert "--port" in captured["npx_args"]
|
|
assert captured["npx_args"][captured["npx_args"].index("--port") + 1] == "4800"
|
|
|
|
|
|
def test_no_host_flag_passed_to_npx(monkeypatch):
|
|
"""The package's arg parser only knows ``--port``; a stray ``--host`` is at
|
|
best ignored and at worst breaks startup, so we must not emit one."""
|
|
config = _make_config()
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert "--host" not in captured["npx_args"]
|
|
|
|
|
|
@pytest.mark.parametrize("blank", ["", " "])
|
|
def test_blank_webui_host_falls_back_to_wildcard(monkeypatch, blank):
|
|
config = _make_config(webui_host=blank)
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert captured["npx_env"].get("HOSTNAME") == "0.0.0.0"
|
|
|
|
|
|
# =============================================================================
|
|
# Backend bind interface + security warning
|
|
# =============================================================================
|
|
|
|
|
|
def test_backend_host_reaches_start_langgraph_dev(monkeypatch):
|
|
config = _make_config(langgraph_dev_host="0.0.0.0")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert captured["backend_host"] == "0.0.0.0"
|
|
|
|
|
|
def test_backend_defaults_to_loopback(monkeypatch):
|
|
"""The backend is an unauthenticated API whose agent can run shell, so it
|
|
stays off the network unless ``langgraph_dev_host`` opts in."""
|
|
config = _make_config()
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert captured["backend_host"] == "127.0.0.1"
|
|
|
|
|
|
def test_public_bind_warning_when_backend_exposed(monkeypatch):
|
|
"""Users who widen the backend get told every time it is reachable
|
|
off-box — an unauthenticated, shell-capable API deserves a standing
|
|
reminder, not a one-time opt-in prompt."""
|
|
config = _make_config(langgraph_dev_host="0.0.0.0")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert any("PUBLIC BIND" in line for line in captured["printed"])
|
|
|
|
|
|
def test_no_public_bind_warning_when_backend_on_loopback(monkeypatch):
|
|
"""The warning must be silenceable, or it degrades into background noise
|
|
that users learn to skip past."""
|
|
config = _make_config(langgraph_dev_host="127.0.0.1")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert not any("PUBLIC BIND" in line for line in captured["printed"])
|
|
|
|
|
|
def test_webui_host_alone_does_not_trigger_warning(monkeypatch):
|
|
"""Only the backend earns a banner. The front-end serves the app shell and
|
|
holds no credentials, so warning on it would double the noise."""
|
|
config = _make_config(webui_host="0.0.0.0", langgraph_dev_host="127.0.0.1")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
assert not any("PUBLIC BIND" in line for line in captured["printed"])
|
|
|
|
|
|
def test_remote_backend_hint_when_frontend_exposed_but_backend_is_not(monkeypatch):
|
|
"""The UI talks to the backend from the browser, so a remote visitor
|
|
cannot reach a loopback backend — say so instead of letting every request
|
|
fail silently."""
|
|
config = _make_config(webui_host="0.0.0.0", langgraph_dev_host="127.0.0.1")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
banner = "\n".join(captured["printed"])
|
|
assert "Remote visitors cannot reach" in banner
|
|
assert "langgraph_dev_host" in banner
|
|
|
|
|
|
def test_no_remote_hint_when_both_exposed(monkeypatch):
|
|
config = _make_config(webui_host="0.0.0.0", langgraph_dev_host="0.0.0.0")
|
|
captured = _run_webui_once(monkeypatch, config)
|
|
|
|
banner = "\n".join(captured["printed"])
|
|
assert "Remote visitors cannot reach" not in banner
|