The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): an unusable bot mailbox dir pauses Bot Chat instead of aborting startup
Teknium0a53953c9845
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 1e9c7a20e10..0c2f4812ef7 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -307,7 +307,6 @@ async def serve_profile_runtime(runner, name, home):publish it in the descriptor/ticket store — the steps boot performs per secondary. Raises whenthe profile's store is unusable; the caller parks it (and releases the reservation)."""from gateway.session_authorities import owner_scope- from gateway.session_bot import recover_bot_deliveriesfrom gateway.session_hosted_service import _ensure_hosted_service, start_ready_hosted_servicesfrom gateway.session_local_recovery import recover_local_sessionsfrom gateway.platforms.webhook_ingress import recover_webhook_finalizations@@ -326,7 +325,7 @@ async def serve_profile_runtime(runner, name, home):authority = await _build_profile_authority(runner, name, home, register=False)try:with owner_scope(authority):- await recover_bot_deliveries(authority)+ await recover_bot_mailbox(authority)recover_local_sessions(authority, schedule=True)await recover_webhook_finalizations(authority)if getattr(runner, 'session_control_server', None) is not None:@@ -362,15 +361,30 @@ def _authorities(runner):return all_authorities(runner)+async def recover_bot_mailbox(authority):+ """Owner-startup Bot Chat recovery, skipped when this token cannot use the mailbox dir.++ An elevated install/update can leave ``runtime/bot_live_delivery`` owned by Administrators with+ no entry for the user (#139485, #138872): the gateway cannot even open its ``.lock``. Bot Chat+ deliveries pause (``_locked`` already logged the dir, its owner and the remedy); every other+ client keeps working instead of the whole gateway refusing to start. Any other failure still+ aborts startup."""+ from gateway.session_bot import recover_bot_deliveries+ from tools.bot_live_delivery import MailboxUnusable+ try:+ await recover_bot_deliveries(authority)+ except MailboxUnusable as exc:+ logger.warning('Bot Chat recovery skipped for %s: %s', authority.db.db_path, exc)++async def start_gateway_runtime_api(runner):from gateway.run_api import start_gateway_apifrom gateway.session_authorities import owner_scoperunner.session_api = await start_gateway_api(runner)runner.session_runtime_descriptor['api_origin'] = runner.session_api.api_origin- from gateway.session_bot import recover_bot_deliveriesfor authority in _authorities(runner):with owner_scope(authority):- await recover_bot_deliveries(authority)+ await recover_bot_mailbox(authority)async def recover_gateway_native_sessions(runner):diff --git a/tests/gateway/test_bot_result_recovery.py b/tests/gateway/test_bot_result_recovery.pyindex c51bb6128ce..15a19c59018 100644--- a/tests/gateway/test_bot_result_recovery.py+++ b/tests/gateway/test_bot_result_recovery.py@@ -163,3 +163,65 @@ def test_owner_startup_recovery_survives_a_denied_mailbox_chmod(tmp_path, monkeyassert watched == {'b' * 32}finally:db.close()+++def _deny_mailbox_lock(monkeypatch, home):+ """The reporters' ACL (#139485, #138872) as this token sees it: the mailbox dir exists, but+ ``.lock`` inside it cannot be opened (Windows: no ACE for the user on an Administrators-owned dir)."""+ import os+ from tools.bot_live_delivery import DELIVERY_DIR_NAME+ lock = home.resolve() / 'runtime' / DELIVERY_DIR_NAME / '.lock'+ lock.parent.mkdir(parents=True)+ real_open = os.open++ def deny(path, *args, **kwargs):+ if os.fspath(path) == str(lock):+ raise PermissionError(13, 'Permission denied', str(path))+ return real_open(path, *args, **kwargs)++ monkeypatch.setattr(os, 'open', deny)+ return lock.parent+++def test_gateway_startup_skips_bot_recovery_when_the_mailbox_dir_is_unusable(tmp_path, monkeypatch, caplog):+ """#139485/#138872: an unusable mailbox dir pauses Bot Chat recovery instead of aborting+ ``start_gateway``; the log names the dir, its owner and the remedy."""+ import asyncio+ import logging+ from gateway import run_api, run_runtime+ root = _deny_mailbox_lock(monkeypatch, tmp_path)+ db = SessionDB(tmp_path / 'state.db')+ try:+ runner = SimpleNamespace(session_authority=SimpleNamespace(db=db, waiters={}),+ session_runtime_descriptor={})++ async def api(_runner):+ return SimpleNamespace(api_origin='http://127.0.0.1:1')++ monkeypatch.setattr(run_api, 'start_gateway_api', api)+ with caplog.at_level(logging.DEBUG):+ asyncio.run(run_runtime.start_gateway_runtime_api(runner))+ assert runner.session_runtime_descriptor['api_origin'] == 'http://127.0.0.1:1'+ warnings = [r.getMessage() for r in caplog.records+ if r.levelno == logging.WARNING and 'not usable by this process' in r.getMessage()]+ assert len(warnings) == 1 and str(root) in warnings[0] and '(owner ' in warnings[0]+ assert 'To repair' in warnings[0]+ finally:+ db.close()+++def test_unusable_mailbox_warns_once_per_dir_for_the_live_readers(tmp_path, monkeypatch, caplog):+ """The receipt readers re-enter ``_locked`` twice a second: one WARNING, DEBUG after, and a+ ``PermissionError`` the callers already handle (never a new exception type)."""+ import logging+ import pytest+ from tools import bot_live_delivery as mailbox+ root = _deny_mailbox_lock(monkeypatch, tmp_path)+ with caplog.at_level(logging.DEBUG, logger=mailbox.log.name):+ for _ in range(3):+ with pytest.raises(PermissionError):+ with mailbox._locked(tmp_path):+ pass+ levels = [r.levelno for r in caplog.records if 'not usable by this process' in r.getMessage()]+ assert levels == [logging.WARNING, logging.DEBUG, logging.DEBUG]+ assert root in mailbox._warned_unusablediff --git a/tests/tools/test_bot_live_delivery_windows_acl.py b/tests/tools/test_bot_live_delivery_windows_acl.pyindex 3399429424d..bef1b0d8454 100644--- a/tests/tools/test_bot_live_delivery_windows_acl.py+++ b/tests/tools/test_bot_live_delivery_windows_acl.py@@ -1,10 +1,13 @@-"""#139485 on a real Windows ACL: a mailbox dir that denies FILE_WRITE_ATTRIBUTES makes ``chmod``-raise WinError 5 (as on an Administrators-owned dir seen by a non-elevated user), yet the dir stays usable.+"""#139485 / #138872 on real Windows ACLs.-CPython's Windows ``Path.chmod`` opens the dir with FILE_FLAG_BACKUP_SEMANTICS, so a token with-SeBackupPrivilege/SeRestorePrivilege enabled (an elevated CI runner) bypasses the deny ACE. The-reporter's non-elevated token has neither. The probe runs in a child that drops both privileges from-its own token first, then exercises the production lock.+The reporters' mailbox dir was created by an elevated process: owner BUILTIN\\Administrators, a DACL+with no entry for the user. Their non-elevated gateway can't chmod it, list it or open ``.lock`` in+it, and startup must skip Bot Chat recovery instead of aborting. A second, milder shape (only+FILE_WRITE_ATTRIBUTES denied) leaves the dir usable, and the lock must keep working there.++CPython opens dirs with FILE_FLAG_BACKUP_SEMANTICS, so a token with SeBackupPrivilege/SeRestorePrivilege+enabled (an elevated CI runner) bypasses every ACE. The reporter's token has neither. Each probe runs in a+child that removes both privileges from its own token first, then exercises the production code."""import jsonimport subprocess@@ -18,7 +21,7 @@ pytestmark = pytest.mark.platforms("windows")_REPO = Path(__file__).resolve().parents[2]-_CHILD = textwrap.dedent(r"""+_DROP_PRIVILEGES = textwrap.dedent(r"""import ctypes, ctypes.wintypes as w, json, subprocess, sysfrom pathlib import Path@@ -50,7 +53,9 @@ _CHILD = textwrap.dedent(r"""tp = TOKEN_PRIVILEGES(1, (LUID_AND_ATTRIBUTES * 1)(LUID_AND_ATTRIBUTES(luid, 0x00000004)))if not advapi.AdjustTokenPrivileges(token, False, ctypes.byref(tp), 0, None, None):raise ctypes.WinError(ctypes.get_last_error())+""")+_CHILD = _DROP_PRIVILEGES + textwrap.dedent(r"""from tools import bot_live_delivery as mailboxhome = Path(sys.argv[1])@@ -86,3 +91,71 @@ def test_mailbox_lock_survives_a_dir_whose_acl_denies_write_attributes(tmp_path)assert result["read"] == {"status": "queued"}finally:subprocess.run(["icacls", str(root), "/remove:d", "*S-1-1-0"], check=False, capture_output=True)+++_UNUSABLE_CHILD = _DROP_PRIVILEGES + textwrap.dedent(r"""+ import asyncio, logging, os+ from types import SimpleNamespace++ home = Path(sys.argv[1])+ root = home / "runtime" / "bot_live_delivery"+ try:+ os.close(os.open(root / ".lock", os.O_CREAT | os.O_WRONLY, 0o600))+ denied = False+ except PermissionError:+ denied = True+ if not denied:+ priv = subprocess.run(["whoami", "/priv"], capture_output=True, text=True, check=False).stdout+ print(json.dumps({"denied": False, "priv": priv}))+ sys.exit(0)++ records = []+ handler = logging.Handler()+ handler.emit = lambda record: records.append((record.levelname, record.getMessage()))+ logging.getLogger().addHandler(handler)+ logging.getLogger().setLevel(logging.DEBUG)++ from gateway import run_api, run_runtime+ from hermes_state import SessionDB++ async def api(_runner):+ return SimpleNamespace(api_origin="http://127.0.0.1:1")++ run_api.start_gateway_api = api+ db = SessionDB(home / "state.db")+ try:+ runner = SimpleNamespace(session_authority=SimpleNamespace(db=db, waiters={}),+ session_runtime_descriptor={})+ # The step start_gateway runs per authority; on main it raised and aborted the gateway.+ asyncio.run(run_runtime.start_gateway_runtime_api(runner))+ finally:+ db.close()+ print(json.dumps({"denied": True, "api_origin": runner.session_runtime_descriptor.get("api_origin"),+ "logs": [r for r in records if "bot" in r[1].lower()]}))+""")+++def test_startup_skips_bot_recovery_on_the_reporters_mailbox_acl(tmp_path):+ root = tmp_path / "runtime" / "bot_live_delivery"+ root.mkdir(parents=True)+ # The reporters' shape: Administrators-owned, inheritance cut, only SYSTEM granted. A+ # privilege-dropped token has no ACE to list or create in it; as owner it keeps only the+ # implicit READ_CONTROL/WRITE_DAC, so os.open(.lock) fails exactly as in #138872.+ for args in (["/setowner", "*S-1-5-32-544"], ["/inheritance:r", "/grant:r", "*S-1-5-18:(OI)(CI)F"]):+ subprocess.run(["icacls", str(root), *args], check=True, capture_output=True)+ try:+ child = subprocess.run([sys.executable, "-c", _UNUSABLE_CHILD, str(tmp_path)], cwd=_REPO,+ capture_output=True, text=True, check=False, timeout=180)+ assert child.returncode == 0, f"gateway startup aborted on the reporters' ACL:\n{child.stderr}"+ result = json.loads(child.stdout.strip().splitlines()[-1])+ assert result["denied"], f"os.open(.lock) succeeded without backup/restore privileges:\n{result['priv']}"+ assert result["api_origin"] == "http://127.0.0.1:1"+ warnings = [message for level, message in result["logs"]+ if level == "WARNING" and "not usable by this process" in message]+ assert len(warnings) == 1, result["logs"]+ assert str(root.resolve()) in warnings[0] and "(owner " in warnings[0]+ assert "icacls" in warnings[0] and "/reset" in warnings[0]+ finally:+ # Give the dir back to this (elevated) test so pytest can delete tmp_path.+ subprocess.run(["icacls", str(root), "/grant", "*S-1-5-32-544:(OI)(CI)F"], check=False, capture_output=True)+ subprocess.run(["icacls", str(root), "/reset", "/t", "/c"], check=False, capture_output=True)diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex 64cd6c669d5..b44a5e8c1d1 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -12,7 +12,7 @@ import osimport reimport timeimport uuid-from contextlib import contextmanager+from contextlib import ExitStack, contextmanagerfrom utils import atomic_json_write, atomic_write_text, fsync_directoryfrom pathlib import Path@@ -116,11 +116,62 @@ def has_mailbox(profile_home: Path | str) -> bool:_warned_unhardened: set[Path] = set()+# Mailbox dirs already reported unusable by this process: WARNING once per dir, DEBUG after,+# because the receipt readers re-enter ``_locked`` while Bot Chat is waiting.+_warned_unusable: set[Path] = set()-@contextmanager-def _locked(home: Path | str):- root = _root(home)+class MailboxUnusable(PermissionError):+ """This token cannot list, create or lock inside the mailbox dir (#139485, #138872).++ On Windows an elevated install/update creates ``runtime/bot_live_delivery`` owned by+ Administrators with no entry for the user; the same user's non-elevated gateway then+ cannot even open ``.lock``. Bot Chat deliveries pause; nothing else depends on the dir.+ A ``PermissionError`` subclass so every existing caller keeps its handling.+ """+++def _dir_owner(path: Path) -> str:+ """Best-effort owner name for the log line; never raises (an ACL that hides it is the reported case)."""+ if os.name == "nt":+ try:+ import pywintypes+ import win32security+ except ImportError as exc:+ return f"unknown ({exc})"+ try:+ descriptor = win32security.GetFileSecurity(str(path), win32security.OWNER_SECURITY_INFORMATION)+ name, domain, _ = win32security.LookupAccountSid(None, descriptor.GetSecurityDescriptorOwner())+ except pywintypes.error as exc:+ return f"unknown ({exc})"+ return f"{domain}\\{name}" if domain else name+ import pwd # windows-footgun: ok — POSIX branch only++ try:+ uid = path.stat().st_uid+ except OSError as exc:+ return f"unknown ({exc})"+ try:+ return pwd.getpwuid(uid).pw_name+ except KeyError:+ return f"uid {uid}"+++def _unusable(root: Path, exc: PermissionError) -> MailboxUnusable:+ if os.name == "nt":+ remedy = f'from an elevated prompt run: icacls "{root}" /reset /t'+ else:+ remedy = f'run: sudo chown -R "$(id -un)" "{root}"'+ level = logging.DEBUG if root in _warned_unusable else logging.WARNING+ _warned_unusable.add(root)+ log.log(level, "bot_live_delivery: mailbox directory %s (owner %s) is not usable by this process (%s); "+ "Bot Chat deliveries are paused until it is repaired, other clients are unaffected. To repair, %s",+ root, _dir_owner(root), exc, remedy)+ return MailboxUnusable(exc.errno, f"bot mailbox directory is not usable: {exc}", str(root))+++def _prepare(root: Path) -> Path:+ """Create/harden the mailbox dir and its ``.lock`` file; returns the lock path."""created = not root.is_dir()root.parent.mkdir(parents=True, exist_ok=True)root.mkdir(mode=0o700, exist_ok=True)@@ -145,7 +196,20 @@ def _locked(home: Path | str):lock = root / ".lock"fd = os.open(lock, os.O_CREAT | os.O_WRONLY, 0o600)os.close(fd)- with _FileLock(lock):+ return lock+++@contextmanager+def _locked(home: Path | str):+ """Hold the mailbox dir lock. A dir this token cannot use raises ``MailboxUnusable``+ (logged once per dir with its owner and the remedy); errors inside the body pass through."""+ root = _root(home)+ with ExitStack() as stack:+ try:+ stack.enter_context(_FileLock(_prepare(root)))+ except PermissionError as exc:+ raise _unusable(root, exc) from exc+ _warned_unusable.discard(root)yield root