Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(workbench): keep internal dispatch socket off shared mounts (#394)

Call White8c4718d3aea1
diff --git a/core/controller.py b/core/controller.py
index f50770eae..65fb39f8b 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -834,10 +834,7 @@ class Controller:
try:
from core import internal_server as _internal_server
- self._internal_server_task = self._loop.create_task(
- _internal_server.serve(self),
- name="internal-dispatch-server",
- )
+ self._internal_server_task = _internal_server.start(self)
except Exception:
logger.exception("internal dispatch server failed to schedule; UI fallback will use the queue path")
self._internal_server_task = None
diff --git a/core/internal_server.py b/core/internal_server.py
index 275d1bc3f..2c45b4f5d 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -17,9 +17,9 @@ Three properties matter:
2. **Local-only.** Unix sockets are bind to a file path on the local
filesystem; no TCP listen, so external network exposure is
impossible.
-3. **0o600 permissions.** The socket file is chmod'd to ``0o600`` so
- only the running user can connect — defense in depth against shared
- hosts.
+3. **Restrictive permissions.** The socket file is created under a
+ restrictive umask and chmod'd to ``0o600`` when the filesystem supports
+ it — defense in depth against shared hosts.
The endpoint set is intentionally tiny for v1 (``dispatch`` + a stub
``cancel``); follow-ups can grow it without changing the bind contract.
@@ -31,6 +31,7 @@ import asyncio
import json
import logging
import os
+import socket
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Optional, TYPE_CHECKING
@@ -51,11 +52,15 @@ logger = logging.getLogger(__name__)
def default_socket_path() -> Path:
"""Where the internal server binds by default.
- Lives under ``~/.vibe_remote/state/`` so it shares the rest of the
- runtime state's filesystem permissions and gets cleaned up on home
- directory wipes.
+ By default this lives under ``~/.vibe_remote/state/`` for backward
+ compatibility. Container runtimes can override it with
+ ``VIBE_INTERNAL_DISPATCH_SOCKET`` when the persisted state mount does not
+ support Unix-socket permission operations.
"""
+ override = os.environ.get("VIBE_INTERNAL_DISPATCH_SOCKET")
+ if override:
+ return Path(override).expanduser()
return paths.get_state_dir() / "dispatch.sock"
@@ -403,18 +408,9 @@ async def serve(controller: "Controller", *, socket_path: Optional[Path] = None)
import uvicorn
- target = (socket_path or default_socket_path()).expanduser().resolve()
- target.parent.mkdir(parents=True, exist_ok=True)
- if target.exists() or target.is_symlink():
- try:
- target.unlink()
- except OSError:
- logger.warning("could not unlink stale dispatch socket %s; bind may fail", target)
-
app = create_app(controller)
config = uvicorn.Config(
app,
- uds=str(target),
log_config=None,
access_log=False,
loop="asyncio",
@@ -422,29 +418,53 @@ async def serve(controller: "Controller", *, socket_path: Optional[Path] = None)
)
server = uvicorn.Server(config)
- async def _chmod_when_ready() -> None:
- # Defense-in-depth: re-assert ``0o600`` once the socket file
- # exists, in case the platform's umask handling differs from
- # what we set above. The loop polls because uvicorn binds the
- # socket synchronously during ``serve`` and we don't want to
- # race against it.
- for _ in range(40):
- await asyncio.sleep(0.025)
- if target.exists():
- try:
- os.chmod(target, 0o600)
- except OSError:
- logger.warning("failed to chmod internal dispatch socket %s", target)
- return
+ listener, target = _bind_socket(socket_path)
+ try:
+ await server.serve(sockets=[listener])
+ finally:
+ try:
+ listener.close()
+ except OSError:
+ pass
+ try:
+ if target.exists() or target.is_symlink():
+ target.unlink()
+ except OSError:
+ logger.debug("could not unlink internal dispatch socket %s", target, exc_info=True)
+
+
+def _bind_socket(socket_path: Optional[Path] = None) -> tuple[socket.socket, Path]:
+ """Pre-bind the Unix socket before handing it to uvicorn.
+
+ Uvicorn binds ``uds=...`` itself and then chmods the path. Docker Desktop
+ bind mounts can support AF_UNIX sockets but reject chmod on those socket
+ pathnames with ``EINVAL``. Binding here and passing the open socket avoids
+ uvicorn's path chmod while keeping the endpoint local-only.
+ """
+
+ target = (socket_path or default_socket_path()).expanduser().resolve()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if target.exists() or target.is_symlink():
+ try:
+ target.unlink()
+ except OSError:
+ logger.warning("could not unlink stale dispatch socket %s; bind may fail", target)
previous_umask = os.umask(0o077)
- chmod_task = asyncio.create_task(_chmod_when_ready(), name="internal-dispatch-chmod")
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
- await server.serve()
+ listener.bind(str(target))
+ listener.listen(2048)
+ listener.setblocking(False)
+ try:
+ os.chmod(target, 0o600)
+ except OSError:
+ logger.warning("failed to chmod internal dispatch socket %s", target, exc_info=True)
+ return listener, target
+ except Exception:
+ listener.close()
+ raise
finally:
- chmod_task.cancel()
- # Restore the previous umask so unrelated file writes from this
- # process aren't permanently affected by our hardening.
os.umask(previous_umask)
diff --git a/docker-compose.three-regression.yml b/docker-compose.three-regression.yml
index 85e080c4e..87dfeb949 100644
--- a/docker-compose.three-regression.yml
+++ b/docker-compose.three-regression.yml
@@ -9,6 +9,7 @@ services:
environment:
VIBE_REMOTE_HOME: /data/vibe_remote
VIBE_DEPLOYMENT_ENV: regression
+ VIBE_INTERNAL_DISPATCH_SOCKET: /tmp/vibe_remote/dispatch.sock
VIBE_UI_PORT: 5123
VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS: "1"
VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST: "${THREE_REGRESSION_PORT_BIND_HOST:-127.0.0.1}"
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index be5365fcc..95635a56d 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -24,6 +24,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vibe import internal_client
+def test_default_socket_path_honors_env_override(monkeypatch, tmp_path):
+ target = tmp_path / "dispatch.sock"
+ monkeypatch.setenv("VIBE_INTERNAL_DISPATCH_SOCKET", str(target))
+
+ assert internal_client.default_socket_path() == target
+
+
def test_cancel_dispatch_round_trip(tmp_path):
"""``cancel_dispatch`` should forward the session id to the
controller's ``POST /internal/cancel/<session_id>`` endpoint and
@@ -90,3 +97,28 @@ def test_dispatch_async_missing_socket_raises_unavailable(tmp_path):
sock = tmp_path / "missing.sock"
with pytest.raises(internal_client.InternalServerUnavailable):
asyncio.run(internal_client.dispatch_async({"session_id": "s", "text": "x"}, socket_path=sock))
+
+
+def test_turn_state_os_error_raises_unavailable(tmp_path):
+ """Socket files can exist on Docker Desktop bind mounts while connection
+ operations raise platform ``OSError`` values (for example errno 95). The UI
+ route must see the same unavailable signal as a missing socket and degrade
+ instead of returning 500."""
+ sock = tmp_path / "dispatch.sock"
+ sock.touch()
+
+ class FailingClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def get(self, _path):
+ raise OSError(95, "Operation not supported")
+
+ with patch("vibe.internal_client.httpx.AsyncClient", return_value=FailingClient()):
+ with pytest.raises(internal_client.InternalServerUnavailable) as exc:
+ asyncio.run(internal_client.turn_state("ses_x", socket_path=sock))
+
+ assert "Operation not supported" in str(exc.value)
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 99f26f768..44f5f7e72 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -16,7 +16,9 @@ We exercise three layers:
from __future__ import annotations
import asyncio
+import socket
import sys
+import tempfile
import types
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
@@ -93,11 +95,35 @@ def _build_controller_double(handler=None):
def test_default_socket_path_lives_under_state_dir(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ monkeypatch.delenv("VIBE_INTERNAL_DISPATCH_SOCKET", raising=False)
path = internal_server.default_socket_path()
assert path.name == "dispatch.sock"
assert tmp_path in path.parents
+def test_default_socket_path_honors_env_override(monkeypatch, tmp_path):
+ target = tmp_path / "runtime" / "dispatch.sock"
+ monkeypatch.setenv("VIBE_INTERNAL_DISPATCH_SOCKET", str(target))
+
+ assert internal_server.default_socket_path() == target
+
+
+def test_bind_socket_prebinds_unix_listener():
+ # macOS has a short sockaddr_un limit, and pytest tmp paths can exceed it.
+ with tempfile.TemporaryDirectory(prefix="vr-") as tmp:
+ target = Path(tmp) / "dispatch.sock"
+ listener, bound = internal_server._bind_socket(target)
+
+ try:
+ assert bound == target.resolve()
+ assert target.exists()
+ assert listener.family == socket.AF_UNIX
+ assert listener.type == socket.SOCK_STREAM
+ finally:
+ listener.close()
+ target.unlink(missing_ok=True)
+
+
def test_create_app_exposes_minimal_endpoints():
app = internal_server.create_app(_build_controller_double())
routes = {(r.path, tuple(sorted(r.methods))) for r in app.routes if hasattr(r, "methods")}
diff --git a/tests/test_three_regression_script.py b/tests/test_three_regression_script.py
index db7d7d423..61823b9c9 100644
--- a/tests/test_three_regression_script.py
+++ b/tests/test_three_regression_script.py
@@ -21,6 +21,7 @@ def test_three_regression_compose_uses_canonical_state_root_env() -> None:
assert "${THREE_REGRESSION_STATE_ROOT:" in compose
assert "./_tmp/three-regression" not in compose
assert "VIBE_SHOW_RUNTIME_SOURCE" in compose
+ assert "VIBE_INTERNAL_DISPATCH_SOCKET: /tmp/vibe_remote/dispatch.sock" in compose
def test_three_regression_script_serializes_state_updates() -> None:
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index bdd38b886..4c2bf518f 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import json
import logging
+import os
from pathlib import Path
from typing import Any, AsyncIterator, Optional
@@ -28,6 +29,8 @@ from config import paths
logger = logging.getLogger(__name__)
+_SOCKET_ERRORS = (httpx.ConnectError, OSError)
+
class InternalServerUnavailable(Exception):
"""Raised when the dispatch socket cannot be reached.
@@ -48,6 +51,9 @@ def default_socket_path() -> Path:
boundaries clean.
"""
+ override = os.environ.get("VIBE_INTERNAL_DISPATCH_SOCKET")
+ if override:
+ return Path(override).expanduser()
return paths.get_state_dir() / "dispatch.sock"
@@ -82,7 +88,7 @@ async def stream_dispatch(
) as client:
try:
stream = client.stream("POST", "/internal/dispatch", json=payload)
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
async with stream as resp:
@@ -112,7 +118,7 @@ async def stream_dispatch(
yield (current_event or "message", parsed)
except InternalServerUnavailable:
raise
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
@@ -142,7 +148,7 @@ async def stream_events(
) as client:
try:
stream = client.stream("GET", "/internal/events")
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
async with stream as resp:
@@ -169,7 +175,7 @@ async def stream_events(
yield (current_event or "message", parsed)
except InternalServerUnavailable:
raise
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
@@ -200,7 +206,7 @@ async def dispatch_async(
timeout=httpx.Timeout(timeout, connect=5.0),
) as client:
resp = await client.post("/internal/dispatch_async", json=payload)
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -229,7 +235,7 @@ async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None
timeout=httpx.Timeout(30.0, connect=1.0),
) as client:
resp = await client.post(f"/internal/cancel/{session_id}")
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -255,7 +261,7 @@ async def send_now(session_id: str, *, socket_path: Optional[Path] = None) -> di
timeout=httpx.Timeout(30.0, connect=1.0),
) as client:
resp = await client.post(f"/internal/send-now/{session_id}")
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
@@ -277,7 +283,7 @@ async def turn_state(session_id: str, *, socket_path: Optional[Path] = None) ->
timeout=httpx.Timeout(5.0, connect=1.0),
) as client:
resp = await client.get(f"/internal/turn-state/{session_id}")
- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ except _SOCKET_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}