pairing.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. """DM pairing: code-based approval of new users on messaging platforms.
  2. Unknown users receive a one-time pairing code that the bot owner approves via the
  3. CLI, instead of static user-ID allowlists. Security properties (OWASP + NIST SP
  4. 800-63-4): 8-char codes from a 32-char unambiguous alphabet via ``secrets``, 1-hour
  5. expiry, max 3 pending per platform, 1 request per user per 10 min, lockout after 5
  6. failed approvals, chmod 0600 data files, codes never logged. Storage: ~/.hermes/pairing/
  7. """
  8. import contextlib
  9. import hashlib
  10. import json
  11. import logging
  12. import os
  13. import secrets
  14. import threading
  15. import time
  16. from pathlib import Path
  17. from typing import Optional
  18. from gateway.whatsapp_identity import expand_whatsapp_aliases, normalize_whatsapp_identifier
  19. from hermes_constants import get_default_hermes_root, get_hermes_dir, get_hermes_home
  20. from utils import atomic_json_write, file_cache_version
  21. logger = logging.getLogger(__name__)
  22. # Unambiguous alphabet -- excludes 0/O, 1/I to prevent confusion
  23. ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
  24. CODE_LENGTH = 8
  25. CODE_TTL_SECONDS = 3600 # Codes expire after 1 hour
  26. RATE_LIMIT_SECONDS = 600 # 1 request per user per 10 minutes
  27. LOCKOUT_SECONDS = 3600 # Lockout duration after too many failures
  28. MAX_PENDING_PER_PLATFORM = 3 # Max pending codes per platform
  29. MAX_FAILED_ATTEMPTS = 5 # Failed approvals before lockout
  30. DECLINE_DEDUPE_SECONDS = 24 * 3600 # One polite decline per (platform, sender) per window (#88028)
  31. # Default pairing directory override. Deliberately ``None``: an eagerly computed
  32. # path would freeze the HERMES_HOME/profile context at gateway boot, ignoring later
  33. # context-local overrides, so the gateway and ``hermes pairing`` CLI wrote different
  34. # directories. ``_default_pairing_dir()`` resolves fresh per call; tests patch this.
  35. PAIRING_DIR = None
  36. # Default (non-profile-scoped) pairing directory. Left unresolved (``None``) here rather than computed
  37. # eagerly: this module is imported once by the long-lived gateway process at container/process boot, and
  38. # computing the path eagerly freezes it to whatever HERMES_HOME/profile context existed at that exact import
  39. # moment for the rest of the process's lifetime -- even if a context-local override (see
  40. # hermes_constants.set_hermes_home_override) is established afterward. A freshly-started, short-lived
  41. # process (e.g. the ``hermes pairing`` CLI) re-imports this module later with the final environment already
  42. # in place, so it never observes the stale value -- the resulting asymmetry is what made pending pairing
  43. # codes issued by the gateway unrecoverable while CLI-side writes to the same directory kept working
  44. # (NousResearch/hermes-agent#93449). ``_default_pairing_dir()`` below resolves this fresh on every call in
  45. # production. Tests patch this attribute directly to a concrete path for isolation (e.g.
  46. # ``patch("gateway.pairing.PAIRING_DIR", tmp_path)``); that continues to work unchanged, since a patched
  47. # (non-``None``) value takes precedence over recomputing.
  48. def _default_pairing_dir() -> Path:
  49. return PAIRING_DIR if PAIRING_DIR is not None else get_hermes_dir("platforms/pairing", "pairing")
  50. def _allowlist_env_for_platform(platform: str) -> Optional[str]:
  51. """Allowlist env var name for ``platform`` (its ``PlatformEntry.allowed_users_env``), or None.
  52. Approving a code also writes the user into an already-configured allowlist (revoke removes
  53. them) so the operator's list stays the visible source of truth. Platforms without one (or with
  54. no allowlist configured) keep the pairing store as the sole grant record (authz union). See
  55. #23778. Discovers plugins first: ``hermes pairing approve`` runs in a CLI process that may not
  56. have loaded them yet."""
  57. platform = (platform or "").lower().strip()
  58. with contextlib.suppress(Exception):
  59. from hermes_cli.plugins import discover_plugins
  60. discover_plugins() # idempotent
  61. with contextlib.suppress(Exception):
  62. from gateway.platform_env import authz_field
  63. from gateway.platform_registry import platform_registry
  64. return authz_field(platform, "allowed_users_env", platform_registry.get(platform)) or None
  65. return None
  66. def _split_allowlist(raw: str) -> list:
  67. return [uid.strip() for uid in raw.split(",") if uid.strip()]
  68. def _platform_uses_whatsapp_identity(platform: str) -> bool:
  69. """True for Baileys WhatsApp and Meta Cloud — same phone/JID identity rules."""
  70. return (platform or "").strip().lower() in {"whatsapp", "whatsapp_cloud"}
  71. def _normalize_user_id(platform: str, user_id: str) -> str:
  72. """Normalize platform-specific user IDs before persisting / comparing them."""
  73. raw_user_id = str(user_id or "").strip()
  74. return (normalize_whatsapp_identifier(raw_user_id) or raw_user_id) if _platform_uses_whatsapp_identity(platform) else raw_user_id
  75. def _user_id_aliases(platform: str, user_id: str) -> set[str]:
  76. """All known equivalent user IDs for auth / allowlist matching."""
  77. raw_user_id = str(user_id or "").strip()
  78. if not raw_user_id:
  79. return set()
  80. aliases = {raw_user_id, _normalize_user_id(platform, raw_user_id)}
  81. if _platform_uses_whatsapp_identity(platform):
  82. aliases.update(expand_whatsapp_aliases(raw_user_id))
  83. aliases.discard("")
  84. return aliases
  85. def _user_ids_match(platform: str, left: str, right: str) -> bool:
  86. """True when two user IDs represent the same principal."""
  87. left_aliases = _user_id_aliases(platform, left)
  88. return bool(left_aliases and left_aliases & _user_id_aliases(platform, right))
  89. def _matching_ids(platform: str, approved: dict, user_id: str) -> list:
  90. return [uid for uid in approved if _user_ids_match(platform, uid, user_id)]
  91. def _read_allowlist_env(env_var: str) -> str:
  92. """Read a platform allowlist env var through the profile secret scope.
  93. Under multiplexing the process env may hold ANOTHER profile's allowlist, so a
  94. scoped miss must return empty rather than borrow it. The shared reader owns the
  95. contract: a bound-scope failure propagates (never silently borrows the env),
  96. while the unscoped default-profile path keeps the legacy ``os.getenv`` read.
  97. Writes (``save_env_value``/``remove_env_value``) target the active profile's
  98. ``.env`` / installed scope, not ``os.environ``.
  99. See #88441.
  100. """
  101. from gateway.platforms._shared import get_scoped_secret
  102. return (get_scoped_secret(env_var, "") or "").strip()
  103. def _configured_allowlist(platform: str):
  104. """``(env_var, ids)`` for a platform whose allowlist is configured, else None.
  105. An unconfigured allowlist means an open gateway: the pairing store stays the
  106. sole grant record and we must never lock the gateway by materializing one.
  107. """
  108. env_var = _allowlist_env_for_platform(platform)
  109. current = _read_allowlist_env(env_var) if env_var else ""
  110. return (env_var, _split_allowlist(current)) if current else None
  111. def _write_allowlist_env(env_var: str, ids: list) -> None:
  112. """Best-effort persist (empty list removes the key); the pairing store grant still authorizes via the union."""
  113. with contextlib.suppress(Exception):
  114. from hermes_cli.config import save_env_value, remove_env_value
  115. save_env_value(env_var, ",".join(ids)) if ids else remove_env_value(env_var)
  116. def _sync_allowlist_add(platform: str, user_id: str) -> None:
  117. """Add ``user_id`` to the platform allowlist env var IF one is configured."""
  118. configured = _configured_allowlist(platform)
  119. if configured is None:
  120. return
  121. env_var, ids = configured
  122. if "*" in ids or str(user_id) in ids:
  123. return
  124. _write_allowlist_env(env_var, [*ids, str(user_id)])
  125. def _iter_live_gateway_adapters():
  126. """Yield adapters from the in-process GatewayRunner, if one is running."""
  127. runner = None
  128. with contextlib.suppress(Exception):
  129. from gateway.run import _gateway_runner_ref
  130. runner = _gateway_runner_ref()
  131. if runner is None:
  132. return
  133. mappings = [getattr(runner, "adapters", None) or {}, *(getattr(runner, "_profile_adapters", None) or {}).values()]
  134. for mapping in mappings:
  135. for adapter in (mapping or {}).values():
  136. if adapter is not None:
  137. yield adapter
  138. def _adapter_platform_name(adapter) -> str:
  139. value = getattr(getattr(adapter, "platform", None), "value", None)
  140. return str(value or getattr(adapter, "name", None) or "").strip().lower()
  141. def _purge_allowlist_entries(entries, platform: str, user_id: str):
  142. """Drop alias-equivalent allowlist entries while preserving ``*``."""
  143. def keep(entry) -> bool:
  144. return str(entry).strip() == "*" or not _user_ids_match(platform, str(entry), str(user_id))
  145. if isinstance(entries, str):
  146. return ",".join(filter(keep, _split_allowlist(entries)))
  147. if isinstance(entries, (set, frozenset)):
  148. return set(filter(keep, entries))
  149. if isinstance(entries, (list, tuple)):
  150. return list(filter(keep, entries))
  151. return entries
  152. def _sync_live_adapter_allowlist_remove(platform: str, user_id: str) -> None:
  153. """Clear revoked principals from in-process adapter allowlist snapshots,
  154. so intake and adapter-owned controls do not keep authorizing until restart."""
  155. platform_name = (platform or "").strip().lower()
  156. if not platform_name or not str(user_id or "").strip():
  157. return
  158. for adapter in _iter_live_gateway_adapters():
  159. if _adapter_platform_name(adapter) != platform_name:
  160. continue
  161. for attr in ("_allow_from", "_allowed_user_ids"):
  162. if hasattr(adapter, attr):
  163. with contextlib.suppress(Exception):
  164. current = getattr(adapter, attr)
  165. purged = _purge_allowlist_entries(current, platform_name, user_id)
  166. if isinstance(current, set):
  167. # In place: Discord approval views / VoiceReceiver hold this same set.
  168. current.intersection_update(purged)
  169. else:
  170. setattr(adapter, attr, purged)
  171. extra = getattr(getattr(adapter, "config", None), "extra", None)
  172. if isinstance(extra, dict):
  173. for key in ("allow_from", "allowed_users"):
  174. if key in extra:
  175. with contextlib.suppress(Exception):
  176. extra[key] = _purge_allowlist_entries(extra.get(key), platform_name, user_id)
  177. def _sync_allowlist_remove(platform: str, user_id: str) -> None:
  178. """Remove ``user_id`` (and WhatsApp alias equivalents) from the allowlist.
  179. Approve mirrors a normalized phone while revoke is often given a JID/device
  180. form, so matching uses alias rules -- exact delete would leave the sender authorized.
  181. An unconfigured allowlist is left alone (config-only snapshots are not touched).
  182. """
  183. configured = _configured_allowlist(platform)
  184. if configured is None:
  185. return
  186. env_var, ids = configured
  187. remaining = _purge_allowlist_entries(ids, platform, user_id)
  188. if len(remaining) == len(ids):
  189. return # Not present.
  190. _write_allowlist_env(env_var, remaining)
  191. _sync_live_adapter_allowlist_remove(platform, user_id)
  192. def _load_json_file(path: Path) -> dict:
  193. """Read a JSON object; {} when missing, malformed, unreadable, or not a dict.
  194. PermissionError is logged loudly: a 0600 file owned by another uid (Docker:
  195. ``docker exec`` as root wrote it, the gosu-dropped gateway can't read it)
  196. would otherwise silently leave the user unauthorized.
  197. """
  198. if not path.exists():
  199. return {}
  200. try:
  201. data = json.loads(path.read_text(encoding="utf-8-sig"))
  202. return data if isinstance(data, dict) else {}
  203. except PermissionError as e:
  204. try:
  205. # Surface this loudly: a 0600 file owned by a different user (classic Docker symptom: `docker
  206. # exec` runs as root and writes the file, then the gateway process — running as `hermes` after
  207. # gosu drop — can't read it) would otherwise be swallowed by the generic OSError branch below,
  208. # silently leaving the user marked unauthorized. See issue #10270.
  209. st = path.stat()
  210. owner_info = f"owner_uid={st.st_uid} mode={oct(st.st_mode)[-4:]}"
  211. except OSError:
  212. owner_info = "<stat failed>"
  213. euid = os.geteuid() if hasattr(os, "geteuid") else "n/a" # no geteuid on Windows
  214. logger.warning(
  215. "Pairing file %s exists but is not readable as uid=%s (%s; %s). "
  216. "If you ran `docker exec <container> hermes pairing approve ...` as root, "
  217. "re-run with `docker exec -u hermes <container> ...` and "
  218. "chown the existing file to the hermes user, or restart the "
  219. "container so the entrypoint can fix ownership.",
  220. path, euid, owner_info, e,
  221. )
  222. return {}
  223. except (json.JSONDecodeError, OSError):
  224. return {}
  225. def _save_json_file(path: Path, data: dict) -> None:
  226. atomic_json_write(path, data, mode=0o600)
  227. def _migrate_split_pairing_dirs(*, home: Optional[Path] = None, active: Optional[Path] = None) -> None:
  228. """Merge split legacy (``pairing``) / new (``platforms/pairing``) data into the active dir.
  229. If both exist, approved users in the inactive location must not be silently
  230. ignored (they would be asked for a fresh code). Active data wins on key conflict.
  231. """
  232. home = home or get_hermes_home()
  233. old_dir = home / "pairing"
  234. active = active if active is not None else _default_pairing_dir()
  235. alternate = home / "platforms" / "pairing" if active.resolve() == old_dir.resolve() else old_dir
  236. if not alternate.exists() or active.resolve() == alternate.resolve():
  237. return
  238. active.mkdir(parents=True, exist_ok=True)
  239. for src in alternate.glob("*.json"):
  240. merged = _load_json_file(src) if src.is_file() else {}
  241. if not merged:
  242. continue
  243. current = _load_json_file(active / src.name)
  244. merged.update(current)
  245. if merged != current:
  246. _save_json_file(active / src.name, merged)
  247. _dir_lock_holders: dict = {}
  248. _dir_lock_holders_guard = threading.Lock()
  249. def _dir_lock_holder(directory: Path) -> threading.local:
  250. """Per-directory reentrancy holder for ``_file_lock`` (shared by every store on that dir)."""
  251. with _dir_lock_holders_guard:
  252. return _dir_lock_holders.setdefault(str(directory), threading.local())
  253. def _is_hashed_entry(entry) -> bool:
  254. return isinstance(entry, dict) and "salt" in entry and "hash" in entry
  255. def _entry_created_at(info):
  256. """Numeric ``created_at`` of a pending entry, or None for malformed/legacy entries."""
  257. created_at = info.get("created_at") if isinstance(info, dict) else None
  258. return created_at if isinstance(created_at, (int, float)) else None
  259. class PairingStore:
  260. """Pairing codes and approved user lists.
  261. Files per platform: ``{platform}-pending.json``, ``{platform}-approved.json``, plus
  262. shared ``_rate_limits.json``. With ``profile="<name>"`` storage resolves from that
  263. profile's HERMES_HOME exactly as ``hermes -p <name> pairing ...`` does, so multiplex
  264. gateways and profile-scoped CLI approvals share one whitelist.
  265. """
  266. def __init__(self, profile: Optional[str] = None):
  267. profile_home = None
  268. if profile:
  269. root = get_default_hermes_root()
  270. profile_home = root if profile == "default" else root / "profiles" / profile
  271. self._dir = get_hermes_dir("platforms/pairing", "pairing", home=profile_home) if profile else _default_pairing_dir()
  272. self._dir.mkdir(parents=True, exist_ok=True)
  273. # Merge the alternate old/new layout so upgrades cannot split approvals.
  274. _migrate_split_pairing_dirs(home=profile_home, active=self._dir)
  275. self._lock = threading.RLock() # adapters run concurrently in threads sharing one store
  276. self._profile = profile # for diagnostics / log lines
  277. self._approved_cache: dict = {}
  278. @property
  279. def profile(self) -> Optional[str]:
  280. """Profile name this store is scoped to, or None for the global store."""
  281. return self._profile
  282. def _pending_path(self, platform: str) -> Path:
  283. return self._dir / f"{platform}-pending.json"
  284. def _approved_path(self, platform: str) -> Path:
  285. return self._dir / f"{platform}-approved.json"
  286. def _rate_limit_path(self) -> Path:
  287. return self._dir / "_rate_limits.json"
  288. def _decline_stamp_path(self) -> Path:
  289. return self._dir / "_declined.json"
  290. def _cleanup_expired(self, platform: str) -> None:
  291. """Remove expired pending codes; malformed/legacy entries (no numeric ``created_at``) count as expired."""
  292. path = self._pending_path(platform)
  293. pending = self._load_json(path)
  294. now = time.time()
  295. live = {
  296. k: v for k, v in pending.items()
  297. if (created := _entry_created_at(v)) is not None and (now - created) <= CODE_TTL_SECONDS
  298. }
  299. if len(live) != len(pending):
  300. self._save_json(path, live)
  301. @contextlib.contextmanager
  302. def _locked(self):
  303. """Serialize load->mutate->save across stores and processes: the dashboard builds a
  304. store per request and the CLI runs in its own process, so ``self._lock`` alone is not enough.
  305. The file lock is taken FIRST: ``is_approved`` runs on the gateway event loop under
  306. ``self._lock``, so holding it while waiting (up to 10 s) on another process would stall
  307. every chat on that loop. ``is_approved`` never takes the file lock, so the order is safe."""
  308. from hermes_cli.auth import _file_lock
  309. with _file_lock(
  310. self._dir / ".lock", _dir_lock_holder(self._dir), 10.0,
  311. f"Timed out waiting for the pairing store lock ({self._dir})",
  312. ), self._lock:
  313. yield
  314. _load_json = staticmethod(_load_json_file)
  315. _save_json = staticmethod(_save_json_file)
  316. def _platforms(self, platform: Optional[str], suffix: str) -> list:
  317. return [platform] if platform else self._all_platforms(suffix)
  318. # ----- Approved users -----
  319. def _load_approved(self, platform: str) -> dict:
  320. path = self._approved_path(platform)
  321. try:
  322. # Opening first preserves fail-closed authorization if permissions change.
  323. # fstat identifies the actual opened file even during atomic replacement.
  324. with path.open("rb") as stream:
  325. st = os.fstat(stream.fileno())
  326. # Keyed before the parse: a write in between costs one re-parse, never a stale hit.
  327. key = (st.st_dev, *file_cache_version(path, st))
  328. cached = self._approved_cache.get(platform)
  329. if cached is not None and cached[0] == key:
  330. return cached[1]
  331. data = json.load(stream)
  332. data = data if isinstance(data, dict) else {}
  333. except (OSError, json.JSONDecodeError, UnicodeDecodeError):
  334. self._approved_cache.pop(platform, None)
  335. # Keep the existing diagnostics for unreadable pairing files.
  336. return self._load_json(path)
  337. self._approved_cache[platform] = (key, data)
  338. return data
  339. def is_approved(self, platform: str, user_id: str) -> bool:
  340. """Check if a user is approved (paired) on a platform."""
  341. with self._lock:
  342. return bool(_matching_ids(platform, self._load_approved(platform), user_id))
  343. def list_approved(self, platform: str | None = None) -> list:
  344. """List approved users, optionally filtered by platform."""
  345. return [
  346. {"platform": p, "user_id": uid, **info}
  347. for p in self._platforms(platform, "approved")
  348. for uid, info in self._load_json(self._approved_path(p)).items()
  349. ]
  350. def _approve_user(self, platform: str, user_id: str, user_name: str = "") -> None:
  351. """Add a user to the approved list. Must be called under self._locked()."""
  352. approved = self._load_json(self._approved_path(platform))
  353. normalized_user_id = _normalize_user_id(platform, user_id)
  354. for approved_user_id in _matching_ids(platform, approved, normalized_user_id):
  355. del approved[approved_user_id]
  356. approved[normalized_user_id] = {"user_name": user_name, "approved_at": time.time()}
  357. self._save_json(self._approved_path(platform), approved)
  358. # Mirror the grant into the operator's allowlist when one is configured.
  359. _sync_allowlist_add(platform, normalized_user_id)
  360. def revoke(self, platform: str, user_id: str) -> bool:
  361. """Remove a user from the approved list. Returns True if found."""
  362. path = self._approved_path(platform)
  363. with self._locked():
  364. approved = self._load_json(path)
  365. matching_ids = _matching_ids(platform, approved, user_id)
  366. if not matching_ids:
  367. return False
  368. for approved_user_id in matching_ids:
  369. del approved[approved_user_id]
  370. self._save_json(path, approved)
  371. # Keep the allowlist mirror in sync (no-op if added by other means).
  372. _sync_allowlist_remove(platform, user_id)
  373. return True
  374. # ----- Pending codes -----
  375. @staticmethod
  376. def _hash_code(code: str, salt: bytes) -> str:
  377. return hashlib.sha256(salt + code.encode("utf-8")).hexdigest()
  378. def _finish_approval(self, platform: str, pending: dict, matched_key: str, matched_entry: dict) -> dict:
  379. """Remove a pending request and approve its user. Must hold self._locked()."""
  380. del pending[matched_key]
  381. self._save_json(self._pending_path(platform), pending)
  382. # A successful approval proves legitimacy, so the persisted brute-force streak
  383. # must not carry over (isolated typos would accumulate into a spurious lockout).
  384. self._reset_failed_attempts(platform)
  385. result = {"user_id": matched_entry["user_id"], "user_name": matched_entry.get("user_name", "")}
  386. self._approve_user(platform, result["user_id"], result["user_name"])
  387. return result
  388. def generate_code(self, platform: str, user_id: str, user_name: str = "") -> Optional[str]:
  389. """Generate a pairing code for a new user.
  390. Returns None if the user is rate-limited, the platform hit MAX_PENDING_PER_PLATFORM,
  391. or the platform is locked out. Only a salted SHA-256 hash of the code is persisted.
  392. """
  393. with self._locked():
  394. self._cleanup_expired(platform)
  395. normalized_user_id = _normalize_user_id(platform, user_id)
  396. if self._is_locked_out(platform) or self._is_rate_limited(platform, user_id):
  397. return None
  398. pending = self._load_json(self._pending_path(platform))
  399. if len(pending) >= MAX_PENDING_PER_PLATFORM:
  400. return None
  401. code = "".join(secrets.choice(ALPHABET) for _ in range(CODE_LENGTH))
  402. salt = os.urandom(16)
  403. # Keyed by a random entry id, not the code itself.
  404. pending[secrets.token_hex(8)] = {
  405. "hash": self._hash_code(code, salt), "salt": salt.hex(),
  406. "user_id": normalized_user_id, "user_name": user_name, "created_at": time.time(),
  407. }
  408. self._save_json(self._pending_path(platform), pending)
  409. self._record_rate_limit(platform, user_id)
  410. return code
  411. def approve_code(self, platform: str, code: str) -> Optional[dict]:
  412. """Approve a pairing code and add its user to the approved list.
  413. Returns ``{user_id, user_name}``, or ``None`` if the code is invalid/expired OR the
  414. platform is locked out (disambiguate with ``_is_locked_out``). Constant-time
  415. salted-hash compare; legacy plaintext entries are ignored and pruned at TTL.
  416. See #10195.
  417. """
  418. with self._locked():
  419. self._cleanup_expired(platform)
  420. # Chat UIs insert visual spacing between code characters; strip all
  421. # whitespace, then match exactly (surrounding words still fail). #89937
  422. code = "".join(str(code or "").upper().split())
  423. # Before the lookup, or an already-issued valid code would bypass lockout.
  424. if self._is_locked_out(platform):
  425. return None
  426. pending = self._load_json(self._pending_path(platform))
  427. # Skip legacy/malformed entries so an in-place upgrade doesn't crash.
  428. for entry_id, entry in pending.items():
  429. if not _is_hashed_entry(entry):
  430. continue
  431. try:
  432. salt = bytes.fromhex(entry["salt"])
  433. except ValueError:
  434. continue
  435. if secrets.compare_digest(self._hash_code(code, salt), entry["hash"]):
  436. return self._finish_approval(platform, pending, entry_id, entry)
  437. self._record_failed_attempt(platform)
  438. return None
  439. @staticmethod
  440. def looks_like_request_id(value: str) -> bool:
  441. """True when ``value`` is shaped like a ``list_pending`` request id (16 hex chars);
  442. pairing codes are 8 uppercase chars, so callers accepting either can dispatch on this."""
  443. value = str(value or "").strip()
  444. return len(value) == 16 and all(c in "0123456789abcdefABCDEF" for c in value)
  445. def approve_request(self, platform: str, request_id: str) -> Optional[dict]:
  446. """Approve a pending request by its server-side request id (admin surfaces that
  447. must never reveal the DM'd code). Returns ``{user_id, user_name}`` or ``None``.
  448. Neither counts toward nor is gated by the brute-force lockout: a request id is only
  449. obtainable by an authenticated admin, so a stale id is "the row expired", not an
  450. attack -- counting it would let a few GUI clicks lock the operator out.
  451. """
  452. with self._locked():
  453. self._cleanup_expired(platform)
  454. request_id = str(request_id or "").strip().lower()
  455. if not request_id:
  456. return None
  457. pending = self._load_json(self._pending_path(platform))
  458. for entry_id, entry in pending.items():
  459. if _is_hashed_entry(entry) and secrets.compare_digest(str(entry_id).lower(), request_id):
  460. return self._finish_approval(platform, pending, entry_id, entry)
  461. return None
  462. def list_pending(self, platform: str | None = None) -> list:
  463. """List pending requests (codes are never returned; each exposes a ``request_id``
  464. for :meth:`approve_request`; legacy pre-hash entries report an empty id)."""
  465. results = []
  466. with self._locked():
  467. for p in self._platforms(platform, "pending"):
  468. self._cleanup_expired(p)
  469. for entry_id, info in self._load_json(self._pending_path(p)).items():
  470. created_at = _entry_created_at(info)
  471. if created_at is None:
  472. continue
  473. is_modern = isinstance(info.get("hash"), str) and isinstance(info.get("salt"), str)
  474. results.append({
  475. "platform": p,
  476. "request_id": str(entry_id) if is_modern else "",
  477. "user_id": info.get("user_id", ""), "user_name": info.get("user_name", ""),
  478. "age_minutes": int((time.time() - created_at) / 60),
  479. })
  480. return results
  481. def clear_pending(self, platform: str | None = None) -> int:
  482. """Clear all pending requests. Returns count removed."""
  483. with self._locked():
  484. count = 0
  485. for p in self._platforms(platform, "pending"):
  486. count += len(self._load_json(self._pending_path(p)))
  487. self._save_json(self._pending_path(p), {})
  488. return count
  489. # ----- Rate limiting and lockout -----
  490. def _limits(self) -> dict:
  491. return self._load_json(self._rate_limit_path())
  492. def _save_limits(self, limits: dict) -> None:
  493. self._save_json(self._rate_limit_path(), limits)
  494. def _is_rate_limited(self, platform: str, user_id: str) -> bool:
  495. """Whether a user (under any alias) has requested a code too recently."""
  496. limits = self._limits()
  497. return any(
  498. (time.time() - limits.get(f"{platform}:{alias}", 0)) < RATE_LIMIT_SECONDS
  499. for alias in _user_id_aliases(platform, user_id)
  500. )
  501. def _record_rate_limit(self, platform: str, user_id: str) -> None:
  502. limits = self._limits()
  503. now = time.time()
  504. for alias in _user_id_aliases(platform, user_id):
  505. limits[f"{platform}:{alias}"] = now
  506. self._save_limits(limits)
  507. # ----- "decline" unauthorized-DM behavior (#88028) -----
  508. def has_recent_decline(self, platform: str, user_id: str) -> bool:
  509. """Whether this sender (under any alias) was sent a polite decline within DECLINE_DEDUPE_SECONDS."""
  510. stamps = self._load_json(self._decline_stamp_path())
  511. now = time.time()
  512. return any(
  513. isinstance(stamped := stamps.get(f"{platform}:{alias}"), (int, float)) and (now - stamped) < DECLINE_DEDUPE_SECONDS
  514. for alias in _user_id_aliases(platform, user_id)
  515. )
  516. def record_decline(self, platform: str, user_id: str) -> None:
  517. """Stamp the sender (all aliases) and prune expired stamps. Callers stamp BEFORE sending so a
  518. delivery failure cannot become a decline storm on the sender's next message."""
  519. with self._locked():
  520. now = time.time()
  521. stamps = {
  522. key: value for key, value in self._load_json(self._decline_stamp_path()).items()
  523. if isinstance(value, (int, float)) and (now - value) < DECLINE_DEDUPE_SECONDS
  524. }
  525. for alias in _user_id_aliases(platform, user_id):
  526. stamps[f"{platform}:{alias}"] = now
  527. self._save_json(self._decline_stamp_path(), stamps)
  528. def _is_locked_out(self, platform: str) -> bool:
  529. return time.time() < self._limits().get(f"_lockout:{platform}", 0)
  530. def _record_failed_attempt(self, platform: str) -> None:
  531. """Record a failed approval attempt; triggers lockout after MAX_FAILED_ATTEMPTS."""
  532. limits = self._limits()
  533. fail_key = f"_failures:{platform}"
  534. fails = limits.get(fail_key, 0) + 1
  535. limits[fail_key] = fails
  536. if fails >= MAX_FAILED_ATTEMPTS:
  537. limits[f"_lockout:{platform}"] = time.time() + LOCKOUT_SECONDS
  538. limits[fail_key] = 0
  539. print(f"[pairing] Platform {platform} locked out for {LOCKOUT_SECONDS}s "
  540. f"after {MAX_FAILED_ATTEMPTS} failed attempts", flush=True)
  541. self._save_limits(limits)
  542. def _reset_failed_attempts(self, platform: str) -> None:
  543. """Clear the failed-approval counter after a success (it tracks *consecutive* failures)."""
  544. limits = self._limits()
  545. fail_key = f"_failures:{platform}"
  546. if limits.get(fail_key):
  547. limits[fail_key] = 0
  548. self._save_limits(limits)
  549. def _all_platforms(self, suffix: str) -> list:
  550. """Platforms that have a ``-<suffix>.json`` data file (``_``-prefixed files are shared state)."""
  551. tail = f"-{suffix}.json"
  552. platforms = (f.name.replace(tail, "") for f in self._dir.iterdir() if f.name.endswith(tail))
  553. return [p for p in platforms if not p.startswith("_")]