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(ui): validate loopback hosts and IPv6 controls (#1839)

vaputac98c1d9868b9
diff --git a/changelog.d/0.76.0/1839.fixed.md b/changelog.d/0.76.0/1839.fixed.md
new file mode 100644
index 00000000..8155ef19
--- /dev/null
+++ b/changelog.d/0.76.0/1839.fixed.md
@@ -0,0 +1 @@
+- **`soup ui` validates the served Host names on a loopback bind.** Requests must name the bound host or `localhost` / `127.0.0.1` / `[::1]` with the bound port; an omitted port means HTTP port 80. Foreign names, wrong ports and missing, malformed or duplicate headers get `403 {"detail": "Host not allowed"}` before authentication, body reads or routes, with the normal security response headers. This closes the Host/Origin hardening gap in the session-cookie check. `--public` keeps its Bearer gate, and the startup login URL is unchanged (#1829 in #1839).
diff --git a/docs/commands.md b/docs/commands.md
index 21f797b0..1d7459c6 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -258,7 +258,7 @@ soup reward stress ... --output-report r.json Save the per-attack report JSON (
soup tui Full-screen Textual dashboard (requires [tui] extra)
soup train --config soup.yaml --profile Record torch.profiler trace to <output>/profiles/
soup --log-level quiet|normal|verbose|debug Global logging tier (Rich-formatted)
-soup ui [--port 7860] Web UI (experiments, training, data)
+soup ui [--port 7860] Web UI (experiments, training, data); loopback Host must name the bound host or localhost / 127.0.0.1 / [::1] with the bound port (omitted = HTTP 80), otherwise 403
soup ui --public [--auth-token T] Phone-scannable Web UI (v0.53.9); /docs + /openapi.json are loopback-only
soup tokenizer train --input c.jsonl --vocab-size N Train BPE tokenizer (v0.53.9)
soup bench <model> Inference speed + memory (same as `soup bench infer <model>`)
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index f921e7d1..75fd075d 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -732,6 +732,16 @@ bypass the limit.
**Interactive API docs are loopback-only.** `/openapi.json`, `/docs`, `/docs/oauth2-redirect` and `/redoc` serve on a loopback bind and are **absent** (404) on any other, including `soup ui --public`. This is deliberate rather than incidental: the schema exposes no run data, configuration or logs, but it does describe every route, parameter and request/response shape, and on a LAN bind that is free reconnaissance. Gating them behind the token instead was rejected — `/docs` is a browser navigation and Swagger cannot attach a Bearer header to it, so gating would break the page for a developer while leaving `/openapi.json` readable by any HTTP client. If you need the schema while bound publicly, read it from a loopback instance of the same version.
+**Host names on a loopback bind (#1829).** Use the bound host or `localhost`,
+`127.0.0.1` or `[::1]`, with the bound port. An omitted port means HTTP port 80;
+on any other port it must be included. Any other name or port gets
+`403 {"detail": "Host not allowed"}` before authentication, body reads or routes.
+This includes a proxy that rewrites `Host`, an SSH tunnel whose local port differs
+from the server's, or a custom DNS name. Missing, malformed or duplicate `Host`
+headers are also refused. These refusals carry the same security headers as other
+UI responses, including on the interactive docs paths. `--public` and other
+non-loopback binds keep the Bearer gate and do not apply this Host allow-list.
+
```bash
# Custom port, don't auto-open browser
soup ui --port 8080 --no-browser
diff --git a/src/soup_cli/ui/app.py b/src/soup_cli/ui/app.py
index ae438441..182ad5de 100644
--- a/src/soup_cli/ui/app.py
+++ b/src/soup_cli/ui/app.py
@@ -167,14 +167,15 @@ class _SecurityHeadersMiddleware:
return
exempt = scope.get("path") in self._policy_exempt_paths
- extra = tuple(
- (name, value)
- for name, value in self._headers
- if not (exempt and name == b"content-security-policy")
- )
async def send_with_headers(message) -> None:
if message.get("type") == "http.response.start":
+ exempt_policy = exempt and message.get("status") == 200
+ extra = tuple(
+ (name, value)
+ for name, value in self._headers
+ if not (exempt_policy and name == b"content-security-policy")
+ )
existing = list(message.get("headers", ()))
present = {name.lower() for name, _ in existing}
added = [(n, v) for n, v in extra if n not in present]
@@ -184,6 +185,76 @@ class _SecurityHeadersMiddleware:
await self._app(scope, receive, send_with_headers)
+def _host_key(host: str) -> str:
+ """Normalize IP literals and case-insensitive hostnames for comparison."""
+ try:
+ return str(ipaddress.ip_address(host))
+ except ValueError:
+ return host.lower()
+
+
+def _host_header_allowed(value: str, allowed_hosts: frozenset[tuple[str, int]]) -> bool:
+ """Match a single HTTP Host header against the served host and port pairs."""
+ if not value:
+ return False
+ if value.startswith("["):
+ host, sep, rest = value[1:].partition("]")
+ if not sep:
+ return False
+ try:
+ ipaddress.IPv6Address(host)
+ except ValueError:
+ return False
+ if rest:
+ if not rest.startswith(":"):
+ return False
+ port_s = rest[1:]
+ else:
+ port_s = "80"
+ else:
+ host, sep, port_s = value.rpartition(":")
+ if not sep:
+ host, port_s = value, "80"
+ elif ":" in host:
+ return False
+ if not port_s.isascii() or not port_s.isdigit():
+ return False
+ # Strip leading zeroes before converting; an arbitrarily long port cannot
+ # overflow Python's integer-string conversion limit.
+ port_s = port_s.lstrip("0") or "0"
+ if len(port_s) > 5:
+ return False
+ return (_host_key(host), int(port_s)) in allowed_hosts
+
+
+class _HostAllowlistMiddleware:
+ """Validate loopback HTTP hosts before routes, auth and body reads."""
+
+ def __init__(self, app, allowed_hosts: frozenset[tuple[str, int]]) -> None:
+ self._app = app
+ self._allowed_hosts = allowed_hosts
+
+ async def __call__(self, scope, receive, send) -> None:
+ # The UI has no WebSocket routes; do not allow a future one to bypass
+ # this HTTP-only gate. Lifespan messages still pass through.
+ if scope.get("type") == "websocket":
+ await send({"type": "websocket.close", "code": 1008})
+ return
+ if scope.get("type") != "http":
+ await self._app(scope, receive, send)
+ return
+ hosts = [value for name, value in scope.get("headers", ()) if name.lower() == b"host"]
+ if len(hosts) != 1 or not _host_header_allowed(
+ hosts[0].decode("latin-1"), self._allowed_hosts
+ ):
+ from starlette.responses import JSONResponse
+
+ response = JSONResponse({"detail": "Host not allowed"}, status_code=403)
+ await response(scope, receive, send)
+ return
+ await self._app(scope, receive, send)
+
+
class TrainRequest(PydanticBaseModel):
"""Request body for starting a training run."""
config_yaml: str
@@ -451,8 +522,17 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
allow_headers=["Authorization", "Content-Type"],
)
- # Added last, so it is the outermost layer: a 413 from the size cap, a CORS
- # preflight and every error response carry the content policy too.
+ # On loopback binds, validate the bound name and aliases before routes,
+ # authentication and body reads. Public binds keep the Bearer gate.
+ if _is_loopback(host):
+ allowed = frozenset(
+ (_host_key(name.strip("[]")), port)
+ for name in ("localhost", "127.0.0.1", "::1", host)
+ )
+ app.add_middleware(_HostAllowlistMiddleware, allowed_hosts=allowed)
+
+ # Added last, so refusals, body-size errors and CORS preflights carry the
+ # security headers as well as normal endpoint responses.
app.add_middleware(
_SecurityHeadersMiddleware,
policy_exempt_paths=_POLICY_EXEMPT_PATHS if _docs_enabled else frozenset(),
diff --git a/tests/test_config_loader_limits.py b/tests/test_config_loader_limits.py
index 1aeafb28..ed248625 100644
--- a/tests/test_config_loader_limits.py
+++ b/tests/test_config_loader_limits.py
@@ -19,6 +19,7 @@ from soup_cli.utils.yaml_limits import (
MAX_YAML_NESTING,
YamlLimitError,
)
+from tests.ui_helpers import ui_client
_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
@@ -585,13 +586,12 @@ def test_command_still_loads_a_config_at_the_size_limit(in_tmp, argv):
@pytest.mark.parametrize("limit", ["nesting", "aliases"])
def test_web_ui_reports_the_refusal_as_an_invalid_config(limit):
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
make_text, make_message = _OVER_LIMIT[limit]
text = make_text()
- with TestClient(create_app()) as client:
+ with ui_client(create_app()) as client:
response = client.post(
"/api/config/validate",
json={"yaml": text},
diff --git a/tests/test_file_derived_text_printing.py b/tests/test_file_derived_text_printing.py
index 804f4c57..46e58883 100644
--- a/tests/test_file_derived_text_printing.py
+++ b/tests/test_file_derived_text_printing.py
@@ -28,6 +28,8 @@ import pytest
from rich.console import Console
from typer.testing import CliRunner
+from tests.ui_helpers import ui_client
+
runner = CliRunner()
ESC = chr(27)
@@ -619,11 +621,11 @@ class TestWebUiConfigLogLines:
@staticmethod
def _client():
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
- return TestClient(create_app()), {"Authorization": f"Bearer {get_auth_token()}"}
+ client = ui_client(create_app())
+ return client, {"Authorization": f"Bearer {get_auth_token()}"}
def _logged(self, caplog) -> list[str]:
return [record.getMessage() for record in caplog.records if record.name == self.LOGGER]
diff --git a/tests/test_issue1147_missing_grad_norm.py b/tests/test_issue1147_missing_grad_norm.py
index 1343446b..90cddcba 100644
--- a/tests/test_issue1147_missing_grad_norm.py
+++ b/tests/test_issue1147_missing_grad_norm.py
@@ -13,6 +13,7 @@ from soup_cli.experiment.tracker import ExperimentTracker
from soup_cli.monitoring.callback import SoupTrainerCallback
from soup_cli.monitoring.display import TrainingDisplay
from soup_cli.utils.why import diagnose
+from tests.ui_helpers import ui_client
def test_callback_separates_display_from_recorded_norms(monkeypatch) -> None:
@@ -121,7 +122,6 @@ def test_web_chart_keeps_null_as_a_gap_instead_of_fabricating_zero() -> None:
def test_web_metrics_api_serializes_null_norm(tmp_path, monkeypatch) -> None:
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
@@ -137,7 +137,7 @@ def test_web_metrics_api_serializes_null_norm(tmp_path, monkeypatch) -> None:
tracker.log_metrics(run_id, step=1, loss=1.0, grad_norm=None)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/{run_id}/metrics",
headers={"Authorization": f"Bearer {get_auth_token()}"},
diff --git a/tests/test_issue1191_ui_session_cookie.py b/tests/test_issue1191_ui_session_cookie.py
index d260a949..18e6ab12 100644
--- a/tests/test_issue1191_ui_session_cookie.py
+++ b/tests/test_issue1191_ui_session_cookie.py
@@ -15,16 +15,16 @@ import pytest
from fastapi.testclient import TestClient
from soup_cli.ui import app as ui_app
-from soup_cli.ui.app import create_app, get_auth_token
+from soup_cli.ui.app import get_auth_token
+from tests.ui_helpers import ui_client
PORT = 7860
COOKIE = f"soup_ui_session_{PORT}"
-# TestClient sends `Host: testserver` over http.
-SAME_ORIGIN = "http://testserver"
+SAME_ORIGIN = "http://127.0.0.1:7860"
def _client(host: str = "127.0.0.1") -> TestClient:
- return TestClient(create_app(host=host, port=PORT))
+ return ui_client(host=host, port=PORT)
def _sign_in(client: TestClient, query: str = ""):
@@ -69,7 +69,7 @@ class TestExchange:
assert first != second
def test_cookie_name_carries_the_port(self):
- client = TestClient(create_app(host="127.0.0.1", port=8123))
+ client = ui_client(port=8123)
resp = client.get(f"/?token={get_auth_token()}", follow_redirects=False)
assert "soup_ui_session_8123" in resp.cookies
@@ -131,7 +131,7 @@ class TestReloadKeepsTheSession:
first = _sign_in(client).cookies[COOKIE]
_sign_in(client)
_sign_in(client)
- probe = TestClient(client.app)
+ probe = ui_client(client.app, port=PORT)
probe.cookies.set(COOKIE, first)
assert probe.get("/api/train/status").status_code == 401
diff --git a/tests/test_issue1195_ui_auth_non_ascii.py b/tests/test_issue1195_ui_auth_non_ascii.py
index dbeeb588..a2c444bd 100644
--- a/tests/test_issue1195_ui_auth_non_ascii.py
+++ b/tests/test_issue1195_ui_auth_non_ascii.py
@@ -17,9 +17,9 @@ import pathlib
import pytest
-pytest.importorskip("fastapi")
+from tests.ui_helpers import ui_client
-from fastapi.testclient import TestClient # noqa: E402
+pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod # noqa: E402
from soup_cli.ui.app import ( # noqa: E402
@@ -46,7 +46,10 @@ class TestNonAsciiAuthorization:
@pytest.fixture
def client(self):
# Default raise_server_exceptions=True ensures unhandled TypeErrors fail tests
- return TestClient(create_app(), raise_server_exceptions=True)
+ return ui_client(
+ create_app(),
+ raise_server_exceptions=True,
+ )
@pytest.mark.parametrize(
"endpoint,method",
@@ -97,7 +100,10 @@ class TestHappyPathParity:
@pytest.fixture
def client(self):
- return TestClient(create_app(), raise_server_exceptions=True)
+ return ui_client(
+ create_app(),
+ raise_server_exceptions=True,
+ )
def test_valid_token_returns_200_on_read_endpoint(self, client):
token = get_auth_token()
diff --git a/tests/test_issue1424_detect_format_multirow.py b/tests/test_issue1424_detect_format_multirow.py
index 1ef11eed..679c7b3d 100644
--- a/tests/test_issue1424_detect_format_multirow.py
+++ b/tests/test_issue1424_detect_format_multirow.py
@@ -31,6 +31,7 @@ from soup_cli.data.formats import (
format_to_messages,
)
from soup_cli.data.loader import load_dataset
+from tests.ui_helpers import ui_client
_CHAT = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a"}]
_SHAREGPT = [{"from": "human", "value": "q"}, {"from": "gpt", "value": "a"}]
@@ -301,10 +302,7 @@ def test_refusal_names_the_first_row_of_each_shape():
def test_inspect_endpoint_reports_a_mixed_file_instead_of_a_500(tmp_path):
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from unittest.mock import patch
from soup_cli.ui.app import create_app, get_auth_token
@@ -315,7 +313,9 @@ def test_inspect_endpoint_reports_a_mixed_file_instead_of_a_500(tmp_path):
] * 3
path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
- client = TestClient(create_app(), raise_server_exceptions=False)
+ client = ui_client(
+ create_app(), raise_server_exceptions=False
+ )
with patch("soup_cli.ui.app.Path.cwd", return_value=tmp_path):
response = client.post(
"/api/data/inspect",
diff --git a/tests/test_issue627_unknown_config_keys.py b/tests/test_issue627_unknown_config_keys.py
index 6cb3526a..331a3f74 100644
--- a/tests/test_issue627_unknown_config_keys.py
+++ b/tests/test_issue627_unknown_config_keys.py
@@ -30,6 +30,7 @@ from soup_cli.config.unknown_keys import (
find_unknown_config_keys,
format_unknown_keys,
)
+from tests.ui_helpers import ui_client
_VALID = """
base: hf/model
@@ -1236,11 +1237,10 @@ class TestTheWebUiKeepsTheHint:
def test_the_400_names_the_key_and_the_suggestion(self, monkeypatch) -> None:
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/train/start",
json={"config_yaml": TestTheLoaderIsActuallyWiredUp.TYPOD},
@@ -1288,11 +1288,11 @@ class TestTheWebUiErrorBranchesAreDistinct:
@staticmethod
def _client():
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
- return TestClient(create_app()), {"Authorization": f"Bearer {get_auth_token()}"}
+ client = ui_client(create_app())
+ return client, {"Authorization": f"Bearer {get_auth_token()}"}
def test_from_form_names_the_field_on_a_validation_error(self) -> None:
client, headers = self._client()
diff --git a/tests/test_issue687_ui_auth.py b/tests/test_issue687_ui_auth.py
index ba354f83..4d9df69f 100644
--- a/tests/test_issue687_ui_auth.py
+++ b/tests/test_issue687_ui_auth.py
@@ -1,11 +1,11 @@
"""Tests for Issue #687: Web UI authentication on read APIs and SSE streams."""
import pytest
-from fastapi.testclient import TestClient
from typer.testing import CliRunner
from soup_cli.cli import app as cli_app
from soup_cli.ui.app import create_app, get_auth_token
+from tests.ui_helpers import ui_client
def _auth_headers():
@@ -34,7 +34,7 @@ class TestReadAuthentication:
)
def test_unauthenticated_reads_return_401(self, endpoint):
"""Unauthenticated requests to read APIs must return 401."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get(endpoint)
assert resp.status_code == 401, f"{endpoint} allowed unauthenticated access"
@@ -52,13 +52,13 @@ class TestReadAuthentication:
)
def test_bad_token_reads_return_401(self, endpoint):
"""Requests with an invalid Bearer token must return 401."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get(endpoint, headers={"Authorization": "Bearer invalid_secret_token"})
assert resp.status_code == 401
def test_authenticated_reads_succeed(self):
"""Authenticated requests with valid Bearer token return 200."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
headers = _auth_headers()
resp = client.get("/api/system", headers=headers)
@@ -84,19 +84,19 @@ class TestPublicEndpoints:
"""Verify that public endpoints remain reachable without authentication."""
def test_index_is_public(self):
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get("/")
assert resp.status_code == 200
assert "text/html" in resp.headers["content-type"]
def test_health_is_public(self):
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get("/api/health")
assert resp.status_code == 200
assert resp.json() == {"status": "ok"}
def test_static_files_are_public(self):
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get("/static/app.js")
assert resp.status_code == 200
@@ -114,26 +114,26 @@ class TestSSEAuthenticationAndTickets:
)
def test_unauthenticated_sse_returns_401(self, endpoint):
"""SSE endpoints without auth must return 401."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get(endpoint)
assert resp.status_code == 401
def test_bearer_header_on_sse_succeeds(self):
"""SSE endpoints accept direct Authorization Bearer header."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get("/api/train/logs", headers=_auth_headers())
assert resp.status_code == 200
def test_durable_token_in_query_rejected(self):
"""?token= query param must NOT be accepted on SSE endpoints (#687)."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
token = get_auth_token()
resp = client.get(f"/api/train/logs?token={token}")
assert resp.status_code == 401
def test_auth_ticket_exchange_and_single_use(self):
"""POST /api/auth/ticket issues ticket, ticket is single-use only."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
# Unauthenticated ticket request fails
resp = client.post("/api/auth/ticket")
@@ -157,7 +157,7 @@ class TestSSEAuthenticationAndTickets:
def test_invalid_ticket_rejected(self):
"""Nonexistent ticket fails with 401."""
- client = TestClient(create_app())
+ client = ui_client(create_app())
resp = client.get("/api/train/logs?ticket=nonexistent-ticket-value")
assert resp.status_code == 401
@@ -183,7 +183,7 @@ class TestNonLoopbackBindingProtection:
def test_create_app_allows_loopback_default(self):
"""create_app allows loopback hosts with normal token."""
app = create_app(host="127.0.0.1")
- client = TestClient(app)
+ client = ui_client(app)
resp = client.get("/api/system", headers=_auth_headers())
assert resp.status_code == 200
diff --git a/tests/test_issue688_ui_drain.py b/tests/test_issue688_ui_drain.py
index 39b89f78..5c257c3c 100644
--- a/tests/test_issue688_ui_drain.py
+++ b/tests/test_issue688_ui_drain.py
@@ -12,10 +12,10 @@ import sys
import time
import pytest
-from fastapi.testclient import TestClient
import soup_cli.ui.app as ui_app_module
from soup_cli.ui.app import TrainLogBuffer, _drain_stdout_worker, create_app, get_auth_token
+from tests.ui_helpers import ui_client
def _auth_headers():
@@ -106,7 +106,7 @@ class TestSubprocessDrain:
ui_app_module._train_log_buffer.append(f"log line {i}")
ui_app_module._train_log_buffer.mark_done()
- client = TestClient(create_app())
+ client = ui_client(create_app())
# Reconnect with Last-Event-ID = 6 -> should receive lines 7, 8, 9
response = client.get(
@@ -147,7 +147,7 @@ class TestSubprocessDrain:
"soup_cli.ui.app._resolve_train_argv",
return_value=[sys.executable, "-c", child_script],
):
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/train/start",
json={"config_yaml": "base: test\ndata:\n train: ./data.jsonl\n"},
diff --git a/tests/test_issue731_ui_docs_bind.py b/tests/test_issue731_ui_docs_bind.py
index d8dd968d..02e7297b 100644
--- a/tests/test_issue731_ui_docs_bind.py
+++ b/tests/test_issue731_ui_docs_bind.py
@@ -17,6 +17,7 @@ import pytest
from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
+from tests.ui_helpers import ui_client
# The four routes #731 is about. `/docs/oauth2-redirect` is derived from
# `swagger_ui_oauth2_redirect_url`, not from `docs_url`, so it is listed
@@ -130,7 +131,7 @@ class TestLoopbackKeepsTheDeveloperConvenience:
@pytest.mark.parametrize("route", DOC_ROUTES)
def test_docs_still_serve_on_loopback(self, route):
- client = TestClient(create_app(host=LOOPBACK))
+ client = ui_client(create_app(host=LOOPBACK))
assert client.get(route).status_code == 200, (
f"{route} stopped serving on a {LOOPBACK} bind; the fix is scoped "
"to non-loopback binds and must not take the local docs with it"
@@ -138,7 +139,7 @@ class TestLoopbackKeepsTheDeveloperConvenience:
def test_localhost_is_treated_as_loopback_too(self):
"""`_is_loopback` accepts the name, so the docs must survive it."""
- client = TestClient(create_app(host="localhost"))
+ client = TestClient(create_app(host="localhost"), base_url="http://localhost:7860")
assert client.get("/openapi.json").status_code == 200
diff --git a/tests/test_issue897_ui_yaml_body_cap.py b/tests/test_issue897_ui_yaml_body_cap.py
index 1e69f0e2..35409710 100644
--- a/tests/test_issue897_ui_yaml_body_cap.py
+++ b/tests/test_issue897_ui_yaml_body_cap.py
@@ -7,17 +7,17 @@ import pytest
import yaml
from soup_cli.recipes.catalog import RECIPES
+from tests.ui_helpers import ui_client as make_ui_client
@pytest.fixture
def ui_client() -> Iterator[tuple[object, dict[str, str]]]:
"""Yield an authenticated Web UI test client."""
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
- with TestClient(create_app()) as client:
+ with make_ui_client(create_app()) as client:
yield client, {"Authorization": f"Bearer {get_auth_token()}"}
diff --git a/tests/test_issue939_ui_body_cap.py b/tests/test_issue939_ui_body_cap.py
index e4d69a41..9c8d1fc2 100644
--- a/tests/test_issue939_ui_body_cap.py
+++ b/tests/test_issue939_ui_body_cap.py
@@ -4,6 +4,8 @@ import asyncio
import pytest
+from tests.ui_helpers import ui_client
+
def _auth_headers():
"""Return auth headers with the current UI token."""
@@ -32,7 +34,6 @@ def test_oversized_body_is_413_before_route_runs(
) -> None:
"""Both routes must stop before their own validation is reached."""
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app
@@ -53,7 +54,7 @@ def test_oversized_body_is_413_before_route_runs(
monkeypatch.setattr(paths, "is_under_cwd", fail_if_called)
- with TestClient(create_app()) as client:
+ with ui_client(create_app()) as client:
response = client.post(endpoint, json=payload, headers=_auth_headers())
assert response.status_code == 413, response.text
diff --git a/tests/test_outbound_endpoint_ip_literals.py b/tests/test_outbound_endpoint_ip_literals.py
index 690c7b2c..1cacbce9 100644
--- a/tests/test_outbound_endpoint_ip_literals.py
+++ b/tests/test_outbound_endpoint_ip_literals.py
@@ -23,6 +23,8 @@ from types import SimpleNamespace
import pytest
+from tests.ui_helpers import ui_client
+
_REFUSED = "private/link-local/reserved IP hosts are not allowed"
# #1549: the refusal says what to do instead.
_REMEDY = "address the server by its hostname"
@@ -410,11 +412,10 @@ class TestChatProxy:
@pytest.fixture
def post(self, sent):
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app, get_auth_token
- client = TestClient(create_app())
+ client = ui_client(create_app())
headers = {"Authorization": f"Bearer {get_auth_token()}"}
def _post(endpoint: str):
diff --git a/tests/test_review_fixes_v07133.py b/tests/test_review_fixes_v07133.py
index bd83b609..b572c855 100644
--- a/tests/test_review_fixes_v07133.py
+++ b/tests/test_review_fixes_v07133.py
@@ -19,6 +19,8 @@ from pathlib import Path
import pytest
from typer.testing import CliRunner
+from tests.ui_helpers import ui_client
+
# --------------------------------------------------------------------------
# HIGH-1 — vLLM serve must not force trust_remote_code=True
@@ -683,13 +685,12 @@ class TestRunsEscape:
class TestConstantTimeToken:
def test_wrong_token_401_right_token_ok(self):
pytest.importorskip("fastapi")
- from starlette.testclient import TestClient
from soup_cli.ui.app import create_app, set_auth_token
set_auth_token("a" * 32)
app = create_app()
- client = TestClient(app)
+ client = ui_client(app)
# A mutating endpoint requires the Bearer token.
bad = client.post(
"/api/train/start",
diff --git a/tests/test_ui.py b/tests/test_ui.py
index 4025a86b..cd6d24c0 100644
--- a/tests/test_ui.py
+++ b/tests/test_ui.py
@@ -6,6 +6,8 @@ from unittest.mock import MagicMock, patch
import pytest
+from tests.ui_helpers import ui_client
+
def _auth_headers():
"""Return auth headers with the current UI token."""
@@ -101,14 +103,11 @@ class TestHealthEndpoint:
def test_health_returns_ok(self):
"""Health endpoint should return ok status."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/health")
assert response.status_code == 200
assert response.json()["status"] == "ok"
@@ -119,14 +118,11 @@ class TestIndexEndpoint:
def test_index_returns_html(self):
"""Root should serve HTML page."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/")
assert response.status_code == 200
assert "text/html" in response.headers["content-type"]
@@ -134,14 +130,11 @@ class TestIndexEndpoint:
def test_index_contains_pages(self):
"""Index HTML should contain all page sections."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/")
html = response.text
assert "page-dashboard" in html
@@ -155,14 +148,11 @@ class TestSystemEndpoint:
def test_system_info(self):
"""System endpoint should return version and device info."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/system", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -178,14 +168,11 @@ class TestTemplatesEndpoint:
def test_list_templates(self):
"""Templates endpoint should return all built-in templates."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/templates", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -198,14 +185,11 @@ class TestTemplatesEndpoint:
def test_templates_contain_yaml(self):
"""Each template should contain valid YAML content."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/templates", headers=_auth_headers())
templates = response.json()["templates"]
for name, yaml_str in templates.items():
@@ -218,14 +202,11 @@ class TestConfigValidation:
def test_valid_config(self):
"""Should validate a correct config."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
yaml_str = """
base: meta-llama/Llama-3.1-8B
data:
@@ -245,14 +226,11 @@ data:
def test_invalid_config(self):
"""Should report errors for invalid config."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/config/validate",
json={"yaml": "invalid: true"},
@@ -265,14 +243,11 @@ data:
def test_empty_config(self):
"""Should reject empty config."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/config/validate",
json={"yaml": ""},
@@ -286,26 +261,20 @@ class TestRunsEndpoint:
def test_list_runs_empty(self, tmp_path):
"""Should return empty list when no runs exist."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/runs", headers=_auth_headers())
assert response.status_code == 200
assert response.json()["runs"] == []
def test_list_runs_with_data(self, tmp_path):
"""Should return runs from the database."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -322,7 +291,7 @@ class TestRunsEndpoint:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/runs", headers=_auth_headers())
assert response.status_code == 200
runs = response.json()["runs"]
@@ -331,10 +300,7 @@ class TestRunsEndpoint:
def test_get_run_detail(self, tmp_path):
"""Should return run details by ID."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -350,7 +316,7 @@ class TestRunsEndpoint:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(f"/api/runs/{run_id}", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -359,16 +325,13 @@ class TestRunsEndpoint:
def test_get_run_not_found(self, tmp_path):
"""Should return 404 for nonexistent run."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
"/api/runs/nonexistent_run_id", headers=_auth_headers()
)
@@ -376,10 +339,7 @@ class TestRunsEndpoint:
def test_delete_run(self, tmp_path):
"""Should delete a run and return success."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -395,7 +355,7 @@ class TestRunsEndpoint:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.delete(
f"/api/runs/{run_id}", headers=_auth_headers()
)
@@ -408,16 +368,13 @@ class TestRunsEndpoint:
def test_delete_run_not_found(self, tmp_path):
"""Should return 404 when deleting nonexistent run."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.delete(
"/api/runs/nonexistent", headers=_auth_headers()
)
@@ -429,10 +386,7 @@ class TestRunMetrics:
def test_get_metrics(self, tmp_path):
"""Should return metrics for a run."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -451,7 +405,7 @@ class TestRunMetrics:
tracker.log_metrics(run_id, step=30, loss=1.5, lr=8e-6)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(f"/api/runs/{run_id}/metrics", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -463,16 +417,13 @@ class TestRunMetrics:
def test_get_metrics_not_found(self, tmp_path):
"""Should return 404 for metrics of nonexistent run."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
"/api/runs/nonexistent/metrics", headers=_auth_headers()
)
@@ -484,10 +435,7 @@ class TestRunEval:
def test_get_eval_results(self, tmp_path):
"""Should return eval results for a run."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -510,7 +458,7 @@ class TestRunEval:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(f"/api/runs/{run_id}/eval", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -524,10 +472,7 @@ class TestDataInspect:
def test_inspect_jsonl(self, tmp_path):
"""Should inspect a JSONL file and return entries."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
@@ -539,7 +484,7 @@ class TestDataInspect:
]
data_file.write_text("\n".join(json.dumps(e) for e in entries), encoding="utf-8")
- client = TestClient(create_app())
+ client = ui_client(create_app())
with patch("soup_cli.ui.app.Path.cwd", return_value=tmp_path):
response = client.post(
"/api/data/inspect",
@@ -555,14 +500,11 @@ class TestDataInspect:
def test_inspect_file_not_found(self, tmp_path):
"""Should return 404 for nonexistent file."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
with patch("soup_cli.ui.app.Path.cwd", return_value=tmp_path):
response = client.post(
"/api/data/inspect",
@@ -573,10 +515,7 @@ class TestDataInspect:
def test_inspect_with_limit(self, tmp_path):
"""Should respect the limit parameter."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
@@ -589,7 +528,7 @@ class TestDataInspect:
"\n".join(json.dumps(e) for e in entries), encoding="utf-8"
)
- client = TestClient(create_app())
+ client = ui_client(create_app())
with patch("soup_cli.ui.app.Path.cwd", return_value=tmp_path):
response = client.post(
"/api/data/inspect",
@@ -603,10 +542,7 @@ class TestDataInspect:
def test_inspect_json_file(self, tmp_path):
"""Should inspect a JSON array file."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
@@ -616,7 +552,7 @@ class TestDataInspect:
]
data_file.write_text(json.dumps(entries), encoding="utf-8")
- client = TestClient(create_app())
+ client = ui_client(create_app())
with patch("soup_cli.ui.app.Path.cwd", return_value=tmp_path):
response = client.post(
"/api/data/inspect",
@@ -632,10 +568,7 @@ class TestTrainEndpoints:
def test_train_status_not_running(self):
"""Should report not running when no training in progress."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_app_module
from soup_cli.ui.app import create_app
@@ -643,34 +576,28 @@ class TestTrainEndpoints:
# Reset global state
ui_app_module._train_process = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/train/status", headers=_auth_headers())
assert response.status_code == 200
assert response.json()["running"] is False
def test_stop_training_not_running(self):
"""Should report no training to stop."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_app_module
from soup_cli.ui.app import create_app
ui_app_module._train_process = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post("/api/train/stop", headers=_auth_headers())
assert response.status_code == 200
assert response.json()["stopped"] is False
def test_start_training(self, tmp_path):
"""Should start training subprocess."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_app_module
from soup_cli.ui.app import create_app
@@ -682,7 +609,7 @@ class TestTrainEndpoints:
mock_popen.pid = 12345
with patch("soup_cli.ui.app.subprocess.Popen", return_value=mock_popen):
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/train/start",
json={
@@ -700,10 +627,7 @@ class TestTrainEndpoints:
def test_start_training_conflict(self, tmp_path):
"""Should reject second training when one is running."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_app_module
from soup_cli.ui.app import create_app
@@ -713,7 +637,7 @@ class TestTrainEndpoints:
mock_proc.poll.return_value = None
ui_app_module._train_process = mock_proc
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/train/start",
json={
@@ -789,28 +713,22 @@ class TestStaticFiles:
def test_static_css(self):
"""Should serve CSS file."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/static/style.css")
assert response.status_code == 200
assert "text/css" in response.headers["content-type"]
def test_static_js(self):
"""Should serve JavaScript file."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/static/app.js")
assert response.status_code == 200
assert "javascript" in response.headers["content-type"]
@@ -830,30 +748,24 @@ class TestRunsLimitParam:
def test_runs_limit_default(self, tmp_path):
"""Should use default limit of 50."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/runs", headers=_auth_headers())
assert response.status_code == 200
def test_runs_custom_limit(self, tmp_path):
"""Should accept custom limit parameter."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/runs?limit=10", headers=_auth_headers())
assert response.status_code == 200
diff --git a/tests/test_ui_chat.py b/tests/test_ui_chat.py
index c3fc3ef7..34802322 100644
--- a/tests/test_ui_chat.py
+++ b/tests/test_ui_chat.py
@@ -23,6 +23,8 @@ from unittest.mock import MagicMock, patch
import pytest
+from tests.ui_helpers import ui_client
+
_UPSTREAM_REPLY = 'data: {"choices":[{"delta":{"content":"pong"}}]}\n\ndata: [DONE]\n\n'
# What the browser receives when the proxied reply above went through `chat_send`.
@@ -166,14 +168,11 @@ class TestChatSSRFProtection:
def test_rejects_non_localhost_http(self):
"""Chat endpoint should reject non-localhost HTTP URLs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -186,14 +185,11 @@ class TestChatSSRFProtection:
def test_allows_localhost_http(self, upstream):
"""Chat endpoint should allow localhost HTTP URLs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -209,14 +205,11 @@ class TestChatSSRFProtection:
def test_allows_https_remote(self, upstream):
"""Chat endpoint should allow HTTPS remote URLs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -236,14 +229,11 @@ class TestChatParamBounds:
def test_max_tokens_capped(self):
"""max_tokens should be capped at 16384."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -258,14 +248,11 @@ class TestChatParamBounds:
def test_temperature_bounded(self):
"""temperature should be bounded 0.0-2.0."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -279,14 +266,11 @@ class TestChatParamBounds:
def test_top_p_bounded(self):
"""top_p should be bounded 0.0-1.0."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -304,14 +288,11 @@ class TestChatInvalidScheme:
def test_rejects_ftp_scheme(self):
"""Chat endpoint should reject ftp:// URLs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -324,14 +305,11 @@ class TestChatInvalidScheme:
def test_rejects_ipv6_mapped_loopback_alias(self):
"""Chat endpoint should reject IPv6-mapped private addresses."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -344,14 +322,11 @@ class TestChatInvalidScheme:
def test_allows_127_loopback_range(self, upstream):
"""Chat endpoint should allow 127.x.x.x loopback addresses."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -367,14 +342,11 @@ class TestChatInvalidScheme:
def test_rejects_file_scheme(self):
"""Chat endpoint should reject file:// URLs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -391,14 +363,11 @@ class TestChatAuth:
def test_requires_auth(self):
"""Chat send (POST) should require Bearer auth."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -414,14 +383,11 @@ class TestChatValidation:
def test_empty_messages_rejected(self):
"""Empty messages array should return 400."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
@@ -434,14 +400,11 @@ class TestChatValidation:
def test_returns_event_stream(self):
"""Chat endpoint should return text/event-stream content type."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
# Mock httpx to avoid real connection
mock_response = MagicMock()
mock_response.status_code = 200
@@ -499,14 +462,11 @@ class TestThisFileIsOffline:
This is the request that waited 75 s on macOS. If it ever passes the guard,
the list is empty and this test says so.
"""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/chat/send",
json={
diff --git a/tests/test_ui_config_builder.py b/tests/test_ui_config_builder.py
index 6942f04f..ed10accf 100644
--- a/tests/test_ui_config_builder.py
+++ b/tests/test_ui_config_builder.py
@@ -2,6 +2,8 @@
import pytest
+from tests.ui_helpers import ui_client
+
def _auth_headers():
"""Return auth headers with the current UI token."""
@@ -27,14 +29,11 @@ class TestConfigSchemaEndpoint:
def test_schema_returns_json(self):
"""Schema endpoint should return valid JSON."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/config/schema", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -42,14 +41,11 @@ class TestConfigSchemaEndpoint:
def test_schema_includes_base_field(self):
"""Schema should include 'base' as a required string field."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/config/schema", headers=_auth_headers())
data = response.json()
assert "base" in data
@@ -58,14 +54,11 @@ class TestConfigSchemaEndpoint:
def test_schema_includes_task_enum(self):
"""Schema should include 'task' with enum options."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/config/schema", headers=_auth_headers())
data = response.json()
assert "task" in data
@@ -75,14 +68,11 @@ class TestConfigSchemaEndpoint:
def test_schema_includes_training_fields(self):
"""Schema should include nested training fields."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/config/schema", headers=_auth_headers())
data = response.json()
assert "training" in data
@@ -92,14 +82,11 @@ class TestConfigSchemaEndpoint:
def test_schema_includes_constraints(self):
"""Schema should include ge/le constraints for bounded fields."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/config/schema", headers=_auth_headers())
data = response.json()
# Check that training.epochs has constraints or type info
@@ -126,14 +113,11 @@ class TestRecipesEndpoint:
def test_recipes_returns_catalog(self):
"""Recipes endpoint should return all recipes."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/recipes", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -142,14 +126,11 @@ class TestRecipesEndpoint:
def test_recipes_have_required_fields(self):
"""Each recipe should have name, model, task fields."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/recipes", headers=_auth_headers())
recipes = response.json()["recipes"]
for recipe in recipes:
@@ -177,14 +158,11 @@ class TestFormToYamlEndpoint:
def test_form_to_yaml_produces_valid_config(self):
"""Form-to-YAML should produce a valid config string."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/config/from-form",
json={
@@ -203,14 +181,11 @@ class TestFormToYamlEndpoint:
def test_form_to_yaml_validates(self):
"""Form-to-YAML should validate via load_config_from_string."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/config/from-form",
json={
@@ -225,14 +200,11 @@ class TestFormToYamlEndpoint:
def test_form_to_yaml_invalid_returns_error(self):
"""Invalid form values should return error."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
# Missing base — should fail validation
response = client.post(
"/api/config/from-form",
@@ -246,14 +218,11 @@ class TestFormToYamlEndpoint:
def test_form_to_yaml_requires_auth(self):
"""Form-to-YAML (POST) should require auth."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/config/from-form",
json={"base": "test"},
@@ -262,14 +231,11 @@ class TestFormToYamlEndpoint:
def test_form_to_yaml_special_chars_in_keys(self):
"""Form values with special YAML characters should be handled safely."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/config/from-form",
json={
@@ -290,14 +256,11 @@ class TestFormToYamlEndpoint:
def test_form_to_yaml_with_lora(self):
"""Form-to-YAML should handle nested lora config."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.post(
"/api/config/from-form",
json={
diff --git a/tests/test_ui_host_header.py b/tests/test_ui_host_header.py
new file mode 100644
index 00000000..fbf7e099
--- /dev/null
+++ b/tests/test_ui_host_header.py
@@ -0,0 +1,207 @@
+"""Loopback UI Host validation before routes, authentication and body reads."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from fastapi.testclient import TestClient
+
+from soup_cli.ui.app import SECURITY_HEADERS, _HostAllowlistMiddleware, create_app, get_auth_token
+from tests.ui_helpers import ui_client
+
+PORT = 7860
+BASE_URL = f"http://127.0.0.1:{PORT}"
+
+
+def _client(**kwargs) -> TestClient:
+ return ui_client(**kwargs)
+
+
+def _bearer_headers() -> dict[str, str]:
+ return {"Authorization": f"Bearer {get_auth_token()}"}
+
+
+def _raw_request(headers: list[tuple[bytes, bytes]], **scope_overrides) -> list[dict]:
+ scope = {
+ "type": "http", "asgi": {"version": "3.0"}, "scheme": "http",
+ "method": "GET", "path": "/api/health", "raw_path": b"/api/health",
+ "query_string": b"", "root_path": "", "headers": headers,
+ "client": ("127.0.0.1", 54321), "server": ("127.0.0.1", PORT),
+ **scope_overrides,
+ }
+ sent = []
+
+ async def receive():
+ raise AssertionError("A refused request must not read its body")
+
+ async def send(message):
+ sent.append(message)
+
+ asyncio.run(create_app()(scope, receive, send))
+ return sent
+
+
+class TestLoopbackHostAllowlist:
+ @pytest.mark.parametrize("host", ["127.0.0.1", "localhost", "[::1]"])
+ def test_served_names(self, host):
+ assert _client().get("/api/health", headers={"Host": f"{host}:{PORT}"}).status_code == 200
+
+ @pytest.mark.parametrize("host", ["::1", "localhost", "127.0.0.2"])
+ def test_other_loopback_binds_serve_the_bound_host_and_aliases(self, host):
+ client = _client(host=host)
+ bound_name = f"[{host}]" if ":" in host else host
+ for name in (bound_name, "127.0.0.1", "localhost", "[::1]"):
+ assert client.get("/api/health", headers={"Host": f"{name}:{PORT}"}).status_code == 200
+
+ @pytest.mark.parametrize("host", ["::1", "0:0:0:0:0:0:0:1"])
+ @pytest.mark.parametrize("port", [80, 8080])
+ def test_ipv6_client_preserves_the_bound_host_and_port(self, host, port):
+ # Use explicit Host headers so TestClient need not parse an IPv6 base URL.
+ client = _client(host=host, port=port)
+ assert client.get("/api/health", headers={"Host": f"[{host}]:{port}"}).status_code == 200
+ assert client.get("/api/health", headers={"Host": f"[{host}]:7860"}).status_code == 403
+
+ @pytest.mark.parametrize("value", ["[0:0:0:0:0:0:0:1]:7860", "LOCALHOST:7860"])
+ def test_ip_literal_and_hostname_normalization(self, value):
+ assert _client().get("/api/health", headers={"Host": value}).status_code == 200
+
+ @pytest.mark.parametrize("name", ["127.0.0.1", "localhost", "[::1]"])
+ def test_default_http_port_is_served_on_port_80(self, name):
+ client = TestClient(create_app(port=80), base_url="http://127.0.0.1")
+ assert client.get("/api/health", headers={"Host": name}).status_code == 200
+ assert client.get("/api/health", headers={"Host": f"{name}:80"}).status_code == 200
+ assert client.get("/api/health", headers={"Host": f"{name}:{PORT}"}).status_code == 403
+
+ def test_nondefault_bound_port_is_served(self):
+ client = _client(port=8080)
+ assert client.get("/api/health", headers={"Host": "localhost:8080"}).status_code == 200
+ assert client.get("/api/health", headers={"Host": "localhost:7860"}).status_code == 403
+
+
+class TestForeignHostRefused:
+ @pytest.mark.parametrize("path", [
+ "/", "/static/app.js", "/openapi.json", "/docs", "/redoc",
+ "/docs/oauth2-redirect", "/api/health", "/api/train/status", "/unknown",
+ ])
+ def test_foreign_host_is_refused_on_every_route(self, path):
+ resp = _client().get(path, headers={"Host": "evil.example.com:7860"})
+ assert resp.status_code == 403
+ assert resp.json() == {"detail": "Host not allowed"}
+ for name, value in SECURITY_HEADERS.items():
+ assert resp.headers[name] == value
+
+ def test_foreign_host_bearer_post_is_refused(self):
+ client = _client()
+ assert client.post("/api/auth/ticket", headers=_bearer_headers()).status_code == 200
+ resp = client.post(
+ "/api/auth/ticket", headers={"Host": "evil.example.com:7860", **_bearer_headers()},
+ )
+ assert resp.status_code == 403
+ assert resp.json() == {"detail": "Host not allowed"}
+
+ def test_foreign_host_cookie_post_is_refused(self):
+ client = _client()
+ assert client.get(f"/?token={get_auth_token()}", follow_redirects=False).status_code == 303
+ assert client.post("/api/auth/ticket", headers={
+ "Host": f"127.0.0.1:{PORT}", "Origin": BASE_URL,
+ }).status_code == 200
+ resp = client.post("/api/auth/ticket", headers={
+ "Host": "evil.example.com:7860", "Origin": "http://evil.example.com:7860",
+ })
+ assert resp.status_code == 403
+ assert resp.json() == {"detail": "Host not allowed"}
+
+ @pytest.mark.parametrize("content_length", [None, b"2097152"])
+ def test_foreign_host_is_refused_before_the_body_cap_reads_any_body(self, content_length):
+ headers = [(b"host", b"evil.example.com:7860"), (b"content-type", b"application/json")]
+ if content_length is not None:
+ headers.append((b"content-length", content_length))
+ sent = _raw_request(
+ headers, method="POST", path="/api/chat/send", raw_path=b"/api/chat/send",
+ )
+ assert sent[0]["status"] == 403
+
+ @pytest.mark.parametrize("value", ["127.0.0.1:9999", "127.0.0.1", "[::1]", ""])
+ def test_wrong_port_or_missing_port_or_empty_host_is_refused(self, value):
+ resp = _client().get("/api/health", headers={"Host": value})
+ assert resp.status_code == 403
+ assert resp.json() == {"detail": "Host not allowed"}
+
+ def test_missing_host_is_refused(self):
+ assert _raw_request([(b"accept", b"*/*")])[0]["status"] == 403
+
+ @pytest.mark.parametrize("value", [
+ "localhost:", "localhost:abc", "localhost:7860:7860", "::1:7860", "[::1",
+ "[::1]x7860", "[::1]:", "[::1]:abc", "[:]:1:7860", "localhost.:7860",
+ "[localhost]:7860", "[127.0.0.1]:7860",
+ "localhost:0", "localhost:65536",
+ ])
+ def test_malformed_host_is_refused(self, value):
+ assert _client().get("/api/health", headers={"Host": value}).status_code == 403
+
+ @pytest.mark.parametrize("value", [b"localhost:\xb2", b"[::1]:\xb2"])
+ def test_non_ascii_port_is_refused(self, value):
+ assert _raw_request([(b"host", value)])[0]["status"] == 403
+
+ @pytest.mark.parametrize("values", [
+ (b"evil.example.com:7860", b"127.0.0.1:7860"),
+ (b"127.0.0.1:7860", b"evil.example.com:7860"),
+ (b"127.0.0.1:7860", b"127.0.0.1:7860"),
+ ])
+ def test_duplicate_host_headers_are_refused(self, values):
+ assert _raw_request([(b"host", values[0]), (b"Host", values[1])])[0]["status"] == 403
+
+
+class TestPublicBindUnchanged:
+ @pytest.mark.parametrize("host", ["192.168.1.5", "0.0.0.0"])
+ def test_public_bind_keeps_bearer_authentication(self, host):
+ client = _client(host=host)
+ headers = {"Host": "anything.example.com:7860"}
+ assert client.get("/api/train/status", headers=headers).status_code == 401
+ response = client.get("/api/train/status", headers={**headers, **_bearer_headers()})
+ assert response.status_code == 200
+
+
+class TestASGIScopes:
+ def test_lifespan_messages_pass_through(self):
+ received = [{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}]
+ scope = {"type": "lifespan"}
+ seen = []
+ sent = []
+
+ async def app(actual_scope, receive, send):
+ assert actual_scope is scope
+ seen.append(await receive())
+ await send({"type": "lifespan.startup.complete"})
+ seen.append(await receive())
+ await send({"type": "lifespan.shutdown.complete"})
+
+ async def receive():
+ return received[len(seen)]
+
+ async def send(message):
+ sent.append(message)
+
+ middleware = _HostAllowlistMiddleware(app, frozenset())
+ asyncio.run(middleware(scope, receive, send))
+ assert seen == received
+ assert sent == [
+ {"type": "lifespan.startup.complete"}, {"type": "lifespan.shutdown.complete"},
+ ]
+
+ def test_websocket_scopes_are_closed_without_calling_downstream(self):
+ sent = []
+
+ async def app(scope, receive, send):
+ raise AssertionError("The HTTP-only UI gate must not pass a WebSocket to a route")
+
+ async def receive():
+ return {"type": "websocket.connect"}
+
+ async def send(message):
+ sent.append(message)
+
+ middleware = _HostAllowlistMiddleware(app, frozenset())
+ asyncio.run(middleware({"type": "websocket"}, receive, send))
+ assert sent == [{"type": "websocket.close", "code": 1008}]
diff --git a/tests/test_ui_live_monitor.py b/tests/test_ui_live_monitor.py
index 516b7b05..2315e8a5 100644
--- a/tests/test_ui_live_monitor.py
+++ b/tests/test_ui_live_monitor.py
@@ -5,6 +5,8 @@ from unittest.mock import MagicMock, patch
import pytest
+from tests.ui_helpers import ui_client
+
def _auth_headers():
"""Return auth headers with the current UI token."""
@@ -30,10 +32,7 @@ class TestTrainLogsSSE:
def test_logs_returns_event_stream(self):
"""SSE endpoint should return text/event-stream content type."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -49,7 +48,7 @@ class TestTrainLogsSSE:
buf.mark_done()
ui_mod._train_log_buffer = buf
- client = TestClient(create_app())
+ client = ui_client(create_app())
try:
with client.stream(
"GET", "/api/train/logs", headers=_auth_headers()
@@ -68,17 +67,14 @@ class TestTrainLogsSSE:
def test_logs_no_training_returns_done(self):
"""When no training is running, SSE should emit done event."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
ui_mod._train_process = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream(
"GET", "/api/train/logs", headers=_auth_headers()
) as resp:
@@ -91,10 +87,7 @@ class TestTrainLogsSSE:
def test_logs_last_event_id_reconnection(self):
"""Last-Event-ID header should skip earlier lines."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -106,7 +99,7 @@ class TestTrainLogsSSE:
buf.mark_done()
ui_mod._train_log_buffer = buf
- client = TestClient(create_app())
+ client = ui_client(create_app())
try:
with client.stream(
"GET",
@@ -124,17 +117,14 @@ class TestTrainLogsSSE:
ui_mod._train_log_buffer = None
def test_logs_no_auth_required(self):
"""SSE log endpoint requires auth (401 without token, 200 with one)."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
ui_mod._train_process = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream("GET", "/api/train/logs") as resp:
assert resp.status_code == 401
with client.stream(
@@ -161,10 +151,7 @@ class TestLiveMetricsSSE:
def test_metrics_live_returns_event_stream(self, tmp_path):
"""SSE metrics endpoint should return text/event-stream content type."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -176,7 +163,7 @@ class TestLiveMetricsSSE:
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream(
"GET", "/api/train/metrics/live", headers=_auth_headers()
) as resp:
@@ -187,10 +174,7 @@ class TestLiveMetricsSSE:
def test_metrics_live_emits_new_rows(self, tmp_path):
"""SSE should emit metric rows as they appear in the DB."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -216,7 +200,7 @@ class TestLiveMetricsSSE:
ui_mod._train_process = mock_proc
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream(
"GET",
f"/api/train/metrics/live?run_id={run_id}",
@@ -234,10 +218,7 @@ class TestLiveMetricsSSE:
def test_metrics_live_no_auth_required(self, tmp_path):
"""SSE metrics endpoint requires auth (401 without token, 200 with one)."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -248,7 +229,7 @@ class TestLiveMetricsSSE:
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream("GET", "/api/train/metrics/live") as resp:
assert resp.status_code == 401
with client.stream(
@@ -260,10 +241,7 @@ class TestLiveMetricsSSE:
def test_metrics_live_done_when_no_training(self, tmp_path):
"""Should emit done event when no training is running."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -272,7 +250,7 @@ class TestLiveMetricsSSE:
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream(
"GET", "/api/train/metrics/live", headers=_auth_headers()
) as resp:
@@ -303,17 +281,14 @@ class TestTrainProgress:
def test_progress_not_running(self):
"""Should return running=false when no training."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
ui_mod._train_process = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get("/api/train/progress", headers=_auth_headers())
assert response.status_code == 200
data = response.json()
@@ -321,10 +296,7 @@ class TestTrainProgress:
def test_progress_running_with_metrics(self, tmp_path):
"""Should return progress when training is running."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -349,7 +321,7 @@ class TestTrainProgress:
ui_mod._train_process = mock_proc
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/train/progress?run_id={run_id}", headers=_auth_headers()
)
@@ -362,10 +334,7 @@ class TestTrainProgress:
def test_progress_returns_correct_fields(self, tmp_path):
"""Progress response should contain all required fields."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -390,7 +359,7 @@ class TestTrainProgress:
ui_mod._train_process = mock_proc
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/train/progress?run_id={run_id}", headers=_auth_headers()
)
@@ -402,17 +371,14 @@ class TestTrainProgress:
def test_progress_no_auth_required(self):
"""Progress endpoint requires auth (401 without token, 200 with one)."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
ui_mod._train_process = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
assert client.get("/api/train/progress").status_code == 401
assert (
client.get("/api/train/progress", headers=_auth_headers()).status_code
@@ -425,10 +391,7 @@ class TestSSEGracefulClose:
def test_logs_closes_when_training_stops(self):
"""Log SSE should require auth and end when training process finishes."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
@@ -438,7 +401,7 @@ class TestSSEGracefulClose:
mock_proc.poll.side_effect = [None, 0]
ui_mod._train_process = mock_proc
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream("GET", "/api/train/logs") as resp:
assert resp.status_code == 401
@@ -460,17 +423,14 @@ class TestSSEGracefulClose:
"""SSE should include heartbeat comments to keep connection alive."""
# This is a design test — heartbeats are sent as SSE comments (:heartbeat)
# Testing that the generator yields at least one event
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
import soup_cli.ui.app as ui_mod
from soup_cli.ui.app import create_app
ui_mod._train_process = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream(
"GET", "/api/train/logs", headers=_auth_headers()
) as resp:
diff --git a/tests/test_ui_metrics.py b/tests/test_ui_metrics.py
index 6a7719bd..edee5e7a 100644
--- a/tests/test_ui_metrics.py
+++ b/tests/test_ui_metrics.py
@@ -5,6 +5,8 @@ from unittest.mock import patch
import pytest
+from tests.ui_helpers import ui_client
+
def _auth_headers():
"""Return auth headers with the current UI token."""
@@ -17,10 +19,7 @@ class TestMetricsFullFields:
def test_metrics_includes_grad_norm(self, tmp_path):
"""Metrics should include grad_norm field."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -40,7 +39,7 @@ class TestMetricsFullFields:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/{run_id}/metrics", headers=_auth_headers()
)
@@ -54,10 +53,7 @@ class TestMetricsFullFields:
def test_metrics_includes_epoch(self, tmp_path):
"""Metrics should include epoch field."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -74,7 +70,7 @@ class TestMetricsFullFields:
tracker.log_metrics(run_id, step=10, epoch=1.5, loss=2.0, lr=1e-5)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/{run_id}/metrics", headers=_auth_headers()
)
@@ -100,10 +96,7 @@ class TestRunsCompareEndpoint:
def test_compare_returns_metrics(self, tmp_path):
"""Compare endpoint should return metrics for multiple runs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -125,7 +118,7 @@ class TestRunsCompareEndpoint:
tracker.log_metrics(run2, step=10, loss=1.8, lr=5e-6)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/compare?ids={run1},{run2}", headers=_auth_headers()
)
@@ -140,16 +133,13 @@ class TestRunsCompareEndpoint:
def test_compare_rejects_too_many_runs(self, tmp_path):
"""Compare endpoint should reject >5 runs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
ids = ",".join([f"run_{i}" for i in range(6)])
response = client.get(
f"/api/runs/compare?ids={ids}", headers=_auth_headers()
@@ -158,16 +148,13 @@ class TestRunsCompareEndpoint:
def test_compare_validates_run_ids(self, tmp_path):
"""Compare endpoint returns entries for nonexistent runs (empty metrics)."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test_validate.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
"/api/runs/compare?ids=nonexistent1,nonexistent2",
headers=_auth_headers(),
@@ -178,16 +165,13 @@ class TestRunsCompareEndpoint:
def test_compare_empty_ids(self, tmp_path):
"""Compare endpoint should reject empty ids."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test_empty.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
"/api/runs/compare?ids=", headers=_auth_headers()
)
@@ -195,16 +179,13 @@ class TestRunsCompareEndpoint:
def test_compare_no_auth_required(self, tmp_path):
"""Compare requires auth (401 without token, 200 with one)."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test_noauth.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
assert client.get("/api/runs/compare?ids=run1,run2").status_code == 401
assert (
client.get(
@@ -219,10 +200,7 @@ class TestEvalResultsEndpoint:
def test_eval_results_include_details(self, tmp_path):
"""Eval results should include parsed details_json."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -244,7 +222,7 @@ class TestEvalResultsEndpoint:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/{run_id}/eval", headers=_auth_headers()
)
@@ -258,10 +236,7 @@ class TestEvalResultsEndpoint:
def test_eval_results_empty(self, tmp_path):
"""Empty eval results should return empty array, not error."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -276,7 +251,7 @@ class TestEvalResultsEndpoint:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/{run_id}/eval", headers=_auth_headers()
)
@@ -286,10 +261,7 @@ class TestEvalResultsEndpoint:
def test_compare_max_five_runs(self, tmp_path):
"""Compare endpoint allows exactly 5 runs."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -307,7 +279,7 @@ class TestEvalResultsEndpoint:
run_ids.append(rid)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
ids_str = ",".join(run_ids)
response = client.get(
f"/api/runs/compare?ids={ids_str}", headers=_auth_headers()
@@ -321,10 +293,7 @@ class TestCompareMetricsContent:
def test_compare_includes_all_metric_fields(self, tmp_path):
"""Compare should return metrics with all fields."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -343,7 +312,7 @@ class TestCompareMetricsContent:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/compare?ids={run_id}", headers=_auth_headers()
)
@@ -356,10 +325,7 @@ class TestCompareMetricsContent:
def test_compare_includes_config(self, tmp_path):
"""Compare should include run config for diff display."""
- try:
- from fastapi.testclient import TestClient
- except ImportError:
- pytest.skip("FastAPI not installed")
+ pytest.importorskip("fastapi")
db_path = tmp_path / "test.db"
with patch.dict(os.environ, {"SOUP_DB_PATH": str(db_path)}):
@@ -374,7 +340,7 @@ class TestCompareMetricsContent:
)
tracker.close()
- client = TestClient(create_app())
+ client = ui_client(create_app())
response = client.get(
f"/api/runs/compare?ids={run_id}", headers=_auth_headers()
)
diff --git a/tests/test_ui_security_headers.py b/tests/test_ui_security_headers.py
index 2e9b7561..9b9eba2f 100644
--- a/tests/test_ui_security_headers.py
+++ b/tests/test_ui_security_headers.py
@@ -8,6 +8,8 @@ from pathlib import Path
import pytest
+from tests.ui_helpers import ui_client
+
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient # noqa: E402
@@ -36,7 +38,7 @@ def _assert_plain_headers(resp):
@pytest.fixture
def client():
- return TestClient(create_app())
+ return ui_client(create_app())
@pytest.mark.parametrize("path", ["/", "/static/app.js", "/static/safe_html.js", "/api/system"])
@@ -100,7 +102,7 @@ def test_headers_on_body_size_rejection(client):
def test_headers_on_event_stream():
ui_mod._train_process = None
ui_mod._train_log_buffer = None
- client = TestClient(create_app())
+ client = ui_client(create_app())
with client.stream(
"GET", "/api/train/logs", headers={"Authorization": f"Bearer {get_auth_token()}"}
) as resp:
diff --git a/tests/test_v0539.py b/tests/test_v0539.py
index 51a007dc..ec0126a0 100644
--- a/tests/test_v0539.py
+++ b/tests/test_v0539.py
@@ -17,6 +17,7 @@ from typer.testing import CliRunner
import soup_cli
from soup_cli.cli import app
+from tests.ui_helpers import ui_client
# CI's Rich pipeline emits ANSI escape codes that split keywords like
# `--vocab-size` into multiple styled spans, breaking naive `in` checks.
@@ -146,7 +147,6 @@ def _auth_headers():
def test_api_train_stream_emits_pending_events():
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app
from soup_cli.utils.sse_train_stream import TrainEvent
@@ -160,7 +160,7 @@ def test_api_train_stream_emits_pending_events():
push_train_event(TrainEvent(type="status", message="started"))
app_inst = create_app()
- client = TestClient(app_inst)
+ client = ui_client(app_inst)
response = client.get("/api/train/stream", headers=_auth_headers())
assert response.status_code == 200
body = response.text
@@ -195,7 +195,6 @@ def test_global_tool_buffer_round_trip():
def test_api_tool_outputs_endpoint():
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app
from soup_cli.utils.tool_outputs import (
@@ -222,7 +221,7 @@ def test_api_tool_outputs_endpoint():
)
app_inst = create_app()
- client = TestClient(app_inst)
+ client = ui_client(app_inst)
response = client.get("/api/tool-outputs?limit=5", headers=_auth_headers())
assert response.status_code == 200
payload = response.json()
@@ -234,11 +233,10 @@ def test_api_tool_outputs_endpoint():
def test_api_tool_outputs_rejects_out_of_bounds_limit():
pytest.importorskip("fastapi")
- from fastapi.testclient import TestClient
from soup_cli.ui.app import create_app
- client = TestClient(create_app())
+ client = ui_client(create_app())
# limit must be 1..1000
assert (
client.get(
diff --git a/tests/ui_helpers.py b/tests/ui_helpers.py
new file mode 100644
index 00000000..902e3172
--- /dev/null
+++ b/tests/ui_helpers.py
@@ -0,0 +1,21 @@
+"""Build Web UI test clients using the address served by create_app."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from fastapi.testclient import TestClient
+
+
+def ui_client(app=None, *, host: str = "127.0.0.1", port: int = 7860, **kwargs) -> TestClient:
+ """Use the served address; IPv6 binds need explicit Host headers on requests."""
+ from fastapi.testclient import TestClient
+
+ from soup_cli.ui.app import create_app
+
+ if app is None:
+ app = create_app(host=host, port=port)
+ # Starlette 1.6 TestClient cannot parse an IPv6 netloc.
+ url_host = "127.0.0.1" if ":" in host else host
+ return TestClient(app, base_url=f"http://{url_host}:{port}", **kwargs)