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(macos): shorten Unix admin socket paths

Ruben Lütke8c581fbd598f
diff --git a/.github/workflows/macos-desktop.yml b/.github/workflows/macos-desktop.yml
index 2aaec05a8a..bb092e182d 100644
--- a/.github/workflows/macos-desktop.yml
+++ b/.github/workflows/macos-desktop.yml
@@ -11,6 +11,7 @@ on:
paths:
- ".github/workflows/macos-desktop.yml"
- "install/**"
+ - "jarvis/admin/**"
- "jarvis/cu/**"
- "jarvis/platform/**"
- "jarvis/setup/**"
@@ -132,6 +133,8 @@ jobs:
shell: bash
run: |
python -m pytest -q \
+ tests/integration/test_admin_unix_loopback.py \
+ tests/unit/admin/test_unix_socket_transport.py \
tests/unit/platform/test_permissions.py \
tests/unit/audio/test_capture_permission_gate.py \
tests/unit/ui/web/test_permissions_routes.py \
diff --git a/jarvis/admin/unix_socket.py b/jarvis/admin/unix_socket.py
index e219eab98b..bd6a9b826b 100644
--- a/jarvis/admin/unix_socket.py
+++ b/jarvis/admin/unix_socket.py
@@ -9,6 +9,8 @@ socket two ways, defense in depth:
directory (``$XDG_RUNTIME_DIR/jarvis-admin-<uid>.sock``, falling back to a
``0700`` ``tempfile.mkdtemp`` when ``$XDG_RUNTIME_DIR`` is absent). This is
the direct equivalent of the pipe ACL: only the owning uid can reach it.
+ Addresses that exceed Darwin's shorter ``AF_UNIX`` limit are mapped
+ deterministically into an owner-only per-uid directory under ``/tmp``.
2. **Peer-credential check** — on every accepted connection the server reads the
connecting process's uid (Linux: ``SO_PEERCRED``; macOS: ``LOCAL_PEERCRED`` /
``getpeereid``) and **rejects any peer whose uid != the server process uid**.
@@ -32,8 +34,11 @@ never selects this transport, but tests still import the module).
from __future__ import annotations
import asyncio
+import errno
+import hashlib
import os
import socket
+import stat
import struct
import tempfile
from collections.abc import Awaitable, Callable
@@ -51,6 +56,84 @@ _MAX_PAYLOAD_BYTES = 12 * 1024 * 1024
_DIR_MODE = 0o700
_SOCK_MODE = 0o600
+# Darwin's ``sockaddr_un.sun_path`` is shorter than Linux's. Keep the encoded
+# path below 100 bytes so the trailing NUL and the platform-specific structure
+# layout always fit (macOS allows 104 bytes, Linux 108). A character count is
+# insufficient because non-ASCII filesystem paths may occupy multiple bytes.
+_MAX_SOCKET_PATH_BYTES = 100
+
+
+def _private_short_socket_dir(uid: int) -> str:
+ """Return a deterministic owner-only directory for shortened addresses."""
+ # The fixed short prefix is deliberate: Darwin's AF_UNIX address budget is
+ # too small for its ordinary per-user TMPDIR. Ownership, type, and mode are
+ # validated below before the directory is trusted.
+ candidates = ("/tmp", tempfile.gettempdir()) # noqa: S108
+ seen: set[str] = set()
+ errors: list[OSError] = []
+
+ for base in candidates:
+ if not base or base in seen:
+ continue
+ seen.add(base)
+ directory = os.path.join(base, f"jarvis-admin-{uid}")
+ try:
+ os.mkdir(directory, _DIR_MODE)
+ except FileExistsError:
+ pass
+ except OSError as exc:
+ errors.append(exc)
+ continue
+
+ try:
+ info = os.lstat(directory)
+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):
+ raise PermissionError(f"admin socket runtime path is not a directory: {directory}")
+ if hasattr(os, "getuid") and info.st_uid != uid:
+ raise PermissionError(
+ f"admin socket runtime directory has the wrong owner: {directory}"
+ )
+ if stat.S_IMODE(info.st_mode) != _DIR_MODE:
+ os.chmod(directory, _DIR_MODE)
+ return directory
+ except OSError as exc:
+ errors.append(exc)
+
+ cause = errors[-1] if errors else None
+ raise OSError(
+ errno.EACCES,
+ "no private runtime directory is available for the admin socket",
+ ) from cause
+
+
+def _portable_socket_path(path: str) -> str:
+ """Shorten an over-budget POSIX address without weakening its ACLs.
+
+ Server and client may normalize the same requested address independently,
+ so the replacement is deterministic. The digest prevents collisions while
+ the per-uid ``0700`` directory, peer-credential check, and HMAC envelope
+ retain the original defense-in-depth model.
+ """
+ if os.name == "nt" or len(os.fsencode(path)) <= _MAX_SOCKET_PATH_BYTES:
+ return path
+
+ uid = os.getuid() if hasattr(os, "getuid") else 0
+ requested = os.path.abspath(os.path.expanduser(path))
+ digest = hashlib.sha256(os.fsencode(requested)).hexdigest()[:24]
+ directory = _private_short_socket_dir(uid)
+ shortened = os.path.join(directory, f"{digest}.sock")
+ if len(os.fsencode(shortened)) > _MAX_SOCKET_PATH_BYTES:
+ raise OSError(
+ errno.ENAMETOOLONG,
+ "no safe admin socket address fits this platform's AF_UNIX limit",
+ )
+ logger.debug(
+ "admin_unix_transport.path_shortened requested_bytes={} effective={}",
+ len(os.fsencode(path)),
+ shortened,
+ )
+ return shortened
+
# ---------------------------------------------------------------------
# Peer-credential reading (the SDDL-owner-ACE equivalent)
@@ -74,7 +157,7 @@ def read_peer_uid(conn: socket.socket) -> int | None:
buf = conn.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize("3i"))
_pid, uid, _gid = struct.unpack("3i", buf)
return int(uid)
- except OSError: # pragma: no cover - platform/kernel guard
+ except (OSError, struct.error): # pragma: no cover - platform/kernel guard
return None
# macOS / BSD: LOCAL_PEERCRED on SOL_LOCAL -> struct xucred; the uid is the
@@ -85,7 +168,7 @@ def read_peer_uid(conn: socket.socket) -> int | None:
try:
uid, _gid = getpeereid(conn.fileno())
return int(uid)
- except OSError: # pragma: no cover - platform/kernel guard
+ except (OSError, struct.error): # pragma: no cover - platform/kernel guard
return None
local_peercred = getattr(socket, "LOCAL_PEERCRED", None)
@@ -97,7 +180,7 @@ def read_peer_uid(conn: socket.socket) -> int | None:
buf = conn.getsockopt(sol_local, local_peercred, struct.calcsize("2I"))
_version, uid = struct.unpack("2I", buf)
return int(uid)
- except OSError: # pragma: no cover - platform/kernel guard
+ except (OSError, struct.error): # pragma: no cover - platform/kernel guard
return None
return None
@@ -155,9 +238,10 @@ class UnixSocketTransport:
@property
def address(self) -> str:
- """The socket path; used by the elevator to bind the helper (3.4)."""
+ """The effective socket path used by the elevator and helper."""
if self._socket_path is None:
self._socket_path = default_socket_path()
+ self._socket_path = _portable_socket_path(self._socket_path)
return self._socket_path
# ------------------------------------------------------------------
@@ -189,8 +273,7 @@ class UnixSocketTransport:
except OSError: # pragma: no cover - platform guard
logger.warning("admin_unix_transport.chmod_failed", path=path)
- logger.info("admin_unix_transport.start",
- path=path, uid=self._server_uid)
+ logger.info("admin_unix_transport.start", path=path, uid=self._server_uid)
try:
async with self._server:
await self._stop.wait()
diff --git a/tests/integration/test_admin_unix_loopback.py b/tests/integration/test_admin_unix_loopback.py
index 4547f34c6f..42a50e5328 100644
--- a/tests/integration/test_admin_unix_loopback.py
+++ b/tests/integration/test_admin_unix_loopback.py
@@ -11,6 +11,7 @@ only), an AF_UNIX socket runs fine on a Linux/macOS CI runner — this test is t
standout cross-platform verification win for the Admin wave and is intentionally
NOT marked ``skip_ci``.
"""
+
from __future__ import annotations
import asyncio
@@ -38,11 +39,12 @@ async def test_signed_envelope_roundtrips_over_unix_socket(tmp_path):
executor = AdminExecutor()
server_transport = UnixSocketTransport(sock_path)
- server = AdminPipeServer(
- secret, pipe_name, executor, sid="S-0-0", transport=server_transport
- )
+ effective_path = server_transport.address
+ server = AdminPipeServer(secret, pipe_name, executor, sid="S-0-0", transport=server_transport)
client = AdminPipeClient(
- secret, pipe_name, io_timeout_s=10.0,
+ secret,
+ pipe_name,
+ io_timeout_s=10.0,
transport=UnixSocketTransport(sock_path),
)
@@ -50,16 +52,16 @@ async def test_signed_envelope_roundtrips_over_unix_socket(tmp_path):
try:
# Wait for the socket to be bound.
import os
+
for _ in range(200):
- if os.path.exists(sock_path):
+ if os.path.exists(effective_path):
break
await asyncio.sleep(0.01)
# On a non-Windows host the registry op is not executable; we are only
# proving the round-trip + HMAC + peer-cred path. A read_registry op
# decodes + validates fine, then the executor returns a typed failure.
- op = ReadRegistryOp(hive="HKCU", key_path="Environment",
- value_name="PATH")
+ op = ReadRegistryOp(hive="HKCU", key_path="Environment", value_name="PATH")
resp = await client.send(op)
assert resp.op_id == op.op_id
# The peer is the same uid (this process talks to itself), so the
@@ -78,21 +80,25 @@ async def test_tampered_hmac_rejected_over_unix_socket(tmp_path):
secret = b"X" * 32
sock_path = str(tmp_path / "jarvis-admin-tamper.sock")
+ server_transport = UnixSocketTransport(sock_path)
server = AdminPipeServer(
- secret, sock_path, AdminExecutor(), sid="S-0-0",
- transport=UnixSocketTransport(sock_path),
+ secret,
+ sock_path,
+ AdminExecutor(),
+ sid="S-0-0",
+ transport=server_transport,
)
+ effective_path = server_transport.address
serve_task = asyncio.create_task(server.serve_forever())
try:
import os
+
for _ in range(200):
- if os.path.exists(sock_path):
+ if os.path.exists(effective_path):
break
await asyncio.sleep(0.01)
- client = AdminPipeClient(
- secret, sock_path, transport=UnixSocketTransport(sock_path)
- )
+ client = AdminPipeClient(secret, sock_path, transport=UnixSocketTransport(sock_path))
op = ReadRegistryOp(hive="HKCU", key_path="Environment")
envelope = client._build_envelope(op)
envelope["hmac"] = "0" * 64
diff --git a/tests/unit/admin/test_unix_socket_transport.py b/tests/unit/admin/test_unix_socket_transport.py
index 526e1292fb..db5270f7d8 100644
--- a/tests/unit/admin/test_unix_socket_transport.py
+++ b/tests/unit/admin/test_unix_socket_transport.py
@@ -10,11 +10,13 @@ that tests monkeypatch), so the rejection/acceptance gate runs on every OS,
including the Windows dev box. The real AF_UNIX bind needs POSIX and is covered
by ``tests/integration/test_admin_unix_loopback.py`` (skipped on Windows).
"""
+
from __future__ import annotations
import os
import stat
import sys
+from pathlib import Path
import pytest
@@ -37,6 +39,25 @@ def test_unix_socket_transport_satisfies_protocol():
assert isinstance(UnixSocketTransport("/tmp/x.sock"), AdminTransport)
+def test_short_socket_address_is_preserved():
+ assert UnixSocketTransport("/tmp/x.sock").address == "/tmp/x.sock"
+
+
[email protected](sys.platform == "win32", reason="AF_UNIX paths are POSIX-only")
+def test_long_socket_address_is_shortened_deterministically(tmp_path):
+ requested = str(tmp_path / ("nested-" * 20) / "jarvis-admin.sock")
+
+ first = UnixSocketTransport(requested).address
+ second = UnixSocketTransport(requested).address
+
+ assert first == second
+ assert first != requested
+ assert len(os.fsencode(first)) <= unix_socket._MAX_SOCKET_PATH_BYTES
+ runtime_dir = Path(first).parent
+ assert stat.S_IMODE(runtime_dir.stat().st_mode) == 0o700
+ assert runtime_dir.stat().st_uid == os.getuid()
+
+
def test_peer_uid_match_accepted(monkeypatch):
t = UnixSocketTransport("/tmp/x.sock")
monkeypatch.setattr(t, "_server_uid", 1000)
@@ -67,7 +88,7 @@ def test_peer_uid_no_socket_rejected():
@pytest.mark.skipif(
sys.platform == "win32",
reason="AF_UNIX bind + os.getuid are POSIX-only; logic is covered by the "
- "monkeypatched peer-cred tests above and the unix loopback test.",
+ "monkeypatched peer-cred tests above and the unix loopback test.",
)
@pytest.mark.asyncio
async def test_socket_file_is_0600_in_0700_dir(tmp_path):
@@ -76,8 +97,10 @@ async def test_socket_file_is_0600_in_0700_dir(tmp_path):
runtime_dir = tmp_path / "runtime"
runtime_dir.mkdir(mode=0o700)
- sock_path = str(runtime_dir / "jarvis-admin.sock")
- transport = UnixSocketTransport(sock_path)
+ requested_path = str(runtime_dir / "jarvis-admin.sock")
+ transport = UnixSocketTransport(requested_path)
+ sock_path = transport.address
+ runtime_dir = Path(sock_path).parent
async def _handler(raw: bytes) -> bytes:
return raw