Skip to content

The agent that grows with you

fix(webapp): the Webapp's routes exist only on the surfaces that use them

emozilla3895357a6a8f
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index da9274e2180..2252cba5872 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -22,7 +22,7 @@ from datetime import datetime
from pathlib import Path, PurePosixPath
from typing import Any, Dict, Optional
-from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
+from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
from hermes_cli import web_server_file_tickets as file_tickets
@@ -33,6 +33,7 @@ from hermes_cli.staged_uploads import (
)
from hermes_cli.web_deps import late
from hermes_cli.web_upload_limit import CHAT_IMAGE_MAX_BYTES
+from hermes_cli.web_server_surface import route_on
from hermes_cli.web_server_files import (
SANDBOX_NOT_FOUND, _agent_fs_path, _fs_path, _hosted_fs_read_guard, _is_unmapped_container_path,
_managed_file_entry, _managed_response_meta, _resolve_managed_path,
@@ -738,7 +739,7 @@ def _pin_ticket_file(authority: file_tickets.FileAuthority, checked):
raise HTTPException(status_code=403, detail="File is not readable") from exc
[email protected]("/api/files/ticket")
[email protected]("/api/files/ticket", dependencies=[Depends(route_on("browser_files"))])
async def issue_file_ticket(payload: FileTicketRequest, request: Request):
"""Ticket a browser download/media URL instead of putting the session token in it."""
from hermes_cli.web_routers.sessions import _history_profile_home
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 605341e6f24..73323b965e9 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -802,9 +802,12 @@ from hermes_cli.web_routers import (
)
import hermes_cli.web_routers.uploads as _upload_routes
+from fastapi import Depends as _Depends
+from hermes_cli.web_server_surface import route_on as _route_on
app.include_router(_files_routes.router)
-app.include_router(_upload_routes.router)
+# The Webapp's routes exist only on the surfaces whose policy names them (404 elsewhere).
+app.include_router(_upload_routes.router, dependencies=[_Depends(_route_on("browser_files"))])
app.include_router(_git_routes.router)
app.include_router(_local_models_routes.router)
app.include_router(_status_routes.router)
@@ -837,7 +840,7 @@ app.include_router(_dashboard_ui_routes.router)
app.include_router(_webapp_routes.router)
app.include_router(_shared_metrics_routes.router)
app.include_router(_delegation_routes.router)
-app.include_router(_webapp_access_routes.router)
+app.include_router(_webapp_access_routes.router, dependencies=[_Depends(_route_on("web_access"))])
# Plugin API routes and the dashboard auth routes (/login, /auth/*, /api/auth/*)
# mount before the SPA catch-all so /{full_path:path} doesn't swallow them. Auth
diff --git a/hermes_cli/web_server_surface.py b/hermes_cli/web_server_surface.py
index 688a69e37dc..c4a76259e1c 100644
--- a/hermes_cli/web_server_surface.py
+++ b/hermes_cli/web_server_surface.py
@@ -1,15 +1,20 @@
"""What each launch surface of the one web-server stack may do.
-The host serving the app records its surface once on ``app.state.ui_surface`` (unset
-reads as ``dashboard``); every surface-dependent decision reads this table instead of
-re-deriving it. ``auth_required`` is decided at runtime by the auth gate, so the
-private-launch predicate is a function over state, not a table field.
+The host serving the app records its surface once on ``app.state.ui_surface``; unset, it reads
+as ``gateway`` on the gateway's own listener for native clients (the app has a
+``gateway_runner``, as the lifespan choice reads) and ``dashboard`` elsewhere (the standalone
+``hermes dashboard`` and ``hermes serve``). Every surface-dependent decision reads this table
+instead of re-deriving it, and :func:`route_on` keeps a route off the surfaces that do not use
+it. ``auth_required`` is decided at runtime by the auth gate, so the private-launch predicate is
+a function over state, not a table field.
"""
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any
+from typing import Any, Callable
+
+from fastapi import HTTPException, Request
@dataclass(frozen=True)
@@ -29,23 +34,51 @@ class SurfacePolicy:
#: Behind the sign-in gate, a write that carries the session cookie (``/auth/logout`` included)
#: must come from this listener's own origin. Elsewhere the gate keeps main's rule.
own_origin_cookie_writes: bool
+ #: ``/api/webapp-access/*`` serves: native Desktop's Web Access pane calls the gateway's own
+ #: listener (the private one, or the Webapp's when it is on).
+ web_access: bool
+ #: The browser's file routes serve: ``/api/chat/file-upload`` stages a picked file,
+ #: ``/api/files/ticket`` mints the path-bound tickets for downloads and media links, and chat
+ #: upload bodies are capped before they are parsed (``web_upload_limit``).
+ browser_files: bool
POLICIES: dict[str, SurfacePolicy] = {
"serve": SurfacePolicy(
serves_spa=False, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,
- own_origin_cookie_writes=False),
+ own_origin_cookie_writes=False, web_access=False, browser_files=False),
"dashboard": SurfacePolicy(
serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,
- own_origin_cookie_writes=False),
+ own_origin_cookie_writes=False, web_access=False, browser_files=False),
+ "gateway": SurfacePolicy(
+ serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,
+ own_origin_cookie_writes=False, web_access=True, browser_files=False),
"webapp": SurfacePolicy(
serves_spa=True, html_token=False, host_terminal=True, launch_link=True, gateway_ticket=True,
- own_origin_cookie_writes=True),
+ own_origin_cookie_writes=True, web_access=True, browser_files=True),
}
+def surface(state: Any) -> str:
+ """The surface *state*'s app serves (see the module docstring)."""
+ recorded = getattr(state, "ui_surface", None)
+ if recorded:
+ return recorded
+ return "gateway" if getattr(state, "gateway_runner", None) is not None else "dashboard"
+
+
def policy(state: Any) -> SurfacePolicy:
- return POLICIES[getattr(state, "ui_surface", "dashboard")]
+ return POLICIES[surface(state)]
+
+
+def route_on(field: str) -> Callable[[Request], None]:
+ """A route dependency answering 404 where the serving surface's policy leaves *field* off, so
+ the route does not exist there for any caller."""
+ def surface_serves(request: Request) -> None:
+ if not getattr(policy(request.app.state), field):
+ raise HTTPException(status_code=404, detail="Not Found")
+
+ return surface_serves
def private_launch(state: Any) -> bool:
diff --git a/hermes_cli/web_upload_limit.py b/hermes_cli/web_upload_limit.py
index cb5afcfb7cd..0e8dcdbae4a 100644
--- a/hermes_cli/web_upload_limit.py
+++ b/hermes_cli/web_upload_limit.py
@@ -7,6 +7,7 @@ from starlette.formparsers import MultiPartException
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Message, Receive, Scope, Send
+from hermes_cli.web_server_surface import policy
from hermes_constants import WEBAPP_ATTACHMENT_MAX_BYTES
# The file cap remains exact in the handler; allow ordinary multipart headers
@@ -27,7 +28,9 @@ _BODY_MAX_BYTES = {
class ChatFileUploadLimitMiddleware:
"""Refuse a chat file or image upload with 413 once its body passes the route's cap: at once
- when Content-Length declares more, else at the first chunk past it."""
+ when Content-Length declares more, else at the first chunk past it. Only on the surfaces whose
+ policy serves the browser's file routes (the Webapp); elsewhere uploads reach their handlers
+ as on main."""
def __init__(self, app: ASGIApp):
self.app = app
@@ -38,7 +41,8 @@ class ChatFileUploadLimitMiddleware:
if root and path.startswith(root + "/"):
path = path[len(root) :]
body_max = _BODY_MAX_BYTES.get(path)
- if scope["type"] != "http" or scope["method"] != "POST" or body_max is None:
+ if (scope["type"] != "http" or scope["method"] != "POST" or body_max is None
+ or not policy(getattr(scope.get("app"), "state", None)).browser_files):
await self.app(scope, receive, send)
return
diff --git a/tests/hermes_cli/native_gateway_client.py b/tests/hermes_cli/native_gateway_client.py
new file mode 100644
index 00000000000..585ab9daf45
--- /dev/null
+++ b/tests/hermes_cli/native_gateway_client.py
@@ -0,0 +1,42 @@
+"""A test client that reaches the dashboard app as native Desktop reaches the gateway's own listener.
+
+Native Desktop's local connection is the gateway's listener, and Electron's main process mints one
+``native-http`` grant per request over the gateway's private control socket and sends it as
+``X-Hermes-Gateway-Ticket`` from a loopback peer, with no Origin
+(``apps/desktop/electron/local-gateway.ts``, ``nativeGatewayHttpHeaders``). Here the grant comes from
+the same ``TicketStore`` the control socket mints from, bound to a runner serving the test's home,
+and the peer is recorded as ``GatewayRuntimeAPI`` records it, so the real
+``hermes_cli.dashboard_auth.native_http`` gate admits each request.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from fastapi.testclient import TestClient
+
+
+def native_desktop_client(monkeypatch) -> TestClient:
+ """A client for ``web_server.app`` bound to a gateway runner serving ``get_hermes_home()``."""
+ from gateway.runtime_bootstrap import TicketStore
+ from gateway.session_authorities import SessionAuthorities
+ from hermes_cli import web_server
+ from hermes_constants import get_hermes_home
+
+ home = get_hermes_home().resolve()
+ authorities = SessionAuthorities(home)
+ authorities.add(home, SimpleNamespace(profile_id=str(home), instance_id="daemon"))
+ store = TicketStore("daemon", authorities.profile_ids())
+ runner = SimpleNamespace(
+ session_authorities=authorities, session_ticket_store=store, _draining=False,
+ session_runtime_descriptor={"state": "ready", "instance_id": "daemon",
+ "served_profiles": authorities.served_profiles()})
+ monkeypatch.setattr(web_server.app.state, "gateway_runner", runner, raising=False)
+
+ async def native_desktop(scope, receive, send):
+ if scope["type"] == "http":
+ ticket = store.mint(profile_id=str(home), subject="desktop", purpose="native-http")
+ scope = {**scope, "headers": [*scope["headers"], (b"x-hermes-gateway-ticket", ticket.encode())],
+ "hermes.gateway_socket_peer": ("127.0.0.1", 50000)}
+ await web_server.app(scope, receive, send)
+
+ return TestClient(native_desktop, raise_server_exceptions=False)
diff --git a/tests/hermes_cli/test_web_server_file_ticket_generations.py b/tests/hermes_cli/test_web_server_file_ticket_generations.py
index dce4e1bb054..439be7e4404 100644
--- a/tests/hermes_cli/test_web_server_file_ticket_generations.py
+++ b/tests/hermes_cli/test_web_server_file_ticket_generations.py
@@ -34,7 +34,7 @@ def file_server(tmp_path, monkeypatch):
monkeypatch.setattr(web_server, "_SESSION_TOKEN", secrets.token_urlsafe(32))
monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)
monkeypatch.setattr(web_server.app.state, "bound_host", "127.0.0.1", raising=False)
- monkeypatch.setattr(web_server.app.state, "ui_surface", "serve", raising=False)
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
server = uvicorn.Server(uvicorn.Config(
diff --git a/tests/hermes_cli/test_web_server_files.py b/tests/hermes_cli/test_web_server_files.py
index 6f27120ba35..98844f1048d 100644
--- a/tests/hermes_cli/test_web_server_files.py
+++ b/tests/hermes_cli/test_web_server_files.py
@@ -249,6 +249,8 @@ def test_browser_file_urls_authenticate_only_with_route_and_path_bound_tickets(
from hermes_cli import web_server_file_tickets
client, root = forced_files_client
+ # The Webapp mints file tickets: the browser's file routes exist only there.
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
video = _seed_file(client, root, name="out/demo.mp4")
other = _seed_file(client, root, name="out/other.mp4")
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index 53202645bb8..d84a9127290 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -264,6 +264,8 @@ def test_a_browser_download_reads_the_ssh_workspace_file_it_listed(client, monke
from hermes_cli import web_server_file_tickets as file_tickets
from hermes_constants import mark_named_profile_deleted
+ # The Webapp: the browser's file routes (download tickets) exist only there.
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
home = tmp_path / ".hermes"
profile = home / "profiles" / "remote-dev"
profile.mkdir(parents=True)
@@ -703,6 +705,8 @@ def test_a_picked_image_reads_back_from_the_host_for_an_ssh_profile(client, monk
file of another profile, a file in the uploads folder the upload route did not name, one in a
folder below it, and a path that leaves the folder through ``..``."""
profile, workspace = _ssh_profiles(tmp_path, monkeypatch)
+ # The Webapp: the browser's file routes (the file picker's upload) exist only there.
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
image = base64.b64decode("iVBORw0KGgo=")
def pick(query):
diff --git a/tests/hermes_cli/test_web_server_surface.py b/tests/hermes_cli/test_web_server_surface.py
new file mode 100644
index 00000000000..0c2a481ff3d
--- /dev/null
+++ b/tests/hermes_cli/test_web_server_surface.py
@@ -0,0 +1,129 @@
+"""Routes only the Webapp or native Desktop's Web Access pane use exist only on the surfaces that use them.
+
+One dashboard app serves every surface: the standalone ``hermes dashboard``, the headless
+``hermes serve``, the gateway's own listener for native clients, and the gateway's Webapp. The surface
+policy (``hermes_cli.web_server_surface``) says which of them serve:
+
+- ``/api/webapp-access/*``: native Desktop's Web Access pane, which calls the gateway's own listener
+ (the private one, or the Webapp's when it is on);
+- the browser's file routes, ``/api/chat/file-upload`` and ``/api/files/ticket``, and the cap on chat
+ upload bodies before they are parsed: the Webapp only.
+
+Everywhere else these routes answer 404 before their handlers run, and chat uploads reach their
+handlers as on main.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi.testclient import TestClient
+
+from hermes_cli import web_server
+from tests.hermes_cli.native_gateway_client import native_desktop_client
+
+WEB_ACCESS = (("get", "/api/webapp-access/status", None), ("post", "/api/webapp-access/start", {}),
+ ("post", "/api/webapp-access/stop", None), ("post", "/api/webapp-access/restart", None))
+
+
[email protected](autouse=True)
+def nothing_acts(monkeypatch):
+ """No route under test may build, register, write config or restart a gateway: a handler that
+ runs answers 500 instead of acting."""
+ import hermes_cli.web_server_gateway as gateway
+ from hermes_cli import webapp, webapp_access
+
+ def refuse(*_args, **_kwargs):
+ raise AssertionError("a Web Access handler ran")
+
+ monkeypatch.setattr(gateway, "_restart_gateway_after", refuse)
+ monkeypatch.setattr(webapp, "prepare_webapp_renderer", refuse)
+ monkeypatch.setattr(webapp_access, "turn_off", refuse)
+ monkeypatch.setattr(webapp_access, "access_status", lambda: {"enabled": False})
+ for key in ("ui_surface", "gateway_runner", "listener_public_url", "webapp_home"):
+ if hasattr(web_server.app.state, key):
+ monkeypatch.delattr(web_server.app.state, key)
+ monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)
+
+
+def _owner_client() -> TestClient:
+ """The loopback session token's holder: the standalone dashboard's page, ``hermes serve``'s
+ spawner, or a tab of the loopback Webapp."""
+ client = TestClient(web_server.app, raise_server_exceptions=False)
+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
+ return client
+
+
+def _browser_file_statuses(client: TestClient) -> tuple[int, int]:
+ upload = client.post("/api/chat/file-upload", files={"file": ("note.txt", b"hello")})
+ ticket = client.post("/api/files/ticket", json={})
+ return upload.status_code, ticket.status_code
+
+
+def _web_access_statuses(client: TestClient) -> list[int]:
+ return [getattr(client, method)(path, **({} if body is None else {"json": body})).status_code
+ for method, path, body in WEB_ACCESS]
+
+
[email protected]("serves_spa", [True, False], ids=["hermes-dashboard", "hermes-serve"])
+def test_the_standalone_dashboard_and_serve_have_neither_web_access_nor_browser_file_routes(
+ monkeypatch, serves_spa):
+ from hermes_constants import get_hermes_home
+
+ monkeypatch.setattr(web_server.app.state, "serves_spa", serves_spa, raising=False)
+ client = _owner_client()
+
+ assert _browser_file_statuses(client) == (404, 404)
+ assert _web_access_statuses(client) == [404] * len(WEB_ACCESS)
+ assert not (get_hermes_home() / "uploads").exists()
+
+
+def test_the_gateways_own_listener_serves_web_access_but_not_the_browser_file_routes(monkeypatch):
+ """With the Webapp off, native Desktop's Web Access pane works on the gateway's listener; the
+ browser's file routes, which only the Webapp calls, are not there."""
+ from hermes_constants import get_hermes_home
+
+ native = native_desktop_client(monkeypatch)
+
+ assert native.get("/api/webapp-access/status").status_code == 200
+ assert native.post("/api/webapp-access/start", json={}).status_code == 422 # reached its handler
+ assert _browser_file_statuses(native) == (404, 404)
+ assert not (get_hermes_home() / "uploads").exists()
+
+
+def test_the_webapp_serves_web_access_and_the_browser_file_routes(monkeypatch):
+ native = native_desktop_client(monkeypatch)
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
+
+ assert native.get("/api/webapp-access/status").status_code == 200
+ upload, ticket = _browser_file_statuses(_owner_client())
+ assert (upload, ticket) == (200, 422)
+
+
[email protected](("surface", "capped"), [(None, False), ("webapp", True)])
+def test_chat_upload_bodies_are_capped_before_parsing_only_on_the_webapp(surface, capped):
+ """An image paste larger than the cap reaches ``/api/chat/image-upload``'s own handler on every
+ surface but the Webapp, as on main; the Webapp refuses it with 413 before reading the body."""
+ import asyncio
+
+ from hermes_cli.web_upload_limit import CHAT_IMAGE_BODY_MAX_BYTES, ChatFileUploadLimitMiddleware
+
+ reached, sent = [], []
+
+ async def handler(scope, receive, send):
+ reached.append(scope["path"])
+
+ async def receive():
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ async def send(message):
+ sent.append(message)
+
+ state = SimpleNamespace() if surface is None else SimpleNamespace(ui_surface=surface)
+ scope = {"type": "http", "method": "POST", "path": "/api/chat/image-upload", "root_path": "",
+ "headers": [(b"content-length", str(CHAT_IMAGE_BODY_MAX_BYTES + 1).encode())],
+ "app": SimpleNamespace(state=state)}
+ asyncio.run(ChatFileUploadLimitMiddleware(handler)(scope, receive, send))
+
+ assert reached == ([] if capped else ["/api/chat/image-upload"])
+ assert [m["status"] for m in sent if m["type"] == "http.response.start"] == ([413] if capped else [])
diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.py
index 98b24b1f54f..b0a7de3400e 100644
--- a/tests/hermes_cli/test_webapp_access.py
+++ b/tests/hermes_cli/test_webapp_access.py
@@ -15,12 +15,12 @@ from fastapi.testclient import TestClient
@pytest.fixture()
-def client():
- from hermes_cli import web_server
+def client(monkeypatch):
+ """Native Desktop on this computer, calling the gateway's own listener as its Web Access pane
+ does: one native grant per request."""
+ from tests.hermes_cli.native_gateway_client import native_desktop_client
- c = TestClient(web_server.app, raise_server_exceptions=False)
- c.headers["Authorization"] = f"Bearer {web_server._SESSION_TOKEN}"
- return c
+ return native_desktop_client(monkeypatch)
@pytest.fixture()
@@ -206,8 +206,8 @@ def test_start_takes_the_public_url_as_typed(client, restarts, nous):
@pytest.fixture()
def lan_browser(monkeypatch):
- """This listener on all interfaces behind password sign-in, and a browser on the LAN signed in
- with a cookie session."""
+ """The gateway's Webapp on all interfaces behind password sign-in, and a browser on the LAN
+ signed in with a cookie session."""
import plugins.dashboard_auth.basic as basic_plugin
from hermes_cli import web_server
from hermes_cli.dashboard_auth import clear_providers, register_provider
@@ -215,7 +215,8 @@ def lan_browser(monkeypatch):
monkeypatch.delenv("HERMES_DASHBOARD_PUBLIC_URL", raising=False)
for key, value in (("bound_host", "0.0.0.0"), ("bound_port", 9120), ("auth_required", True),
- ("trusted_public_hosts", frozenset())):
+ ("trusted_public_hosts", frozenset()), ("ui_surface", "webapp"),
+ ("listener_public_url", "")):
monkeypatch.setattr(web_server.app.state, key, value, raising=False)
clear_providers()
register_provider(basic_plugin.BasicAuthProvider(
@@ -301,13 +302,12 @@ def test_other_requests_answer_while_start_builds_and_registers(client, restarts
the callback (a network round trip), a config request answers at once."""
import threading
- from hermes_cli import web_server, webapp, webapp_access
+ from hermes_cli import webapp, webapp_access
answered_during_step: list[list[int]] = []
def ask_for_config(answers: list[int]) -> None:
- other = TestClient(web_server.app, raise_server_exceptions=False)
- other.headers.update(client.headers)
+ other = TestClient(client.app, raise_server_exceptions=False)
answers.append(other.get("/api/config").status_code)
def slow_step(*_args, **_options):
diff --git a/tests/hermes_cli/test_webapp_file_urls.py b/tests/hermes_cli/test_webapp_file_urls.py
index 067cb78e22b..297fd517ffc 100644
--- a/tests/hermes_cli/test_webapp_file_urls.py
+++ b/tests/hermes_cli/test_webapp_file_urls.py
@@ -26,7 +26,7 @@ def webapp_client(monkeypatch, tmp_path):
home.mkdir()
monkeypatch.delenv("HERMES_DASHBOARD_FILES_ROOT", raising=False)
monkeypatch.setenv("HOME", str(home))
- for key, value in (("auth_required", False), ("bound_host", None)):
+ for key, value in (("auth_required", False), ("bound_host", None), ("ui_surface", "webapp")):
monkeypatch.setattr(web_server.app.state, key, value, raising=False)
client = TestClient(web_server.app)
client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
diff --git a/tests/hermes_cli/test_webapp_upload_limit.py b/tests/hermes_cli/test_webapp_upload_limit.py
index dcae11f6792..619406f6426 100644
--- a/tests/hermes_cli/test_webapp_upload_limit.py
+++ b/tests/hermes_cli/test_webapp_upload_limit.py
@@ -31,6 +31,9 @@ def upload_app(tmp_path, monkeypatch):
monkeypatch.setattr(web_server.app.state, "auth_required", True, raising=False)
monkeypatch.setattr(web_server.app.state, "bound_host", "0.0.0.0", raising=False)
monkeypatch.setattr(web_server.app.state, "trusted_public_hosts", frozenset(), raising=False)
+ # The Webapp behind sign-in: the only surface that caps upload bodies before parsing them.
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
+ monkeypatch.setattr(web_server.app.state, "listener_public_url", "", raising=False)
clear_providers()
register_provider(StubAuthProvider())
# Observe the actual parser's open files, retaining references so GC cannot
@@ -51,9 +54,14 @@ def upload_app(tmp_path, monkeypatch):
async def _login(client):
+ """Sign the browser in on the Webapp; returns what its own page's requests carry (its session
+ cookies and its Origin), so another client can send the same request. On the Webapp a browser
+ login's token never works alone as a bearer token."""
response = await client.get("/auth/login?provider=stub", follow_redirects=True)
assert response.status_code != 401
- return next(v for k, v in client.cookies.items() if k.endswith(SESSION_AT_COOKIE))
+ assert any(k.endswith(SESSION_AT_COOKIE) for k in client.cookies)
+ return {"Cookie": "; ".join(f"{k}={v}" for k, v in client.cookies.items()),
+ "Origin": "https://dashboard.example.com"}
@pytest.mark.parametrize(
@@ -99,9 +107,9 @@ def test_upload_bound_stops_parser_and_closes_spools(upload_app, monkeypatch, de
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=web_server.app), base_url="https://dashboard.example.com"
) as client:
- token = await _login(client)
+ page = await _login(client)
headers = {
- "Authorization": f"Bearer {token}",
+ **page,
"Content-Type": "multipart/form-data; boundary=" + boundary.decode(),
}
if declared_length is not None:
@@ -163,8 +171,8 @@ def test_an_oversized_image_paste_is_refused_before_its_body_is_read(upload_app,
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=web_server.app), base_url="https://dashboard.example.com"
) as client:
- token = await _login(client)
- headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
+ page = await _login(client)
+ headers = {**page, "Content-Type": "application/json"}
if declared_length is not None:
headers["Content-Length"] = str(2 * allowed) if declared_length == "oversize" else declared_length
response = await client.post("/api/chat/image-upload", content=body(), headers=headers)
@@ -226,8 +234,7 @@ def test_other_upload_routes_keep_their_larger_caps(upload_app, monkeypatch):
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=web_server.app), base_url="https://dashboard.example.com"
) as client:
- token = await _login(client)
- headers = {"Authorization": f"Bearer {token}"}
+ headers = await _login(client)
payload = b"x" * web_server._MANAGED_FILE_MAX_BYTES
response = await client.post(
"/api/files/upload-stream",
diff --git a/tests/hermes_cli/test_webapp_uploads.py b/tests/hermes_cli/test_webapp_uploads.py
index 29a51542d4d..f9cac031603 100644
--- a/tests/hermes_cli/test_webapp_uploads.py
+++ b/tests/hermes_cli/test_webapp_uploads.py
@@ -35,6 +35,8 @@ def _client(tmp_path: Path, monkeypatch) -> TestClient:
monkeypatch.setattr(web_server, "_SESSION_TOKEN", "webapp-test-token")
monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)
monkeypatch.setattr(web_server.app.state, "bound_host", "127.0.0.1", raising=False)
+ # The loopback Webapp: the only surface that serves the browser's file routes.
+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)
return TestClient(web_server.app, base_url="http://127.0.0.1")