Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(web): engine-agnostic WebSocket auth — readable rejects + one-time tickets (BUG-065)

Ruben Lütke3b979d7c608c
diff --git a/jarvis/ui/web/fast_bootstrap.py b/jarvis/ui/web/fast_bootstrap.py
index eba72047cb..158eba5901 100644
--- a/jarvis/ui/web/fast_bootstrap.py
+++ b/jarvis/ui/web/fast_bootstrap.py
@@ -87,7 +87,16 @@ class FastBootstrap:
@property
def app(self) -> Any:
- """The bootstrap ASGI app (handed to uvicorn / driven directly in tests)."""
+ """The SECURED bootstrap entry, for tests and external embedders.
+
+ NOT what :meth:`serve` binds. Production serves :meth:`_asgi` directly
+ (see the comment in :meth:`_start_server`): the warming surface is
+ deliberately credential-free — static shell, health, onboarding
+ fastpath, accept-then-close 1013 websockets — and every held request
+ delegates to the real app, which applies its own SurfaceSecurity.
+ This wrapped variant adds the boundary in front of the SAME warming
+ surface for callers that embed the bootstrap somewhere less trusted.
+ """
return self._entry_app
async def _entry_app(self, scope: dict, receive: Any, send: Any) -> None:
@@ -95,6 +104,18 @@ class FastBootstrap:
if self._ready.is_set() and self._full["app"] is not None:
await self._full["app"](scope, receive, send)
return
+ if scope["type"] == "websocket":
+ # Answer a warming websocket BEFORE the security boundary: WebKit
+ # engines drop the HttpOnly session cookie from WS handshakes
+ # (BUG-065), so an auth check here would reject exactly the
+ # clients this "try again later" is meant for. Accept-then-close
+ # leaks nothing ("warming" is already public via /api/health) and
+ # gives every engine a readable 1013 instead of an opaque 1006
+ # that renders as OFFLINE.
+ await receive() # consume the websocket.connect event
+ await send({"type": "websocket.accept"})
+ await send({"type": "websocket.close", "code": 1013})
+ return
await self._secured_app(scope, receive, send)
async def _asgi(self, scope: dict, receive: Any, send: Any) -> None:
@@ -241,6 +262,9 @@ class FastBootstrap:
await send({"type": "http.response.body", "body": body})
elif kind == "websocket":
# 1013 = "try again later" → clients reconnect once the app is up.
+ # Accept first: a close before the accept surfaces as an opaque
+ # 1006 in every browser, which the UI reads as OFFLINE (BUG-065).
+ await send({"type": "websocket.accept"})
await send({"type": "websocket.close", "code": 1013})
# ---- static frontend (served while warming, no black screen) -----------
@@ -373,6 +397,14 @@ class FastBootstrap:
# (``iscoroutinefunction(method.__call__)`` is False), which would call
# it as ``app(scope)`` and crash. A module-level-style closure is
# correctly detected as ASGI3.
+ #
+ # DELIBERATELY ``_asgi`` and not the secured ``self.app``: the warming
+ # surface must stay credential-free. Gating it on the session cookie
+ # would race the desktop token injection at every boot (AuthGate would
+ # 401 before pywebview delivers the token) and would go dark for
+ # WebKit websockets entirely (BUG-065). Everything held during warm-up
+ # is delegated to the real app afterwards, which enforces its own
+ # SurfaceSecurity — so nothing protected is ever served from here.
_self = self
async def _asgi3(scope: dict, receive: Any, send: Any) -> None:
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 28cb571085..5fd5c7a397 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -333,7 +333,18 @@ async def _run_headless(args) -> int:
await send({"type": "lifespan.shutdown.complete"})
return
return
- # http / websocket: hold until the full app is ready, then delegate.
+ # Websocket while warming: answer NOW with accept-then-close 1013.
+ # Holding the handshake open makes browsers time out after tens of
+ # seconds and report an opaque 1006, so a headless boot watched from a
+ # browser rendered as a long spurious OFFLINE instead of "starting"
+ # (the same contract FastBootstrap serves on the desktop; BUG-065).
+ if kind == "websocket" and not _full_ready.is_set():
+ await receive() # consume the websocket.connect event
+ await send({"type": "websocket.accept"})
+ await send({"type": "websocket.close", "code": 1013})
+ return
+
+ # http: hold until the full app is ready, then delegate.
if not _full_ready.is_set():
try:
await asyncio.wait_for(_full_ready.wait(), timeout=120.0)
@@ -367,6 +378,8 @@ async def _run_headless(args) -> int:
await send({"type": "http.response.body", "body": body})
elif kind == "websocket":
# 1013 = "try again later" → clients reconnect once the app is up.
+ # Accept first so browsers read the code instead of an opaque 1006.
+ await send({"type": "websocket.accept"})
await send({"type": "websocket.close", "code": 1013})
# Cloud-first: a headless VPS / container must be reachable by a remote
diff --git a/jarvis/ui/web/surface_security.py b/jarvis/ui/web/surface_security.py
index 59eb6fe681..85fdbf885d 100644
--- a/jarvis/ui/web/surface_security.py
+++ b/jarvis/ui/web/surface_security.py
@@ -20,10 +20,11 @@ import re
import secrets
import sys
import threading
+import time
from collections.abc import Awaitable, Callable, Iterable, MutableMapping
from http.cookies import CookieError, SimpleCookie
from typing import Any, Literal
-from urllib.parse import urlsplit
+from urllib.parse import parse_qs, urlsplit
COOKIE_NAME = "jarvis_session"
@@ -67,6 +68,51 @@ def _consume_bootstrap_token(token: str) -> bool:
return True
+# One-time WebSocket handshake tickets. WebKit (Safari / WKWebView on macOS,
+# WebKitGTK on Linux) does not attach the HttpOnly + SameSite=Strict session
+# cookie to a WebSocket handshake — the same cookie that authenticates every
+# fetch — so cookie-only WS auth silently bricks the live event channel on
+# every non-Chromium engine (BUG-065). A ticket is minted over an
+# authenticated HTTP request (where the cookie IS sent on all engines),
+# expires quickly, and is consumed on first presentation, so a leaked URL
+# cannot be replayed. Process-local and shared module-globally so a ticket
+# minted by the fast-boot bootstrap's boundary instance stays valid for the
+# real app's boundary instance after the serve-first handoff.
+_WS_TICKET_LOCK = threading.Lock()
+_WS_TICKETS: dict[str, float] = {}
+_WS_TICKET_TTL_S = 60.0
+_WS_TICKET_MAX_LIVE = 256 # runaway-mint guard; a UI needs a handful
+
+
+def _mint_ws_ticket() -> str | None:
+ """Mint a single-use, short-lived WebSocket ticket (None when saturated)."""
+ now = time.monotonic()
+ with _WS_TICKET_LOCK:
+ expired = [ticket for ticket, expiry in _WS_TICKETS.items() if expiry < now]
+ for ticket in expired:
+ del _WS_TICKETS[ticket]
+ if len(_WS_TICKETS) >= _WS_TICKET_MAX_LIVE:
+ return None
+ ticket = secrets.token_urlsafe(32)
+ _WS_TICKETS[ticket] = now + _WS_TICKET_TTL_S
+ return ticket
+
+
+def _consume_ws_ticket(ticket: str) -> bool:
+ """Atomically consume a live ticket; expired or replayed tickets fail."""
+ if not ticket:
+ return False
+ with _WS_TICKET_LOCK:
+ expiry = _WS_TICKETS.pop(ticket, None)
+ return expiry is not None and expiry >= time.monotonic()
+
+
+def reset_ws_tickets() -> None:
+ """Test hook: clears the ticket store entirely."""
+ with _WS_TICKET_LOCK:
+ _WS_TICKETS.clear()
+
+
def _iter_values(value: str | Iterable[str] | None) -> tuple[str, ...]:
if value is None:
return ()
@@ -419,6 +465,14 @@ def _default_session_validator(token: str) -> bool:
return False
+#: Scope key stamped by :class:`SurfaceSecurity` after it consumed a valid
+#: one-time WebSocket ticket. Tickets are single-use, so a route-level
+#: re-check can never re-validate the raw credential — it must honor this
+#: process-internal stamp instead. Clients cannot forge it: ASGI scopes are
+#: built by the server from the wire request; arbitrary keys never cross it.
+WS_TICKET_SCOPE_KEY = "jarvis.ws_ticket_authenticated"
+
+
def credentials_valid(scope: Scope) -> bool:
"""Validate the credential carried by ``scope`` without Host/Origin checks.
@@ -426,8 +480,13 @@ def credentials_valid(scope: Scope) -> bool:
A Bearer may be either the persistent control key or a registered ephemeral
UI token. Cookie credentials are ephemeral UI tokens. Supplying any
malformed Authorization header is authoritative and prevents cookie
- fallback.
+ fallback. A websocket the outer boundary authenticated via a one-time
+ ticket (BUG-065: WebKit engines drop the HttpOnly session cookie from WS
+ handshakes) carries the boundary's scope stamp — the ticket itself was
+ already consumed and cannot be checked twice.
"""
+ if scope.get(WS_TICKET_SCOPE_KEY) is True:
+ return True
bearer_present, bearer = _presented_bearer(scope)
if bearer_present:
if bearer is None:
@@ -450,8 +509,18 @@ async def _reject(
detail: str,
ws_code: int,
authenticate: bool = False,
+ receive: Receive | None = None,
) -> None:
if scope.get("type") == "websocket":
+ # Accept, then close with the specific code. Closing BEFORE the accept
+ # turns into an opaque HTTP handshake failure that every browser
+ # reports as code 1006 — indistinguishable from "server down", which
+ # made a WebKit auth miss render as a permanent OFFLINE (BUG-065).
+ # Accepting first costs nothing, leaks nothing, and lets the client
+ # read the real 4401/4403 and react (mint a ticket, stop retrying).
+ if receive is not None:
+ await receive() # consume the pending websocket.connect event
+ await send({"type": "websocket.accept"})
await send({"type": "websocket.close", "code": ws_code, "reason": detail})
return
body = json.dumps({"detail": detail}, separators=(",", ":")).encode("utf-8")
@@ -472,7 +541,9 @@ async def _reject(
await send({"type": "http.response.body", "body": body})
-async def reject_host(scope: Scope, send: Send) -> None:
+async def reject_host(
+ scope: Scope, send: Send, receive: Receive | None = None
+) -> None:
"""Reject an untrusted Host for HTTP or WebSocket before downstream code."""
await _reject(
scope,
@@ -480,10 +551,13 @@ async def reject_host(scope: Scope, send: Send) -> None:
status_code=400,
detail="Untrusted Host header.",
ws_code=4403,
+ receive=receive,
)
-async def reject_origin(scope: Scope, send: Send) -> None:
+async def reject_origin(
+ scope: Scope, send: Send, receive: Receive | None = None
+) -> None:
"""Reject a foreign, null, malformed, or required-but-missing Origin."""
await _reject(
scope,
@@ -491,10 +565,13 @@ async def reject_origin(scope: Scope, send: Send) -> None:
status_code=403,
detail="Untrusted Origin header.",
ws_code=4403,
+ receive=receive,
)
-async def reject_unauthorized(scope: Scope, send: Send) -> None:
+async def reject_unauthorized(
+ scope: Scope, send: Send, receive: Receive | None = None
+) -> None:
"""Reject a request that lacks a valid Jarvis credential."""
await _reject(
scope,
@@ -503,9 +580,30 @@ async def reject_unauthorized(scope: Scope, send: Send) -> None:
detail="Invalid or missing Jarvis credential.",
ws_code=4401,
authenticate=True,
+ receive=receive,
)
+def _presented_ws_ticket(scope: Scope) -> str | None:
+ """Extract the single ``ticket`` query value from a websocket scope.
+
+ Returns ``None`` when absent; an ambiguous (repeated) or empty value is
+ returned as ``""`` so the caller rejects instead of falling back to other
+ credentials — presenting a ticket is authoritative, like a Bearer header.
+ """
+ raw = scope.get("query_string", b"")
+ try:
+ query = parse_qs(bytes(raw).decode("latin-1"), keep_blank_values=True)
+ except (AttributeError, UnicodeDecodeError, ValueError):
+ return None
+ values = query.get("ticket")
+ if values is None:
+ return None
+ if len(values) != 1:
+ return ""
+ return values[0]
+
+
def _is_static_request(path: str, method: str) -> bool:
if method not in _SAFE_HTTP_METHODS:
return False
@@ -764,6 +862,66 @@ class SurfaceSecurity:
)
await send({"type": "http.response.body", "body": b""})
+ async def _handle_ws_ticket_request(
+ self, scope: Scope, receive: Receive, send: Send
+ ) -> None:
+ """Mint a one-time WebSocket ticket for an already-authenticated caller.
+
+ The ticket exists because WebKit engines drop the HttpOnly session
+ cookie from WebSocket handshakes (BUG-065): the browser proves its
+ session over plain HTTP here — where the cookie IS sent — and gets a
+ short-lived, single-use credential its next WS handshake can carry.
+ Framework-free and implemented at this boundary (like the session
+ exchange above) so it exists identically behind the fast-boot
+ bootstrap and the full app.
+ """
+ if not is_secure_or_loopback(scope):
+ # Mirror the session exchange: a bearer credential must never be
+ # minted over sniffable plain HTTP on a non-loopback bind.
+ await _reject(
+ scope,
+ send,
+ status_code=403,
+ detail="WebSocket tickets require HTTPS or direct loopback.",
+ ws_code=4403,
+ receive=receive,
+ )
+ return
+ auth_kind = self._authenticate(scope)
+ if auth_kind is None:
+ await reject_unauthorized(scope, send, receive)
+ return
+ if auth_kind == "session" and not self.origin_is_trusted(scope, required=True):
+ await reject_origin(scope, send, receive)
+ return
+ ticket = _mint_ws_ticket()
+ if ticket is None:
+ await _reject(
+ scope,
+ send,
+ status_code=503,
+ detail="WebSocket ticket store is saturated; retry shortly.",
+ ws_code=1013,
+ receive=receive,
+ )
+ return
+ body = json.dumps(
+ {"ticket": ticket, "expires_in": int(_WS_TICKET_TTL_S)},
+ separators=(",", ":"),
+ ).encode("utf-8")
+ await send(
+ {
+ "type": "http.response.start",
+ "status": 200,
+ "headers": [
+ (b"content-type", b"application/json"),
+ (b"content-length", str(len(body)).encode("ascii")),
+ (b"cache-control", b"no-store"),
+ ],
+ }
+ )
+ await send({"type": "http.response.body", "body": body})
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
kind = scope.get("type")
if kind not in {"http", "websocket"}:
@@ -771,7 +929,7 @@ class SurfaceSecurity:
return
if not self.host_is_trusted(scope):
- await reject_host(scope, send)
+ await reject_host(scope, send, receive)
return
path = str(scope.get("path", "") or "")
@@ -781,7 +939,7 @@ class SurfaceSecurity:
# A supplied Origin is never advisory: malformed, null, or foreign
# values fail even on otherwise-public static and health requests.
if not self.origin_is_trusted(scope):
- await reject_origin(scope, send)
+ await reject_origin(scope, send, receive)
return
if kind == "websocket" and path == "/api/telephony/media":
@@ -794,16 +952,19 @@ class SurfaceSecurity:
# them without weakening the actual request's credential check.
if method == "OPTIONS":
if not self.origin_is_trusted(scope, required=True):
- await reject_origin(scope, send)
+ await reject_origin(scope, send, receive)
return
await self.app(scope, receive, send)
return
if path == "/api/ui/session" and method == "POST":
await self._handle_session_request(scope, receive, send)
return
+ if path == "/api/ui/ws-ticket" and method == "POST":
+ await self._handle_ws_ticket_request(scope, receive, send)
+ return
if path == "/api/ui/shell-painted" and method == "POST":
if not self.origin_is_trusted(scope, required=True):
- await reject_origin(scope, send)
+ await reject_origin(scope, send, receive)
return
await self.app(scope, receive, send)
return
@@ -813,28 +974,58 @@ class SurfaceSecurity:
auth_kind = self._authenticate(scope)
if auth_kind is None:
- await reject_unauthorized(scope, send)
+ await reject_unauthorized(scope, send, receive)
return
if auth_kind == "session" and method in _UNSAFE_HTTP_METHODS:
if not self.origin_is_trusted(scope, required=True):
- await reject_origin(scope, send)
+ await reject_origin(scope, send, receive)
return
await self.app(scope, receive, send)
return
if _mission_inner_auth_socket(path):
if not self.origin_is_trusted(scope, required=True):
- await reject_origin(scope, send)
+ await reject_origin(scope, send, receive)
return
await self.app(scope, receive, send)
return
+ # A presented ticket is authoritative (no cookie fallback), mirroring
+ # the Bearer rule: WebKit engines cannot attach the HttpOnly session
+ # cookie to a WS handshake, so this one-time credential — minted via
+ # POST /api/ui/ws-ticket over cookie-authenticated HTTP — is how a
+ # non-Chromium browser opens the live event channel (BUG-065).
+ # Transport rule mirrors the mint: HTTPS/WSS or direct loopback only.
+ ticket = _presented_ws_ticket(scope)
+ if ticket is not None:
+ if not is_secure_or_loopback(scope):
+ await _reject(
+ scope,
+ send,
+ status_code=403,
+ detail="WebSocket tickets require HTTPS or direct loopback.",
+ ws_code=4403,
+ receive=receive,
+ )
+ return
+ if not _consume_ws_ticket(ticket):
+ await reject_unauthorized(scope, send, receive)
+ return
+ if not self.origin_is_trusted(scope, required=True):
+ await reject_origin(scope, send, receive)
+ return
+ # Stamp the scope so route-level defense-in-depth re-checks
+ # (credentials_valid) recognize the already-consumed ticket.
+ scope[WS_TICKET_SCOPE_KEY] = True
+ await self.app(scope, receive, send)
+ return
+
auth_kind = self._authenticate(scope)
if auth_kind is None:
- await reject_unauthorized(scope, send)
+ await reject_unauthorized(scope, send, receive)
return
if auth_kind == "session" and not self.origin_is_trusted(scope, required=True):
- await reject_origin(scope, send)
+ await reject_origin(scope, send, receive)
return
await self.app(scope, receive, send)
@@ -842,6 +1033,7 @@ class SurfaceSecurity:
__all__ = [
"COOKIE_NAME",
"SurfaceSecurity",
+ "WS_TICKET_SCOPE_KEY",
"append_session_cookie",
"build_set_cookie_header",
"credentials_valid",
@@ -849,6 +1041,7 @@ __all__ = [
"reject_host",
"reject_origin",
"reject_unauthorized",
+ "reset_ws_tickets",
"scope_host_is_trusted",
"scope_origin_is_trusted",
]
diff --git a/tests/unit/ui/web/test_fast_bootstrap_ws.py b/tests/unit/ui/web/test_fast_bootstrap_ws.py
index ed0fe83564..a03fdd2c2e 100644
--- a/tests/unit/ui/web/test_fast_bootstrap_ws.py
+++ b/tests/unit/ui/web/test_fast_bootstrap_ws.py
@@ -35,3 +35,27 @@ async def test_warming_ws_is_fast_closed_with_1013() -> None:
finally:
await bs.stop()
logging.disable(logging.NOTSET)
+
+
+async def test_warming_ws_gets_1013_even_without_any_credential() -> None:
+ """The macOS/Linux desktop reality (BUG-065): WebKit engines drop the
+ HttpOnly session cookie from WS handshakes. A warming socket must still
+ receive the readable accept-then-close 1013 — an auth reject here would
+ surface as an opaque 1006 and render the boot as a spurious OFFLINE."""
+ logging.disable(logging.CRITICAL)
+ bs = FastBootstrap(session_token=_TOKEN)
+ await bs.serve("127.0.0.1", 47996) # NOT set_app -> warming
+ try:
+ async with websockets.connect(
+ "ws://127.0.0.1:47996/ws",
+ open_timeout=3,
+ origin="http://127.0.0.1:47996",
+ # No Cookie header at all — the cookie-less WebKit handshake.
+ ) as ws:
+ with pytest.raises(websockets.ConnectionClosed) as exc:
+ await asyncio.wait_for(ws.recv(), timeout=3)
+ assert exc.value.code == 1013
+ finally:
+ await bs.stop()
+ logging.disable(logging.NOTSET)
diff --git a/tests/unit/ui_web/test_surface_security.py b/tests/unit/ui_web/test_surface_security.py
index 4d4a318126..68b4a38010 100644
--- a/tests/unit/ui_web/test_surface_security.py
+++ b/tests/unit/ui_web/test_surface_security.py
@@ -15,11 +15,14 @@ from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
from jarvis.core import control_key
+from jarvis.ui.web import surface_security
from jarvis.ui.web.missions_auth import register_token, reset_tokens
from jarvis.ui.web.surface_security import (
COOKIE_NAME,
SurfaceSecurity,
build_set_cookie_header,
+ credentials_valid,
+ reset_ws_tickets,
)
pytestmark = pytest.mark.no_auto_web_auth
@@ -57,12 +60,14 @@ class _ProbeApp:
@pytest.fixture(autouse=True)
def _auth_state(monkeypatch: pytest.MonkeyPatch):
reset_tokens()
+ reset_ws_tickets()
register_token(_SESSION_TOKEN)
monkeypatch.setattr(control_key, "get_control_key", lambda: _CONTROL_KEY)
try:
yield
finally:
reset_tokens()
+ reset_ws_tickets()
def _client(
@@ -509,14 +514,17 @@ def test_public_telephony_websocket_allows_a_non_browser_without_origin() -> Non
def test_public_telephony_websocket_still_enforces_host_and_supplied_origin(
headers: dict[str, str],
) -> None:
+ # Rejects are accept-then-close so the client can read the specific code:
+ # a close before the accept surfaces as an opaque 1006 in every browser,
+ # which the UI cannot distinguish from "server down" (BUG-065).
client, inner = _client()
- with pytest.raises(WebSocketDisconnect) as exc_info:
- with client.websocket_connect(
- "/api/telephony/media",
- headers=headers,
- ):
- pass
+ with client.websocket_connect(
+ "/api/telephony/media",
+ headers=headers,
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ websocket.receive_json()
assert exc_info.value.code == 4403
assert inner.scopes == []
@@ -544,3 +552,227 @@ def test_public_callback_allowlist_is_method_and_path_exact(
assert response.status_code == 401
assert inner.scopes == []
+
+
+# ---------------------------------------------------------------------------
+# One-time WebSocket tickets + readable websocket rejects (BUG-065).
+#
+# WebKit engines (Safari / WKWebView on macOS, WebKitGTK on Linux) do not
+# attach the HttpOnly session cookie to a WebSocket handshake, so cookie-only
+# WS auth bricks the live event channel on every non-Chromium browser. The
+# boundary therefore (a) closes rejected sockets AFTER the accept so the
+# specific 4401/4403 is readable, and (b) accepts a short-lived single-use
+# ticket minted over cookie-authenticated plain HTTP.
+# ---------------------------------------------------------------------------
+
+
+def test_cookieless_websocket_reject_is_a_readable_4401() -> None:
+ client, inner = _client()
+
+ with client.websocket_connect("/ws", headers=_headers()) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ websocket.receive_json()
+
+ assert exc_info.value.code == 4401
+ assert inner.scopes == []
+
+
+def test_ws_ticket_mint_requires_a_credential() -> None:
+ client, inner = _client()
+
+ response = client.post("/api/ui/ws-ticket", headers=_headers())
+
+ assert response.status_code == 401
+ assert inner.scopes == []
+
+
+def test_session_ws_ticket_mint_requires_an_origin() -> None:
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+
+ response = client.post("/api/ui/ws-ticket", headers=_headers(origin=None))
+
+ assert response.status_code == 403
+ assert inner.scopes == []
+
+
+def test_ws_ticket_opens_the_socket_without_any_cookie() -> None:
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ minted = client.post("/api/ui/ws-ticket", headers=_headers())
+ assert minted.status_code == 200
+ assert minted.headers["cache-control"] == "no-store"
+ ticket = minted.json()["ticket"]
+ assert isinstance(ticket, str) and len(ticket) >= 32
+
+ # The WS handshake itself presents NO cookie — the WebKit reality.
+ client.cookies.clear()
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}", headers=_headers()
+ ) as websocket:
+ assert websocket.receive_json() == {"type": "probe"}
+
+ assert len(inner.scopes) == 1
+
+
+def test_ws_ticket_is_single_use() -> None:
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ ticket = client.post("/api/ui/ws-ticket", headers=_headers()).json()["ticket"]
+ client.cookies.clear()
+
+ with client.websocket_connect(f"/ws?ticket={ticket}", headers=_headers()):
+ pass
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}", headers=_headers()
+ ) as replay:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ replay.receive_json()
+
+ assert exc_info.value.code == 4401
+ assert len(inner.scopes) == 1
+
+
+def test_expired_ws_ticket_is_rejected() -> None:
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ ticket = client.post("/api/ui/ws-ticket", headers=_headers()).json()["ticket"]
+ client.cookies.clear()
+ surface_security._WS_TICKETS[ticket] = 0.0 # force expiry
+
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}", headers=_headers()
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ websocket.receive_json()
+
+ assert exc_info.value.code == 4401
+ assert inner.scopes == []
+
+
+def test_ws_ticket_from_a_hostile_origin_is_rejected_before_consumption() -> None:
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ ticket = client.post("/api/ui/ws-ticket", headers=_headers()).json()["ticket"]
+ client.cookies.clear()
+
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}",
+ headers=_headers(origin="https://attacker.example"),
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ websocket.receive_json()
+
+ # The global Origin gate fires before ticket handling: the hostile page
+ # is rejected outright and the unconsumed ticket stays valid for the
+ # legitimate same-origin owner.
+ assert exc_info.value.code == 4403
+ assert inner.scopes == []
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}", headers=_headers()
+ ) as legitimate:
+ assert legitimate.receive_json() == {"type": "probe"}
+ assert len(inner.scopes) == 1
+
+
+def test_ws_ticket_without_any_origin_is_consumed_and_rejected() -> None:
+ # required=True on the ticket path: a browser always sends an Origin on a
+ # WS handshake, so an origin-less ticket presentation is not a browser —
+ # native clients authenticate with a Bearer instead. Fail-closed AND burn
+ # the ticket so it cannot be probed origin-less and replayed later.
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ ticket = client.post("/api/ui/ws-ticket", headers=_headers()).json()["ticket"]
+ client.cookies.clear()
+
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}", headers=_headers(origin=None)
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ websocket.receive_json()
+ assert exc_info.value.code == 4403
+
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}", headers=_headers()
+ ) as replay:
+ with pytest.raises(WebSocketDisconnect) as replay_exc:
+ replay.receive_json()
+ assert replay_exc.value.code == 4401
+ assert inner.scopes == []
+
+
+def test_ws_ticket_never_authenticates_plain_http() -> None:
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ ticket = client.post("/api/ui/ws-ticket", headers=_headers()).json()["ticket"]
+ client.cookies.clear()
+
+ response = client.get(f"/api/config?ticket={ticket}", headers=_headers())
+
+ assert response.status_code == 401
+ assert inner.scopes == []
+
+
+def test_ticket_authenticated_socket_passes_route_level_recheck() -> None:
+ """Tool-capable sockets (/ws/audio, workspace PTY) re-check credentials
+ route-locally via ``credentials_valid``. A ticket is consumed by the outer
+ boundary and cannot be validated twice, so the boundary stamps the scope
+ and the re-check must honor it — otherwise the exact WebKit clients the
+ ticket exists for (BUG-065) get accepted by the boundary and then closed
+ 4401 by the route itself."""
+ client, inner = _client()
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ ticket = client.post("/api/ui/ws-ticket", headers=_headers()).json()["ticket"]
+ client.cookies.clear()
+
+ with client.websocket_connect(
+ f"/ws/audio?ticket={ticket}", headers=_headers()
+ ) as websocket:
+ assert websocket.receive_json() == {"type": "probe"}
+
+ assert len(inner.scopes) == 1
+ assert credentials_valid(inner.scopes[0]) is True
+
+
+def test_non_loopback_plain_http_ws_ticket_mint_is_rejected() -> None:
+ public_url = "http://jarvis.example"
+ client, inner = _client(
+ base_url=public_url,
+ peer=("203.0.113.9", 50_000),
+ public_urls=(public_url,),
+ )
+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+
+ response = client.post(
+ "/api/ui/ws-ticket",
+ headers=_headers(origin=public_url, host="jarvis.example"),
+ )
+
+ assert response.status_code == 403
+ assert inner.scopes == []
+
+
+def test_non_loopback_plain_ws_ticket_presentation_is_rejected() -> None:
+ # Mint legitimately over loopback, then present the ticket over a
+ # sniffable plain-HTTP non-loopback transport: refused, unconsumed.
+ loopback_client, _ = _client()
+ loopback_client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)
+ ticket = loopback_client.post(
+ "/api/ui/ws-ticket", headers=_headers()
+ ).json()["ticket"]
+
+ public_url = "http://jarvis.example"
+ client, inner = _client(
+ base_url=public_url,
+ peer=("203.0.113.9", 50_000),
+ public_urls=(public_url,),
+ )
+ with client.websocket_connect(
+ f"/ws?ticket={ticket}",
+ headers=_headers(origin=public_url, host="jarvis.example"),
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ websocket.receive_json()
+
+ assert exc_info.value.code == 4403
+ assert inner.scopes == []