Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(serve): say what --tool-auth-token covers when the server binds beyond loopback (#1689)

Alpamys Makazhanc900a1b435c5
diff --git a/changelog.d/0.75.1/1689.changed.md b/changelog.d/0.75.1/1689.changed.md
new file mode 100644
index 00000000..9831823c
--- /dev/null
+++ b/changelog.d/0.75.1/1689.changed.md
@@ -0,0 +1,9 @@
+- `soup serve` says what `--tool-auth-token` covers when it binds beyond loopback. A
+ non-loopback `--host` is refused without the token, which reads as if the token put the
+ whole server behind a credential; it is checked on the tool, thumbs and adapter routes
+ only, the generation routes take none, the vLLM / SGLang / MII backends have no route
+ that checks it, and on a wildcard bind (`0.0.0.0`, `::`) the `Host` header is not
+ compared. None of that changes. The command now prints it as a `Note:` at startup on
+ such a bind, the `--host` help says that the token is required there (it said "should be
+ paired with") and what it is checked on, and `docs/serving-and-export.md` has a paragraph
+ on what the token does not cover (#1689).
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index d09e0276..2158a053 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -896,3 +896,14 @@ generation on their server or enumerate the loaded adapters — CORS alone would
that page *reading* the reply, not sending the request. Requests that carry no `Origin` at
all — curl, the OpenAI/Anthropic SDKs, a reverse proxy — are unaffected, and `Host` is not
checked on these routes, so a proxy can still front them under its own hostname.
+
+**What `--tool-auth-token` does not cover.** `soup serve` refuses a non-loopback `--host`
+without `--tool-auth-token`, but the token is checked on the tool routes, `/v1/thumbs` and
+the adapter routes only. `/v1/chat/completions`, `/v1/messages`, `/v1/models`, `/health` and
+`/metrics` take no token on any bind, so they answer every client that can reach the port;
+put a proxy that authenticates in front of the server if that is not intended. With
+`--backend vllm`, `sglang` or `mii` there are no tool or adapter routes, so no route checks
+the token. On a wildcard bind (`0.0.0.0`, `::`) there is no single name to compare `Host`
+against, so the routes that otherwise compare it check only that an `Origin` header, when
+sent, names the same host as `Host`. `soup serve` prints these points at startup whenever
+it binds beyond loopback.
diff --git a/src/soup_cli/commands/serve.py b/src/soup_cli/commands/serve.py
index 2392c9af..a2a1185d 100644
--- a/src/soup_cli/commands/serve.py
+++ b/src/soup_cli/commands/serve.py
@@ -92,9 +92,9 @@ def serve(
"127.0.0.1",
"--host",
help=(
- "Host to bind to. Defaults to loopback (127.0.0.1); the server "
- "exposes an unauthenticated code-exec tool endpoint, so binding a "
- "public interface (0.0.0.0) should be paired with --tool-auth-token."
+ "Host to bind to. Defaults to loopback (127.0.0.1). Any other host "
+ "needs --tool-auth-token, which is checked on the tool, thumbs and "
+ "adapter routes only: the generation routes take no token."
),
),
device: Optional[str] = typer.Option(
@@ -329,6 +329,9 @@ def serve(
"tool endpoints (/v1/tools/bash, /v1/tools/python)."
)
raise typer.Exit(code=2)
+ # The token that check asks for does not cover every route: say which.
+ for _notice in _non_loopback_notices(host, backend):
+ console.print(f"[yellow]Note:[/] {_notice}")
# v0.71.12 #221 — validate `--bank` up front (path containment + backend)
# so a typo / bad path surfaces before backend init.
if bank is not None:
@@ -1239,6 +1242,54 @@ def _load_serve_tokenizer(
# Backends whose FastAPI app actually serves /metrics (#333). ``--dashboard``
# on anything else used to no-op in silence.
_METRICS_BACKENDS = frozenset({"transformers", "vllm"})
+# The binds `soup serve` accepts without --tool-auth-token (the same three
+# spellings the refusal in serve() and _check_tool_auth compare against).
+_LOOPBACK_BINDS = frozenset({"127.0.0.1", "localhost", "::1"})
+
+
+def _non_loopback_notices(host: str, backend: str) -> list[str]:
+ """What an operator binding beyond loopback should know about the token.
+
+ Empty for a loopback bind. The lines describe the server as it is: a
+ non-loopback bind is refused without ``--tool-auth-token``, which reads as
+ if the token covered every route, and it does not.
+
+ * transformers: the token is checked on the tool, thumbs and adapter
+ routes only. On a wildcard bind those routes cannot compare ``Host``
+ with a bound name either, which is the second line.
+ * vLLM / SGLang / MII: their apps have no such routes and are never handed
+ the token, so no route checks it.
+
+ The host is user input printed before anything validates it, so it goes
+ through ``for_terminal``.
+ """
+ if host in _LOOPBACK_BINDS:
+ return []
+ from soup_cli.utils.local_request_guard import is_wildcard_bind
+
+ where = f"bound to '{for_terminal(host)}', not loopback"
+ backend_name = backend.lower()
+ if backend_name != "transformers":
+ return [
+ f"{where}, and the {for_terminal(backend_name)} backend has no tool or "
+ "adapter routes, so no route checks --tool-auth-token: every route "
+ "(generation included) will answer every client that can reach this port "
+ "without a token. Put a proxy that authenticates in front if that is not "
+ "intended."
+ ]
+ notices = [
+ f"{where}. --tool-auth-token is checked on the tool, thumbs and adapter routes "
+ "only: /v1/chat/completions, /v1/messages, /v1/models, /health and /metrics "
+ "answer every client that can reach this port without a token. Put a proxy "
+ "that authenticates in front if that is not intended."
+ ]
+ if is_wildcard_bind(host):
+ notices.append(
+ "a wildcard bind has no single name, so the Host header is not compared: "
+ "the tool, thumbs and adapter routes check only that an Origin header, "
+ "when sent, names the same host as Host."
+ )
+ return notices
def _dashboard_warning(backend: str) -> Optional[str]:
diff --git a/src/soup_cli/utils/local_request_guard.py b/src/soup_cli/utils/local_request_guard.py
index 4fab562f..bb21ba53 100644
--- a/src/soup_cli/utils/local_request_guard.py
+++ b/src/soup_cli/utils/local_request_guard.py
@@ -66,6 +66,15 @@ def _normalise_bind(bind_host: str) -> str:
return bind
+def is_wildcard_bind(bind_host: str) -> bool:
+ """True when ``bind_host`` names every interface rather than one address.
+
+ For such a bind there is no single name to compare ``Host`` against, which
+ is why :func:`check_local_request` falls back to ``Origin`` alone.
+ """
+ return _normalise_bind(bind_host) in WILDCARD_HOSTS
+
+
def _allowed_hostnames(bind: str) -> frozenset[str]:
"""The hostnames that name an already-normalised, non-wildcard bind."""
return LOOPBACK_HOSTNAMES if bind in LOOPBACK_HOSTNAMES else frozenset({bind})
diff --git a/tests/test_serve_non_loopback_notice.py b/tests/test_serve_non_loopback_notice.py
new file mode 100644
index 00000000..a4e21d1f
--- /dev/null
+++ b/tests/test_serve_non_loopback_notice.py
@@ -0,0 +1,190 @@
+"""``soup serve`` says what ``--tool-auth-token`` covers when it binds beyond loopback.
+
+A non-loopback ``--host`` is refused without ``--tool-auth-token``, which
+reads as if the token put the whole server behind a credential. It does not:
+
+* on the transformers backend the token is checked on the tool, thumbs and
+ adapter routes only; the generation routes take none;
+* the vLLM, SGLang and MII apps have no such routes and are never handed the
+ token, so no route checks it there;
+* on a wildcard bind there is no single name to compare ``Host`` against, so
+ the routes that do compare it check only ``Origin`` against ``Host``.
+
+None of that changes here. The command now prints it at startup, and the
+``--host`` help says that the token is required and what it is checked on.
+"""
+
+from __future__ import annotations
+
+from io import StringIO
+
+import pytest
+from rich.console import Console
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.commands import serve as serve_cmd
+from soup_cli.utils.local_request_guard import WILDCARD_HOSTS, is_wildcard_bind
+from tests.conftest import strip_ansi
+
+runner = CliRunner()
+
+LOOPBACK = ["127.0.0.1", "localhost", "::1"]
+# One named interface: a LAN address, a hostname, an IPv6 literal.
+NAMED = ["192.168.1.20", "10.0.0.5", "gpu-box.internal", "fe80::1", "[fe80::1]"]
+# Every spelling the request guard treats as "all interfaces".
+WILDCARD = ["0.0.0.0", "::", "[::]", "*", ""]
+OTHER_BACKENDS = ["vllm", "sglang", "mii"]
+
+TOKEN_SCOPE = "--tool-auth-token is checked on the tool, thumbs and adapter routes only"
+OPEN_ROUTES = "answer every client that can reach this port without a token"
+NO_HOST_CHECK = "the Host header is not compared"
+
+
+def _plain(text: str) -> str:
+ """ANSI-stripped, whitespace-collapsed CLI output, safe to substring-match."""
+ return " ".join(strip_ansi(text).split())
+
+
+def _rendered(notices: list[str]) -> str:
+ """The notices as the command prints them, markup applied, on a wide console."""
+ buffer = StringIO()
+ console = Console(file=buffer, width=400, color_system=None)
+ for notice in notices:
+ console.print(f"[yellow]Note:[/] {notice}")
+ return " ".join(buffer.getvalue().split())
+
+
+class TestWildcardSpellings:
+ def test_the_test_list_is_the_guards_own_set(self):
+ # If the guard learns a new spelling, the cases below must cover it.
+ assert set(WILDCARD) == set(WILDCARD_HOSTS)
+
+ @pytest.mark.parametrize("host", WILDCARD + [" 0.0.0.0 ", "[::]"])
+ def test_wildcard_binds_are_recognised(self, host):
+ assert is_wildcard_bind(host) is True
+
+ @pytest.mark.parametrize("host", LOOPBACK + NAMED)
+ def test_a_single_address_is_not_a_wildcard(self, host):
+ assert is_wildcard_bind(host) is False
+
+
+class TestNotices:
+ @pytest.mark.parametrize("backend", ["transformers", *OTHER_BACKENDS])
+ @pytest.mark.parametrize("host", LOOPBACK)
+ def test_a_loopback_bind_gets_no_notice(self, host, backend):
+ assert serve_cmd._non_loopback_notices(host, backend) == []
+
+ @pytest.mark.parametrize("host", NAMED)
+ def test_a_named_interface_gets_the_token_scope_only(self, host):
+ notices = serve_cmd._non_loopback_notices(host, "transformers")
+
+ assert len(notices) == 1
+ out = _rendered(notices)
+ assert f"bound to '{host}', not loopback" in out
+ assert TOKEN_SCOPE in out
+ assert "/v1/chat/completions, /v1/messages" in out
+ assert OPEN_ROUTES in out
+ assert NO_HOST_CHECK not in out
+
+ @pytest.mark.parametrize("host", WILDCARD)
+ def test_a_wildcard_bind_also_says_host_is_not_compared(self, host):
+ notices = serve_cmd._non_loopback_notices(host, "transformers")
+
+ assert len(notices) == 2
+ out = _rendered(notices)
+ assert TOKEN_SCOPE in out
+ assert OPEN_ROUTES in out
+ assert NO_HOST_CHECK in out
+ assert "check only that an Origin header, when sent, names the same host as Host" in out
+
+ @pytest.mark.parametrize("backend", OTHER_BACKENDS + ["VLLM", "SGLang"])
+ @pytest.mark.parametrize("host", ["192.168.1.20", "0.0.0.0"])
+ def test_other_backends_are_told_that_no_route_checks_the_token(self, host, backend):
+ notices = serve_cmd._non_loopback_notices(host, backend)
+
+ # One notice even on a wildcard bind: these apps compare Host nowhere,
+ # so there is no Host rule to describe.
+ assert len(notices) == 1
+ out = _rendered(notices)
+ assert f"the {backend.lower()} backend has no tool or adapter routes" in out
+ assert "no route checks --tool-auth-token" in out
+ assert OPEN_ROUTES in out
+ assert TOKEN_SCOPE not in out
+
+ @pytest.mark.parametrize(
+ "host",
+ ["[bold]lan[/bold]", "[/]", "[red]x", "lan\x1b[31mred", "lan\x9b31m"],
+ ids=["tag-pair", "bare-close", "unclosed", "esc-csi", "c1-csi"],
+ )
+ def test_the_host_is_shown_literally(self, host):
+ out = _rendered(serve_cmd._non_loopback_notices(host, "transformers"))
+
+ assert "\x1b" not in out
+ assert "\x9b" not in out
+ visible = host.replace("\x1b", "").replace("\x9b", "")
+ assert f"bound to '{visible}', not loopback" in out
+
+
+class TestTheCommandPrintsThem:
+ def _serve(self, *args: str):
+ # The model path does not exist, so the command stops long before a
+ # server starts; the notices are printed before that.
+ return runner.invoke(app, ["serve", "--model", "no-such-model-dir", *args])
+
+ @pytest.mark.parametrize("host", ["0.0.0.0", "192.168.1.20"])
+ def test_a_non_loopback_bind_with_a_token_prints_the_scope(self, host, monkeypatch):
+ monkeypatch.setenv("COLUMNS", "400")
+
+ result = self._serve("--host", host, "--tool-auth-token", "s3cret-token-value")
+
+ out = _plain(result.output)
+ assert f"Note: bound to '{host}', not loopback" in out
+ assert TOKEN_SCOPE in out
+ assert (NO_HOST_CHECK in out) is (host == "0.0.0.0")
+ assert "s3cret-token-value" not in out
+
+ def test_the_backend_option_reaches_the_notice(self, monkeypatch):
+ monkeypatch.setenv("COLUMNS", "400")
+
+ result = self._serve(
+ "--host", "0.0.0.0", "--tool-auth-token", "s3cret-token-value", "--backend", "sglang"
+ )
+
+ out = _plain(result.output)
+ assert "the sglang backend has no tool or adapter routes" in out
+ assert TOKEN_SCOPE not in out
+
+ def test_a_loopback_bind_prints_no_notice(self, monkeypatch):
+ monkeypatch.setenv("COLUMNS", "400")
+
+ result = self._serve("--tool-auth-token", "s3cret-token-value")
+
+ out = _plain(result.output)
+ assert "not loopback" not in out
+ assert TOKEN_SCOPE not in out
+
+ def test_without_a_token_the_bind_is_still_refused_first(self, monkeypatch):
+ # Unchanged behaviour: exit 2 and the existing message, no notice.
+ monkeypatch.setenv("COLUMNS", "400")
+
+ result = self._serve("--host", "0.0.0.0")
+
+ assert result.exit_code == 2, (result.output, repr(result.exception))
+ out = _plain(result.output)
+ assert "binding non-loopback host '0.0.0.0' requires --tool-auth-token <secret>" in out
+ assert "Note: bound to" not in out
+
+
+class TestHostHelp:
+ def test_help_says_the_token_is_required_and_what_it_is_checked_on(self, monkeypatch):
+ monkeypatch.setenv("COLUMNS", "200")
+
+ result = runner.invoke(app, ["serve", "--help"])
+
+ assert result.exit_code == 0, (result.output, repr(result.exception))
+ # The help table wraps a long description; drop its borders before joining.
+ out = _plain(result.output.replace("│", " "))
+ assert "Any other host needs --tool-auth-token" in out
+ assert "checked on the tool, thumbs and adapter routes only" in out
+ assert "should be paired with" not in out