Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ui): strictly validate malformed Host authorities (#2520)
Call White79cad7d3e84f
diff --git a/tests/test_host_header_boundary.py b/tests/test_host_header_boundary.pynew file mode 100644index 000000000..ac83e1af9--- /dev/null+++ b/tests/test_host_header_boundary.py@@ -0,0 +1,84 @@+import asyncio++import pytest+from fastapi import WebSocketDisconnect+from starlette.requests import Request++from vibe.ui_compat import CompatRequest+from vibe.ui_server import _RejectInvalidHostMiddleware, _is_valid_host_header, app+++ "host",+ [+ "lan.example/assets/x?",+ "lan.example/assets/x#",+ "[::::]",+ "[1:2:3:4:5:6:7:8:9]",+ "[fe80::1%x?y]",+ "[fe80::1%x#y]",+ ],+)+def test_invalid_host_websocket_closes_before_route(monkeypatch, tmp_path, host):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ with pytest.raises(WebSocketDisconnect) as exc_info:+ with app.test_client().websocket_connect("/api/events", headers={"Host": host}):+ pytest.fail("invalid Host was accepted")+ assert exc_info.value.code == 1008+++ "host",+ ["lan.example:0", "[fe80::1%en0]", "[fe80::1%25en0]", "[v1.fe80::1]", "lan.example%20:443"],+)+def test_valid_host_authorities_remain_accepted(host):+ assert _is_valid_host_header(host)+++ ("scope_type", "headers"),+ [+ ("http", [(b"host", b"lan.example:\xb2")]),+ ("websocket", [(b"host", b"[fe80::1%x?y]")]),+ ("websocket", [(b"host", b"[fe80::1%x#y]")]),+ ],+)+def test_raw_invalid_host_bytes_are_rejected_before_inner_app(scope_type, headers):+ sent = []+ reached = []++ async def inner(scope, receive, send):+ reached.append(True)++ async def receive():+ raise AssertionError("invalid Host must not read the request")++ async def send(message):+ sent.append(message)++ asyncio.run(+ _RejectInvalidHostMiddleware(inner)(+ {"type": scope_type, "headers": headers}, receive, send+ )+ )+ assert not reached+ if scope_type == "http":+ assert sent[0]["type"] == "http.response.start"+ assert sent[0]["status"] == 400+ else:+ assert sent == [{"type": "websocket.close", "code": 1008}]+++def test_compat_request_path_uses_routed_scope_path():+ scope = {+ "type": "http",+ "method": "GET",+ "path": "/api/config",+ "raw_path": b"/api/config",+ "query_string": b"",+ "headers": [(b"host", b"lan.example/assets/x?")],+ "client": ("testclient", 50000),+ "server": ("testserver", 80),+ "scheme": "http",+ }+ assert CompatRequest(Request(scope)).path == "/api/config"diff --git a/tests/test_ui_server_mutation_protection.py b/tests/test_ui_server_mutation_protection.pyindex 30291cdac..048f68341 100644--- a/tests/test_ui_server_mutation_protection.py+++ b/tests/test_ui_server_mutation_protection.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport ipaddressfrom http.cookies import SimpleCookie+import pytest+from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, V2Configfrom vibe import ui_serverfrom vibe.ui_compat import TEST_REMOTE_ADDR_HEADER@@ -97,6 +99,54 @@ def test_config_post_rejects_host_mismatch_before_parsing_malformed_json(monkeypassert response.get_json()["error"] == "remote_access_host_mismatch"+ "host",+ [+ "lan.example/assets/x?",+ "lan.example/assets/x#",+ "[::::]",+ "[1:2:3:4:5:6:7:8:9]",+ "lan.example%zz",+ ],+)+def test_malformed_host_is_refused_before_request_hooks(monkeypatch, tmp_path, host):+ """A Host carrying path delimiters must not reshape the path the auth hooks see.++ Starlette < 1.0.1 rebuilds ``request.url`` from the raw Host, so such a value+ made a write to ``/api/config`` look like a public ``/assets/`` request to a+ peer reaching a wildcard-bound UI directly.+ """+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ )+ config.ui.setup_host = "0.0.0.0"+ config.save()+ config_path = tmp_path / "config" / "config.json"+ before = config_path.read_bytes()+ client = app.test_client()++ response = client.post(+ "/api/config",+ json={"agents": {"claude": {"enabled": True, "cli_path": "/tmp/unexpected-cli"}}},+ headers={+ "Host": host,+ "Origin": "http://lan.example",+ "Cookie": "vibe_csrf_token=t",+ "X-Vibe-CSRF-Token": "t",+ },+ environ_base={"REMOTE_ADDR": "203.0.113.10"},+ )++ assert response.status_code == 400+ assert response.get_json() == {"ok": False, "error": "invalid_host_header"}+ assert config_path.read_bytes() == before++def test_config_post_accepts_vendor_json_content_type(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))V2Config(diff --git a/vibe/ui_compat.py b/vibe/ui_compat.pyindex 8abf091aa..cde3f4ef8 100644--- a/vibe/ui_compat.py+++ b/vibe/ui_compat.py@@ -54,7 +54,9 @@ class CompatRequest:@propertydef path(self) -> str:- return self._request.url.path+ # The routed path. ``request.url`` is rebuilt from the Host header, so+ # its path can differ from the one the router dispatched on.+ return self._request.scope["path"]@propertydef args(self) -> QueryParams:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex f8a9fcd8a..be08f416f 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3106,7 +3106,92 @@ def _apply_vault_sandbox_security_headers(response: FastAPIResponse, path: str)@app.middleware("http")async def add_vault_sandbox_security_headers(starlette_request: FastAPIRequest, call_next):response = await call_next(starlette_request)- return _apply_vault_sandbox_security_headers(response, starlette_request.url.path)+ return _apply_vault_sandbox_security_headers(response, starlette_request.scope["path"])+++# RFC 9112 §3.2 Host: ``uri-host [":" port]`` (same grammar Starlette >= 1.0.1+# enforces). Anything else, e.g. ``/``, ``?`` or ``#``, would let the Host move+# the path boundary of the URL rebuilt from it.+_VALID_REG_NAME_RE = re.compile(+ r"(?:[a-z0-9._~!$&'()*+,;=-]|%[0-9a-f]{2})+",+ re.IGNORECASE,+)+_VALID_ZONE_ID_RE = re.compile(r"[a-z0-9._~-]+", re.IGNORECASE)+_VALID_IPV_FUTURE_RE = re.compile(+ r"(?-i:v)[0-9a-f]+\.[a-z0-9._~!$&'()*+,;=:-]+",+ re.IGNORECASE,+)+_VALID_ASCII_DIGITS_RE = re.compile(r"[0-9]+")+++def _is_valid_host_header(value: str) -> bool:+ """Return whether *value* is a syntactically valid Host authority."""++ host = value+ port = ""+ if value.startswith("["):+ closing = value.find("]")+ if closing < 0:+ return False+ literal = value[1:closing]+ suffix = value[closing + 1 :]+ if suffix:+ if not suffix.startswith(":") or _VALID_ASCII_DIGITS_RE.fullmatch(suffix[1:]) is None:+ return False+ port = suffix[1:]+ address, separator, zone = literal.partition("%")+ if separator:+ if zone.startswith("25"):+ zone = zone[2:]+ if _VALID_ZONE_ID_RE.fullmatch(zone) is None:+ return False+ try:+ ipaddress.IPv6Address(address)+ except ValueError:+ if separator or _VALID_IPV_FUTURE_RE.fullmatch(literal) is None:+ return False+ else:+ if value.count(":") > 1:+ return False+ host, separator, port = value.partition(":")+ if separator and _VALID_ASCII_DIGITS_RE.fullmatch(port) is None:+ return False+ if _VALID_REG_NAME_RE.fullmatch(host) is None:+ return False++ port = port.lstrip("0")+ return len(port) <= 5 and int(port or "0") <= 65535+++class _RejectInvalidHostMiddleware:+ """Refuse HTTP and WebSocket requests whose Host is not a valid authority.++ Request hooks and handlers read origin and host values derived from Host;+ this keeps every one of them on a well-formed value. Registered after the+ other middleware so it wraps all of them.+ """++ def __init__(self, asgi_app: Any) -> None:+ self.app = asgi_app++ async def __call__(self, scope: Any, receive: Any, send: Any) -> None:+ if scope["type"] in {"http", "websocket"}:+ hosts = [value for key, value in scope.get("headers") or () if key == b"host"]+ if len(hosts) > 1 or (hosts and not _is_valid_host_header(hosts[0].decode("latin-1"))):+ if scope["type"] == "websocket":+ await send({"type": "websocket.close", "code": 1008})+ return+ response = FastAPIResponse(+ content='{"ok":false,"error":"invalid_host_header"}',+ status_code=400,+ media_type="application/json",+ )+ await response(scope, receive, send)+ return+ await self.app(scope, receive, send)+++app.add_middleware(_RejectInvalidHostMiddleware)@app.after_request