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.

feat(ui): keep the session across reloads with an HttpOnly cookie (#1191) (#1474)

Mohd Uwaish6a467076aec0
diff --git a/changelog.d/0.75.1/1474.added.md b/changelog.d/0.75.1/1474.added.md
new file mode 100644
index 00000000..7fde560b
--- /dev/null
+++ b/changelog.d/0.75.1/1474.added.md
@@ -0,0 +1 @@
+- **`soup ui` keeps the session across reloads with an HttpOnly cookie on a loopback bind (#1191 by @mohdUwaish59 in #1474).** Opening `/?token=<TOKEN>` checks the token, sets an `HttpOnly; SameSite=Strict; Path=/` session cookie named after the port (`soup_ui_session_<PORT>`) and redirects to the same URL without `token`, keeping the other query parameters. The cookie holds a random session id that the server keeps only in memory, never the token, so a reload or a new tab stays signed in without the token being readable from page script, and every restart ends every session. A cookie-authenticated request other than `GET`/`HEAD` must carry an `Origin` naming this exact server (scheme, host and port), because every port of `127.0.0.1` is one site and `SameSite=Strict` alone would not stop a page from another local app; a missing or `null` `Origin` is refused with 403. The `Authorization: Bearer` header is unchanged and needs no `Origin`, SSE streams accept the cookie while Bearer clients keep the ticket exchange, and CORS still sends no `Access-Control-Allow-Credentials`. On `--public` or any non-loopback bind no cookie is set or accepted, and the phone page keeps the token in page memory as before.
diff --git a/docs/serving-and-export.md b/docs/serving-and-export.md
index ff36d7b5..d20f862a 100644
--- a/docs/serving-and-export.md
+++ b/docs/serving-and-export.md
@@ -649,7 +649,9 @@ soup ui
> keeps the token for that tab, so a reload works, and removes it from the
> address bar; your browser's history still records the URL. A new tab or
> another browser needs the URL again, and the token changes every time
-> `soup ui` starts unless you pass `--auth-token`.
+> `soup ui` starts unless you pass `--auth-token`. Releases with the session
+> cookie keep a new tab signed in as well; see "Session cookie on a loopback
+> bind" below.
**Pages:**
- **Dashboard** — view all experiment runs, loss charts, system info, multi-run comparison
@@ -671,7 +673,9 @@ terminal panel.
**Security:** The Web UI generates a random auth token at startup (printed to console). Every private endpoint — mutating (start/stop training, delete runs, inspect data, validate config) and reading (runs, metrics, system, recipes, SSE streams) — requires an `Authorization: Bearer <token>` header. `/` and `/api/health` stay open so the dashboard can load. CORS is restricted to the served origin. Data inspection is sandboxed to the working directory.
-**The token is not kept across reloads.** The page reads the token from `?token=…` (the `--public` phone URL) or asks for it the first time a request is refused, then holds it in page memory only: never `sessionStorage`, `localStorage`, a cookie or a `window` property. A reload or a new tab therefore asks for it again; paste the token `soup ui` printed (the whole `Authorization: Bearer …` line works too). If you cancel the prompt, the page stays signed out until your next click, which asks again. That is deliberate: a token persisted where page script can read it would turn a future rendering mistake into a token disclosure. It does not protect against script already running in the page; the content policy below is the defence there.
+**The page never stores the token.** The page reads the token from `?token=…` (the `--public` phone URL) or asks for it the first time a request is refused, then holds it in page memory only: never `sessionStorage`, `localStorage`, a cookie or a `window` property. Without the session cookie below, a reload or a new tab therefore asks for it again; paste the token `soup ui` printed (the whole `Authorization: Bearer …` line works too). If you cancel the prompt, the page stays signed out until your next click, which asks again. That is deliberate: a token persisted where page script can read it would turn a future rendering mistake into a token disclosure. It does not protect against script already running in the page; the content policy below is the defence there.
+
+**Session cookie on a loopback bind (#1191).** Opening `http://127.0.0.1:<PORT>/?token=<TOKEN>` checks the token, sets an `HttpOnly; SameSite=Strict; Path=/` cookie named `soup_ui_session_<PORT>` and redirects to the same URL without `token`. The cookie holds a random session id, never the token, so page script cannot read a credential, and a reload or a new tab in that browser stays signed in. The cookie belongs to the hostname you opened: signing in at `127.0.0.1` does not sign in `localhost`, so keep using the same one. It has no expiry, so it ends when the browser session does, and the server keeps the ids only in memory, so every `soup ui` restart ends every session; open the `?token=` URL again to sign back in. A request authenticated by the cookie that is not a `GET` or `HEAD` must carry an `Origin` naming this exact server (scheme, host and port) or it is refused with 403: every port of `127.0.0.1` counts as one site, so `SameSite=Strict` alone would let a page served by another local app on a different port use the cookie. The `Authorization: Bearer` header works exactly as before and needs no `Origin`, so scripts and API clients are unchanged. A wrong token sets nothing and loads the page as before. A browser that blocks cookies for `127.0.0.1` gets the token prompt after the redirect, because the token has already left the URL; paste the token there. With `--public` (or any non-loopback `--host`) no cookie is set or accepted: the phone page keeps the token in page memory, and a reload asks for it again or you re-scan the QR code. **What this does not cover:** cookies are not isolated by port, so any other server on `127.0.0.1` that your browser sends a same-site request to also receives the session cookie. Such a server can replay it outside a browser with any `Origin`, since the `Origin` check only stops browsers, and act as you in the UI, including starting training, until `soup ui` restarts.
YAML-entry request bodies are capped at 1 MiB on `/api/config/validate`,
`/api/train/start`, and `/api/config/from-form`. Larger bodies return HTTP 413
diff --git a/src/soup_cli/ui/app.py b/src/soup_cli/ui/app.py
index e89369fa..ab202688 100644
--- a/src/soup_cli/ui/app.py
+++ b/src/soup_cli/ui/app.py
@@ -10,9 +10,11 @@ import sys
import tempfile
import threading
import time
+from collections import OrderedDict
from pathlib import Path
from types import MappingProxyType
from typing import Mapping, Optional
+from urllib.parse import urlencode
from pydantic import BaseModel as PydanticBaseModel
from pydantic import Field
@@ -24,6 +26,9 @@ STATIC_DIR = Path(__file__).parent / "static"
# Max file read size to prevent memory exhaustion
_MAX_INSPECT_LIMIT = 500
+# #1191: live session ids per app; the oldest is dropped past this.
+_MAX_UI_SESSIONS = 64
+
# #939: cap the body before FastAPI parses it, sized per route (chat/send
# forwards upstream; inspect only ever needs a path and an int). #897 extends
# the same mechanism to every YAML-bearing Web UI route.
@@ -389,7 +394,7 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
from fastapi import Depends, FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
- from fastapi.responses import HTMLResponse
+ from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
# #731: FastAPI's interactive docs describe every route, parameter and
@@ -453,20 +458,73 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
policy_exempt_paths=_POLICY_EXEMPT_PATHS if _docs_enabled else frozenset(),
)
+ # #1191: `/?token=` swaps the token for an HttpOnly session cookie, so a
+ # reload keeps the session without page script ever reading a credential.
+ # The ids live only in this app's memory: a restart ends every session.
+ # Loopback binds only -- `--public` over LAN HTTP keeps the closure flow.
+ # The port is in the name because cookies are not isolated by port.
+ _session_cookie = f"soup_ui_session_{port}"
+ _session_ids: "OrderedDict[str, None]" = OrderedDict()
+ _session_lock = threading.Lock()
+ _session_enabled = _is_loopback(host)
+
+ def _new_session() -> str:
+ session_id = secrets.token_urlsafe(32)
+ with _session_lock:
+ _session_ids[session_id] = None
+ while len(_session_ids) > _MAX_UI_SESSIONS:
+ _session_ids.popitem(last=False)
+ return session_id
+
+ def _session_matches(request: Request) -> bool:
+ """True for a live session cookie; 403 on a cross-origin state change.
+
+ SameSite=Strict does not help here: every port of 127.0.0.1 is one site,
+ so a page on another local port gets the cookie attached. Browsers always
+ send `Origin` on a fetch POST/DELETE, so anything but GET/HEAD must name
+ exactly this server -- scheme, host and port. `check_local_request`
+ cannot do this: it compares hostnames without ports on purpose.
+ """
+ # Defence in depth: `_new_session` only runs behind the same check in
+ # `index()`, so a non-loopback app never holds an id to match.
+ if not _session_enabled:
+ return False
+ value = request.cookies.get(_session_cookie, "").encode("utf-8")
+ if not value:
+ return False
+ with _session_lock:
+ live = list(_session_ids)
+ # Constant-time against every live id, like `_bearer_matches`.
+ matched = False
+ for session_id in live:
+ matched |= secrets.compare_digest(value, session_id.encode("utf-8"))
+ if not matched:
+ return False
+ if request.method not in ("GET", "HEAD"):
+ origin = request.headers.get("Origin", "").lower()
+ expected = f"{request.url.scheme}://{request.headers.get('Host', '')}".lower()
+ if not origin or origin != expected:
+ raise HTTPException(status_code=403, detail="Origin not allowed")
+ return True
+
def _verify_token(request: Request):
- """Verify Bearer token on API endpoints."""
+ """Verify Bearer token (or the #1191 session cookie) on API endpoints."""
auth = request.headers.get("Authorization", "")
# Constant-time compare — a plain != leaks the token byte-by-byte via
# response timing when `soup ui --public` is exposed on a LAN.
- if not _bearer_matches(auth):
- raise HTTPException(status_code=401, detail="Unauthorized")
+ if _bearer_matches(auth) or _session_matches(request):
+ return
+ raise HTTPException(status_code=401, detail="Unauthorized")
def _verify_token_or_ticket(request: Request):
- """Verify Bearer token or consume a single-use ticket for SSE streaming."""
+ """Verify Bearer token, session cookie, or a single-use SSE ticket."""
auth = request.headers.get("Authorization", "")
if auth and _bearer_matches(auth):
return
+ if _session_matches(request):
+ return
+
ticket = request.query_params.get("ticket", "")
if ticket and consume_auth_ticket(ticket):
return
@@ -483,7 +541,24 @@ def create_app(host: str = "127.0.0.1", port: int = 7860):
# --- Static files ---
@app.get("/", response_class=HTMLResponse)
- def index():
+ def index(request: Request):
+ token = request.query_params.get("token")
+ # A wrong token sets nothing: the page loads as before and its prompt
+ # recovers. On a non-loopback bind the page's script still needs
+ # `?token=` from the URL, so there is no redirect either.
+ if _session_enabled and token and _bearer_matches(f"Bearer {token}"):
+ query = urlencode(
+ [(k, v) for k, v in request.query_params.multi_items() if k != "token"]
+ )
+ response = RedirectResponse(
+ request.url.path + (f"?{query}" if query else ""), status_code=303
+ )
+ # No Max-Age/Expires: it ends with the browser session. No Secure:
+ # `soup ui` serves plain HTTP.
+ response.set_cookie(
+ _session_cookie, _new_session(), httponly=True, samesite="strict", path="/"
+ )
+ return response
index_path = STATIC_DIR / "index.html"
return HTMLResponse(content=index_path.read_text(encoding="utf-8"))
diff --git a/src/soup_cli/ui/static/app.js b/src/soup_cli/ui/static/app.js
index 45e688d7..f603c6ea 100644
--- a/src/soup_cli/ui/static/app.js
+++ b/src/soup_cli/ui/static/app.js
@@ -5,7 +5,9 @@ const API = ''; // same origin
// #1136 — The Bearer token lives only in this closure: never on `window`, in
// web storage or in a cookie, so a future rendering mistake cannot read it
// back. Every request goes through authFetch, which adds the header itself and
-// never returns the token. The cost is deliberate: a reload asks for it again.
+// never returns the token. A reload keeps the session only through the
+// HttpOnly cookie `/?token=` sets on a loopback bind (#1191), which this
+// script never touches; otherwise it asks for the token again.
// This narrows what injected script can take away; it does not stop script
// already running in the page (the CSP is the defence there).
const authFetch = (() => {
diff --git a/tests/test_issue1191_ui_session_cookie.py b/tests/test_issue1191_ui_session_cookie.py
new file mode 100644
index 00000000..d260a949
--- /dev/null
+++ b/tests/test_issue1191_ui_session_cookie.py
@@ -0,0 +1,252 @@
+"""#1191 — `soup ui` keeps the session across reloads with an HttpOnly cookie.
+
+`GET /?token=<token>` checks the token, sets a random session id in an HttpOnly
+cookie and redirects to the same URL without `token`. Cookie-authenticated requests
+other than GET/HEAD must carry an `Origin` naming this exact server, because every
+port of 127.0.0.1 is one site and SameSite=Strict does not stop another local app.
+The Bearer header keeps working unchanged for scripted clients.
+"""
+
+from __future__ import annotations
+
+from urllib.parse import parse_qsl, urlencode, urlsplit
+
+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
+
+PORT = 7860
+COOKIE = f"soup_ui_session_{PORT}"
+# TestClient sends `Host: testserver` over http.
+SAME_ORIGIN = "http://testserver"
+
+
+def _client(host: str = "127.0.0.1") -> TestClient:
+ return TestClient(create_app(host=host, port=PORT))
+
+
+def _sign_in(client: TestClient, query: str = ""):
+ return client.get(f"/?token={get_auth_token()}{query}", follow_redirects=False)
+
+
+def _signed_in(host: str = "127.0.0.1") -> TestClient:
+ client = _client(host)
+ assert _sign_in(client).status_code == 303
+ return client
+
+
+def _set_cookie_headers(resp) -> list[str]:
+ return resp.headers.get_list("set-cookie")
+
+
+class TestExchange:
+ def test_token_url_sets_a_session_cookie_and_redirects(self):
+ resp = _sign_in(_client())
+ assert resp.status_code == 303
+ (header,) = _set_cookie_headers(resp)
+ assert header.startswith(f"{COOKIE}=")
+
+ def test_cookie_flags(self):
+ (header,) = _set_cookie_headers(_sign_in(_client()))
+ attrs = [part.strip().lower() for part in header.split(";")[1:]]
+ assert "httponly" in attrs
+ assert "samesite=strict" in attrs
+ assert "path=/" in attrs
+ # A session cookie: it ends with the browser session.
+ assert not any(a.startswith(("max-age", "expires")) for a in attrs)
+ # `soup ui` serves plain HTTP.
+ assert "secure" not in attrs
+
+ def test_cookie_value_is_a_random_id_not_the_token(self):
+ client = _client()
+ first = _sign_in(client).cookies[COOKIE]
+ second = _sign_in(client).cookies[COOKIE]
+ token = get_auth_token()
+ assert token not in first and first not in token
+ assert len(first) >= 43 # token_urlsafe(32)
+ assert first != second
+
+ def test_cookie_name_carries_the_port(self):
+ client = TestClient(create_app(host="127.0.0.1", port=8123))
+ resp = client.get(f"/?token={get_auth_token()}", follow_redirects=False)
+ assert "soup_ui_session_8123" in resp.cookies
+
+ def test_redirect_drops_token_and_keeps_other_params(self):
+ resp = _sign_in(_client(), "&tab=chat&run=a&run=b")
+ location = urlsplit(resp.headers["location"])
+ assert location.path == "/"
+ assert parse_qsl(location.query) == [("tab", "chat"), ("run", "a"), ("run", "b")]
+
+ def test_redirect_without_other_params_has_no_query(self):
+ assert _sign_in(_client()).headers["location"] == "/"
+
+ @pytest.mark.parametrize("token", ["wrong-token", "", "tést"])
+ def test_wrong_token_sets_nothing_and_serves_the_page(self, token):
+ resp = _client().get(f"/?token={token}", follow_redirects=False)
+ assert resp.status_code == 200
+ assert "<html" in resp.text.lower()
+ assert not _set_cookie_headers(resp)
+
+ def test_plain_page_sets_nothing(self):
+ resp = _client().get("/", follow_redirects=False)
+ assert resp.status_code == 200
+ assert not _set_cookie_headers(resp)
+
+
+class TestReloadKeepsTheSession:
+ def test_cookie_alone_authenticates_a_read(self):
+ client = _signed_in()
+ assert client.get("/api/train/status").status_code == 200
+
+ def test_no_cookie_is_still_refused(self):
+ assert _client().get("/api/train/status").status_code == 401
+
+ def test_unknown_cookie_is_refused(self):
+ client = _client()
+ client.cookies.set(COOKIE, "not-a-live-session-id")
+ assert client.get("/api/train/status").status_code == 401
+
+ def test_cookie_opens_the_sse_stream(self):
+ resp = _signed_in().get("/api/train/logs")
+ assert resp.status_code == 200
+ assert "event: done" in resp.text
+
+ def test_cookie_can_still_fetch_an_sse_ticket(self):
+ resp = _signed_in().post("/api/auth/ticket", headers={"Origin": SAME_ORIGIN})
+ assert resp.status_code == 200
+ assert resp.json()["ticket"]
+
+ def test_restart_ends_every_session(self):
+ old = _signed_in()
+ session_id = old.cookies[COOKIE]
+ restarted = _client()
+ restarted.cookies.set(COOKIE, session_id)
+ assert restarted.get("/api/train/status").status_code == 401
+
+ def test_oldest_session_is_dropped_past_the_cap(self, monkeypatch):
+ monkeypatch.setattr(ui_app, "_MAX_UI_SESSIONS", 2)
+ client = _client()
+ first = _sign_in(client).cookies[COOKIE]
+ _sign_in(client)
+ _sign_in(client)
+ probe = TestClient(client.app)
+ probe.cookies.set(COOKIE, first)
+ assert probe.get("/api/train/status").status_code == 401
+
+
+class TestOriginCheck:
+ def test_same_origin_cookie_post_is_allowed(self):
+ resp = _signed_in().post("/api/auth/ticket", headers={"Origin": SAME_ORIGIN})
+ assert resp.status_code == 200
+
+ @pytest.mark.parametrize(
+ "origin",
+ [
+ "http://testserver:9999", # another port of the same host
+ "https://testserver", # another scheme
+ "http://evil.example",
+ "null",
+ ],
+ )
+ def test_cross_origin_cookie_post_is_refused(self, origin):
+ resp = _signed_in().post("/api/auth/ticket", headers={"Origin": origin})
+ assert resp.status_code == 403
+
+ def test_cookie_post_without_origin_is_refused(self):
+ assert _signed_in().post("/api/auth/ticket").status_code == 403
+
+ def test_cookie_delete_without_origin_is_refused(self):
+ assert _signed_in().delete("/api/runs/some-run").status_code == 403
+
+ def test_bearer_post_without_origin_still_works(self):
+ resp = _client().post(
+ "/api/auth/ticket", headers={"Authorization": f"Bearer {get_auth_token()}"}
+ )
+ assert resp.status_code == 200
+
+ def test_bearer_post_with_a_foreign_origin_still_works(self):
+ # Scripted clients are unchanged: the Bearer header is not sent automatically.
+ resp = _signed_in().post(
+ "/api/auth/ticket",
+ headers={
+ "Authorization": f"Bearer {get_auth_token()}",
+ "Origin": "http://testserver:9999",
+ },
+ )
+ assert resp.status_code == 200
+
+
+class TestPublicBind:
+ def test_no_cookie_and_no_redirect_on_a_non_loopback_bind(self):
+ # The phone page's script reads `?token=` itself, so it must stay in the URL.
+ resp = _sign_in(_client("0.0.0.0"))
+ assert resp.status_code == 200
+ assert not _set_cookie_headers(resp)
+
+ def test_cookie_is_not_accepted_on_a_non_loopback_bind(self):
+ client = _client("0.0.0.0")
+ client.cookies.set(COOKIE, "anything")
+ assert client.get("/api/train/status").status_code == 401
+
+
+class TestNoCredentialedCors:
+ @pytest.mark.parametrize("host", ["127.0.0.1", "0.0.0.0"])
+ def test_no_allow_credentials_on_any_response(self, host):
+ client = _signed_in() if host == "127.0.0.1" else _client(host)
+ origin = f"http://127.0.0.1:{PORT}"
+ responses = [
+ client.get("/api/train/status", headers={"Origin": origin}),
+ client.get("/api/runs/x", headers={"Origin": "http://127.0.0.1:1"}),
+ client.options(
+ "/api/auth/ticket",
+ headers={"Origin": origin, "Access-Control-Request-Method": "POST"},
+ ),
+ _sign_in(client),
+ ]
+ for resp in responses:
+ assert "access-control-allow-credentials" not in resp.headers
+
+def _spy_compare_digest(monkeypatch) -> list:
+ seen = []
+ real = ui_app.secrets.compare_digest
+
+ def spy(a, b):
+ seen.append((a, b))
+ return real(a, b)
+
+ monkeypatch.setattr(ui_app.secrets, "compare_digest", spy)
+ return seen
+
+
+class TestConstantTimeComparisons:
+ def test_exchange_compares_the_token_in_constant_time(self, monkeypatch):
+ seen = _spy_compare_digest(monkeypatch)
+ assert _sign_in(_client()).status_code == 303
+ presented = f"Bearer {get_auth_token()}".encode("utf-8")
+ assert any(a == presented and isinstance(b, bytes) for a, b in seen), seen
+
+ def test_session_cookie_is_compared_in_constant_time(self, monkeypatch):
+ client = _signed_in()
+ session_id = client.cookies[COOKIE].encode("utf-8")
+ seen = _spy_compare_digest(monkeypatch)
+ assert client.get("/api/train/status").status_code == 200
+ assert any(a == session_id and isinstance(b, bytes) for a, b in seen), seen
+
+
+class TestRedirectStaysOnThisServer:
+ def test_hostile_parameters_never_become_the_redirect_target(self):
+ hostile = [
+ ("next", "//evil.example/"),
+ ("redirect", "http://evil.example/"),
+ ("url", "\\\\evil.example"),
+ ("x", "a\r\nSet-Cookie: pwn=1"),
+ ]
+ resp = _sign_in(_client(), "&" + urlencode(hostile))
+ assert resp.status_code == 303
+ parts = urlsplit(resp.headers["location"])
+ assert parts.scheme == "" and parts.netloc == "", resp.headers["location"]
+ assert parts.path == "/"
+ assert parse_qsl(parts.query) == hostile
+ assert all("pwn" not in c for c in _set_cookie_headers(resp))