Skip to content

The agent that grows with you

fix(gateway): pairing store edits are serialized across processes

Maciej Lisiewski5fbc692a6b68
diff --git a/gateway/pairing.py b/gateway/pairing.py
index a66014979be..0e49e256112 100644
--- a/gateway/pairing.py
+++ b/gateway/pairing.py
@@ -312,6 +312,16 @@ def _migrate_split_pairing_dirs(*, home: Optional[Path] = None, active: Optional
_save_json_file(active / src.name, merged)
+_dir_lock_holders: dict = {}
+_dir_lock_holders_guard = threading.Lock()
+
+
+def _dir_lock_holder(directory: Path) -> threading.local:
+ """Per-directory reentrancy holder for ``_file_lock`` (shared by every store on that dir)."""
+ with _dir_lock_holders_guard:
+ return _dir_lock_holders.setdefault(str(directory), threading.local())
+
+
def _is_hashed_entry(entry) -> bool:
return isinstance(entry, dict) and "salt" in entry and "hash" in entry
@@ -373,6 +383,20 @@ class PairingStore:
if len(live) != len(pending):
self._save_json(path, live)
+ @contextlib.contextmanager
+ def _locked(self):
+ """Serialize load->mutate->save across stores and processes: the dashboard builds a
+ store per request and the CLI runs in its own process, so ``self._lock`` alone is not enough.
+ The file lock is taken FIRST: ``is_approved`` runs on the gateway event loop under
+ ``self._lock``, so holding it while waiting (up to 10 s) on another process would stall
+ every chat on that loop. ``is_approved`` never takes the file lock, so the order is safe."""
+ from hermes_cli.auth import _file_lock
+ with _file_lock(
+ self._dir / ".lock", _dir_lock_holder(self._dir), 10.0,
+ f"Timed out waiting for the pairing store lock ({self._dir})",
+ ), self._lock:
+ yield
+
_load_json = staticmethod(_load_json_file)
_save_json = staticmethod(_save_json_file)
@@ -415,7 +439,7 @@ class PairingStore:
]
def _approve_user(self, platform: str, user_id: str, user_name: str = "") -> None:
- """Add a user to the approved list. Must be called under self._lock."""
+ """Add a user to the approved list. Must be called under self._locked()."""
approved = self._load_json(self._approved_path(platform))
normalized_user_id = _normalize_user_id(platform, user_id)
for approved_user_id in _matching_ids(platform, approved, normalized_user_id):
@@ -428,7 +452,7 @@ class PairingStore:
def revoke(self, platform: str, user_id: str) -> bool:
"""Remove a user from the approved list. Returns True if found."""
path = self._approved_path(platform)
- with self._lock:
+ with self._locked():
approved = self._load_json(path)
matching_ids = _matching_ids(platform, approved, user_id)
if not matching_ids:
@@ -447,7 +471,7 @@ class PairingStore:
return hashlib.sha256(salt + code.encode("utf-8")).hexdigest()
def _finish_approval(self, platform: str, pending: dict, matched_key: str, matched_entry: dict) -> dict:
- """Remove a pending request and approve its user. Must hold self._lock."""
+ """Remove a pending request and approve its user. Must hold self._locked()."""
del pending[matched_key]
self._save_json(self._pending_path(platform), pending)
# A successful approval proves legitimacy, so the persisted brute-force streak
@@ -463,7 +487,7 @@ class PairingStore:
Returns None if the user is rate-limited, the platform hit MAX_PENDING_PER_PLATFORM,
or the platform is locked out. Only a salted SHA-256 hash of the code is persisted.
"""
- with self._lock:
+ with self._locked():
self._cleanup_expired(platform)
normalized_user_id = _normalize_user_id(platform, user_id)
if self._is_locked_out(platform) or self._is_rate_limited(platform, user_id):
@@ -491,7 +515,7 @@ class PairingStore:
See #10195.
"""
- with self._lock:
+ with self._locked():
self._cleanup_expired(platform)
# Chat UIs insert visual spacing between code characters; strip all
# whitespace, then match exactly (surrounding words still fail). #89937
@@ -528,7 +552,7 @@ class PairingStore:
obtainable by an authenticated admin, so a stale id is "the row expired", not an
attack -- counting it would let a few GUI clicks lock the operator out.
"""
- with self._lock:
+ with self._locked():
self._cleanup_expired(platform)
request_id = str(request_id or "").strip().lower()
if not request_id:
@@ -543,7 +567,7 @@ class PairingStore:
"""List pending requests (codes are never returned; each exposes a ``request_id``
for :meth:`approve_request`; legacy pre-hash entries report an empty id)."""
results = []
- with self._lock:
+ with self._locked():
for p in self._platforms(platform, "pending"):
self._cleanup_expired(p)
for entry_id, info in self._load_json(self._pending_path(p)).items():
@@ -561,7 +585,7 @@ class PairingStore:
def clear_pending(self, platform: str | None = None) -> int:
"""Clear all pending requests. Returns count removed."""
- with self._lock:
+ with self._locked():
count = 0
for p in self._platforms(platform, "pending"):
count += len(self._load_json(self._pending_path(p)))
@@ -605,7 +629,7 @@ class PairingStore:
def record_decline(self, platform: str, user_id: str) -> None:
"""Stamp the sender (all aliases) and prune expired stamps. Callers stamp BEFORE sending so a
delivery failure cannot become a decline storm on the sender's next message."""
- with self._lock:
+ with self._locked():
now = time.time()
stamps = {
key: value for key, value in self._load_json(self._decline_stamp_path()).items()
diff --git a/tests/gateway/test_pairing.py b/tests/gateway/test_pairing.py
index 9bf3fba9c1b..2c2af8e627e 100644
--- a/tests/gateway/test_pairing.py
+++ b/tests/gateway/test_pairing.py
@@ -3,12 +3,15 @@
import json
import os
import sys
+import threading
import time
from pathlib import Path
from unittest.mock import patch
import pytest
+from tests.lock_contention import watch_file_lock_contention
+from tests.waiting import wait_until
from gateway.pairing import (
PairingStore,
ALPHABET,
@@ -506,6 +509,47 @@ class TestRevoke:
with patch("gateway.pairing.PAIRING_DIR", tmp_path):
assert store.is_approved("telegram", "user1") is False
+ def test_revoke_from_other_store_is_not_undone_by_inflight_approval(self, tmp_path, monkeypatch):
+ """Dashboard requests and the ``hermes pairing`` CLI each build their own store, so
+ an approval that read approved.json before a revoke landed must not write it back."""
+ with patch("gateway.pairing.PAIRING_DIR", tmp_path), \
+ patch("gateway.pairing._sync_allowlist_add"), patch("gateway.pairing._sync_allowlist_remove"):
+ seed = PairingStore()
+ seed._approve_user("telegram", "carol")
+ code = seed.generate_code("telegram", "alice", "Alice")
+ dashboard = PairingStore()
+ cli = PairingStore()
+ approved_path = dashboard._approved_path("telegram")
+ contended = watch_file_lock_contention(monkeypatch)
+ revoke_done = threading.Event()
+ revoke_result = []
+ real_load = dashboard._load_json
+
+ def revoke_in_other_process():
+ revoke_result.append(cli.revoke("telegram", "carol"))
+ revoke_done.set()
+
+ def load_then_let_revoke_run(path):
+ data = real_load(path)
+ if path == approved_path and not revoke_result and threading.current_thread().name == "dashboard":
+ threading.Thread(target=revoke_in_other_process, daemon=True).start()
+ # Unserialized stores let the revoke finish inside this window; serialized ones
+ # are seen blocking on the pairing lock instead.
+ wait_until(lambda: revoke_done.is_set() or contended.is_set(),
+ what="the revoke finished or blocked on the pairing lock")
+ return data
+
+ dashboard._load_json = load_then_let_revoke_run
+ approver = threading.Thread(target=dashboard.approve_code, args=("telegram", code), name="dashboard")
+ approver.start()
+ approver.join(10)
+ assert revoke_done.wait(10)
+
+ final = json.loads(approved_path.read_text())
+ assert revoke_result == [True]
+ assert "alice" in final
+ assert "carol" not in final
+
# ---------------------------------------------------------------------------
# List & clear