Skip to content

The agent that grows with you

fix(gateway): recover a stale gateway.lock this user cannot use, never a held or linked one

Teknium62063f25d287
diff --git a/gateway/runtime_ownership.py b/gateway/runtime_ownership.py
index e08ffafda42..a6757f84db4 100644
--- a/gateway/runtime_ownership.py
+++ b/gateway/runtime_ownership.py
@@ -1,6 +1,8 @@
"""Nonblocking, all-or-nothing reservations of canonical profile homes.
-Lock inodes are never removed: unlinking a locked inode creates a second owner.
+A held lock inode is never removed: unlinking it creates a second owner. The one exception is a
+stale inode this user cannot use (left by a gateway that ran as root, #42685) that is provably
+unheld; it is replaced once, and every winner checks that the path still names the inode it locked.
"""
from __future__ import annotations
@@ -41,6 +43,94 @@ def tighten_lock_mode(fd: int) -> None:
os.fchmod(fd, 0o600) # windows-footgun: ok — POSIX branch
+_LOCK_FLAGS = os.O_RDWR | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0)
+
+
+def _open_checked(path: Path, flags: int) -> int:
+ fd = os.open(path, flags, 0o600)
+ try:
+ tighten_lock_mode(fd)
+ except BaseException:
+ os.close(fd)
+ raise
+ return fd
+
+
+def _inode_locked_per_proc(ino: int) -> bool | None:
+ """Linux ``/proc/locks``: whether any lock names inode *ino* (on any device, so a btrfs/overlay
+ st_dev mismatch can only refuse, never miss a holder). None where the table is unavailable."""
+ try:
+ table = Path('/proc/locks').read_text(encoding='ascii', errors='replace')
+ except OSError:
+ return None
+ suffix = f':{ino}'
+ return any(field.endswith(suffix) and field.count(':') == 2
+ for line in table.splitlines() for field in line.split())
+
+
+def _unlink_stale_lock(path: Path) -> bool:
+ """Unlink a ``gateway.lock`` this user cannot use (unopenable, or another uid's) when no process
+ holds it: a flock probe through a read-only descriptor, else Linux ``/proc/locks``. Symlinks,
+ hardlinks, non-regular files, a home whose ``gateway.pid`` names a live process and anything not
+ provably unheld are left in place (False)."""
+ from gateway.status import _live_pid_from_record, _read_pid_record
+ if os.name == 'nt':
+ return False # a sharing violation is a live holder there
+ info = os.lstat(path)
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
+ return False
+ if _live_pid_from_record(_read_pid_record(path.with_name('gateway.pid'))) is not None:
+ return False
+ try:
+ probe = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | os.O_NONBLOCK)
+ except PermissionError:
+ return _inode_locked_per_proc(info.st_ino) is False and _unlink_if_same(path, info)
+ import fcntl
+ try:
+ if not _same_inode(os.fstat(probe), info):
+ return False
+ try:
+ fcntl.flock(probe, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return False
+ # Unlinked while still locked: a late locker of the old inode never shares our lock.
+ return _unlink_if_same(path, info)
+ finally:
+ os.close(probe)
+
+
+def _unlink_if_same(path: Path, info) -> bool:
+ if not _same_inode(os.lstat(path), info):
+ return False
+ os.unlink(path)
+ return True
+
+
+def _same_inode(left, right) -> bool:
+ return (left.st_dev, left.st_ino) == (right.st_dev, right.st_ino)
+
+
+def _open_lock(path: Path) -> int:
+ """Descriptor for *path*, replacing a provably stale inode this user cannot use once."""
+ try:
+ return _open_checked(path, _LOCK_FLAGS)
+ except PermissionError:
+ if not _unlink_stale_lock(path):
+ raise
+ # A racer may create the fresh inode first; both then contend for its flock as usual.
+ return _open_checked(path, _LOCK_FLAGS)
+
+
+def _still_names(path: Path, fd: int) -> bool:
+ """True when *path* is still the inode *fd* locked (a stale-lock replacement unlinks it)."""
+ if os.name == 'nt':
+ return True
+ try:
+ return _same_inode(os.lstat(path), os.fstat(fd))
+ except FileNotFoundError:
+ return False
+
+
class ProfileOwnership:
def __init__(self):
self._handles: dict[Path, object] = {}
@@ -62,12 +152,10 @@ class ProfileOwnership:
continue
home.mkdir(mode=0o700, parents=True, exist_ok=True)
path = home / 'gateway.lock'
- flags = os.O_RDWR | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0)
- fd = os.open(path, flags, 0o600)
- handle = os.fdopen(fd, 'r+', encoding='utf-8')
+ fd = _open_lock(path)
+ handle = os.fdopen(fd, 'r+', encoding='utf-8') # windows-footgun: ok — write-only
try:
- tighten_lock_mode(handle.fileno())
- if not _try_acquire_file_lock(handle):
+ if not _try_acquire_file_lock(handle) or not _still_names(path, handle.fileno()):
raise OwnershipConflict(f'Gateway runtime already owns profile {home}')
record = {**_build_pid_record(), 'hermes_home': str(home)}
handle.seek(0)
diff --git a/tests/gateway/test_runtime_ownership.py b/tests/gateway/test_runtime_ownership.py
index 1cb9e7c687c..8fbdad6a9b5 100644
--- a/tests/gateway/test_runtime_ownership.py
+++ b/tests/gateway/test_runtime_ownership.py
@@ -115,3 +115,60 @@ def test_profile_reservations_unwind_without_releasing_another_owner(tmp_path):
blocker.reserve([homes[1]])
free.close()
contender.close()
+
+
[email protected](hasattr(os, 'geteuid') and os.geteuid() == 0, reason="root opens a mode-000 file")
[email protected]("mode", [0o000, 0o400])
+def test_stale_unopenable_gateway_lock_is_replaced_on_boot(tmp_path, monkeypatch, mode):
+ """Main's #42685: a lock this user cannot open (left by a root-run gateway) and that no process
+ holds is unlinked and recreated, so boot does not exit "already held" forever."""
+ import json
+ from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock
+ home = tmp_path / 'home'
+ home.mkdir(mode=0o700)
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ lock = home / 'gateway.lock'
+ lock.write_text('{"pid": 1}', encoding='utf-8')
+ lock.chmod(mode)
+ try:
+ assert acquire_gateway_runtime_lock()
+ assert lock.stat().st_mode & 0o777 == 0o600 # a fresh inode (the stale one is not ours to chmod)
+ assert json.loads(lock.read_text(encoding='utf-8-sig'))['pid'] == os.getpid()
+ finally:
+ release_gateway_runtime_lock()
+
+
[email protected](hasattr(os, 'geteuid') and os.geteuid() == 0, reason="root opens a mode-000 file")
+def test_unusable_gateway_lock_held_or_linked_is_never_unlinked(tmp_path):
+ """The stale-lock recovery never removes an inode a live process holds, and never follows a
+ symlink or touches a hardlinked lock."""
+ from gateway import runtime_ownership
+ homes = {kind: tmp_path / kind for kind in ('held', 'held_readable', 'hardlink', 'symlink')}
+ for home in homes.values():
+ home.mkdir(mode=0o700)
+ held = [homes[kind] / 'gateway.lock' for kind in ('held', 'held_readable')]
+ for path in held:
+ path.write_text('', encoding='utf-8')
+ holder = subprocess.Popen( # a live owner (flock on both inodes) from another process
+ [sys.executable, '-c', 'import fcntl,sys;fs=[open(p) for p in sys.argv[1:]];'
+ '[fcntl.flock(f,fcntl.LOCK_EX) for f in fs];print(1,flush=True);sys.stdin.read()',
+ *map(str, held)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ try:
+ assert holder.stdout.readline().strip() == '1'
+ held[0].chmod(0) # unopenable: only /proc/locks can show the holder
+ held[1].chmod(0o400) # readable: the flock probe sees the holder
+ (tmp_path / 'other').write_text('', encoding='utf-8')
+ os.link(tmp_path / 'other', homes['hardlink'] / 'gateway.lock')
+ (homes['hardlink'] / 'gateway.lock').chmod(0)
+ (homes['symlink'] / 'gateway.lock').symlink_to(tmp_path / 'target')
+ before = {kind: os.lstat(home / 'gateway.lock').st_ino for kind, home in homes.items()}
+ for kind, home in homes.items():
+ with pytest.raises(OSError):
+ runtime_ownership.ProfileOwnership().reserve([home])
+ assert os.lstat(home / 'gateway.lock').st_ino == before[kind], kind
+ assert not (tmp_path / 'target').exists()
+ finally:
+ holder.stdin.close()
+ holder.wait(timeout=10)
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index f060f8cefcb..de69238c999 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -1523,6 +1523,9 @@ class TestPermissionErrorOnLockFile:
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
lock = tmp_path / "gateway.lock"
lock.write_text("existing owner")
+ # The owner is live (its gateway.pid names a running process): an unopenable lock with no
+ # provable holder is the stale #42685 case and is replaced (test_runtime_ownership).
+ (tmp_path / "gateway.pid").write_text(json.dumps({"pid": os.getpid()}), encoding="utf-8")
inode = lock.stat().st_ino
lock.chmod(0)
try: