The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): surface the messaging platform's auth posture in the Test result
Austin Pickette93446126d5e
diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.pyindex bbf2d7bb7fe..bb50fa77c96 100644--- a/hermes_cli/web_routers/messaging.py+++ b/hermes_cli/web_routers/messaging.py@@ -954,15 +954,147 @@ def _notify_multiplexer_hot_serve(profile: Optional[str]) -> bool:return notify_multiplexer_profiles_changed(name) is not None+def _gate_env(name: str) -> str:+ """Per-profile allow/deny gate env read, always stripped (gateway seam)."""+ from gateway.platforms._shared import platform_gate_env++ return platform_gate_env(name)+++def _platform_authz_env_names(platform_id: str) -> tuple[str, str]:+ """``(allowed_users_env, allow_all_env)`` for a platform, honoring plugin registry+ entries. Empty strings mean "this platform has no per-user authorization surface"+ (webhook-style trusted inbound or unknown), so no posture is computed for it."""+ from gateway.pairing import _PLATFORM_ALLOWLIST_ENV++ allowed = _PLATFORM_ALLOWLIST_ENV.get(platform_id, "")+ allow_all = allowed.replace("_ALLOWED_USERS", "_ALLOW_ALL_USERS")+ if not allowed:+ with contextlib.suppress(Exception):+ from gateway.platform_registry import platform_registry++ entry = platform_registry.get(platform_id)+ if entry is not None:+ if getattr(entry, "trusted_inbound", False) is True:+ return "", ""+ allowed = getattr(entry, "allowed_users_env", "") or ""+ allow_all = getattr(entry, "allow_all_env", "") or ""+ return allowed, allow_all+++def _platform_dm_policy(platform_id: str) -> str:+ """Effective ``dm_policy`` for the ACTIVE profile's ``platforms.<id>`` config+ (``open``/``allowlist``/``disabled``/``pairing``). The default here is NOT the adapter+ default: adapters without a config key never consult ``dm_policy`` in+ ``_principal_authorized``, so a policy-shaped key only matters where one exists."""+ with contextlib.suppress(Exception):+ plat_cfg = (load_config().get("platforms") or {}).get(platform_id)+ if isinstance(plat_cfg, dict):+ policy = str(plat_cfg.get("extra", {}).get("dm_policy") or "").strip().lower()+ if policy:+ return policy+ return ""+++def _count_csv(value: str) -> int:+ return len([part for part in (value or "").split(",") if part.strip()])+++def _messaging_platform_posture(platform_id: str, entry: dict[str, Any], scoped: bool) -> dict[str, Any] | None:+ """Auth-posture verdict for a CONNECTED platform (must be called inside the profile+ scope, after the connectivity chain has already reported ``connected``).++ Mirrors the decision ladder of ``AuthorizationMixin._principal_authorized``+ (gateway/authz_mixin.py) for the "can any user reach the bot" question, evaluated+ against the ACTIVE profile's env/config only — never the dashboard process's+ ``os.environ`` (which carries the ROOT profile's credentials, #66030):++ - allow-all flags: ``{PLATFORM}_ALLOW_ALL_USERS`` then ``GATEWAY_ALLOW_ALL_USERS``+ - allowlists: the platform's ``{PLATFORM}_ALLOWED_USERS``, ``GATEWAY_ALLOWED_USERS``,+ plus the Telegram group vars (a group-only grant still authorizes real users)+ - pairing grants: approved users in the profile's pairing store (the gateway honors+ the store as a UNION with the allowlists)+ - adapter/config-enforced policy (``dm_policy: allowlist`` with an ``allow_from``):+ the own-policy adapters (WeCom, Weixin, QQBot, WhatsApp, Yuanbao) gate at intake++ Everything failing → deny-all: the connection is up but no sender can get through,+ which the Channels "Test" button must not render as a plain green "connected".+ Returns ``None`` when the platform has no per-user authorization surface at all.+ """+ allowed_env, allow_all_env = _platform_authz_env_names(platform_id)+ if not allowed_env:+ return None++ # Same scoped-vs-process split _platform_enablement uses: under a named profile the+ # process env belongs to the ROOT install and must not authorize anyone here, and a+ # profile's .env must not borrow the root's allowlists (false green) either.+ def gate_env(name: str) -> str:+ if scoped:+ return load_env().get(name, "")+ return _gate_env(name)++ if allow_all_env and gate_env(allow_all_env).lower() in ("true", "1", "yes"):+ return {"posture": "open", "message": f"{entry['name']} is open: {allow_all_env} is set."}+ if gate_env("GATEWAY_ALLOW_ALL_USERS").lower() in ("true", "1", "yes"):+ return {"posture": "open", "message": "Gateway is open: GATEWAY_ALLOW_ALL_USERS is set."}++ allowlists = {+ allowed_env: gate_env(allowed_env),+ "GATEWAY_ALLOWED_USERS": gate_env("GATEWAY_ALLOWED_USERS"),+ "TELEGRAM_GROUP_ALLOWED_USERS": gate_env("TELEGRAM_GROUP_ALLOWED_USERS") if platform_id == "telegram" else "",+ "TELEGRAM_GROUP_ALLOWED_CHATS": gate_env("TELEGRAM_GROUP_ALLOWED_CHATS") if platform_id == "telegram" else "",+ }+ for env_name, value in allowlists.items():+ if value.strip():+ n = _count_csv(value)+ return {+ "posture": "allowlist",+ "message": f"Connected. {n} user{'s' if n != 1 else ''} allowlisted via {env_name}.",+ }++ if _platform_dm_policy(platform_id) == "allowlist":+ return {"posture": "allowlist", "message": "Connected. Access restricted by the configured allow_from policy."}++ # Pairing grants: the profile's approved users (the gateway honors the store as a+ # union with any allowlist, gateway/authz_mixin.py `_pairing_store_for`).+ approved = pending = 0+ with contextlib.suppress(Exception):+ from gateway.pairing import PairingStore++ store = PairingStore()+ approved = len(store.list_approved(platform_id))+ pending = len(store.list_pending(platform_id))+ if approved:+ return {+ "posture": "pairing",+ "message": f"Connected. {approved} user{'s' if approved != 1 else ''} paired.",+ }++ base = (+ f"{entry['name']} is connected, but no users are authorized yet — "+ f"set {allowed_env}, approve a pairing request, or enable pairing for new users."+ )+ if pending:+ base += f" {pending} pairing request{'s' if pending != 1 else ''} pending approval."+ return {"posture": "deny_all", "message": base}++@router.post("/api/messaging/platforms/{platform_id}/test")async def test_messaging_platform(platform_id: str, profile: Optional[str] = None):entry = _require_platform(platform_id)def _run():with _profile_scope(profile) as scoped_dir:- return _platform_payloads(scoped_dir, [entry])[0]+ payload = _platform_payloads(scoped_dir, [entry])[0]+ posture = None+ if payload["state"] == "connected":+ # Still inside the profile scope: load_env()/load_config()/PairingStore+ # must resolve the ACTIVE profile's env/config/pairing store, not the+ # dashboard process's root home.+ posture = _messaging_platform_posture(platform_id, entry, scoped_dir is not None)+ return payload, posture- payload = await asyncio.to_thread(_run)+ payload, posture = await asyncio.to_thread(_run)def result(ok: bool, message: str) -> dict[str, Any]:return {"ok": ok, "state": payload["state"], "message": message}@@ -975,7 +1107,17 @@ async def test_messaging_platform(platform_id: str, profile: Optional[str] = Nonif not payload["gateway_running"]:return result(False, "Gateway is not running. Restart the gateway to connect this platform.")if payload["state"] == "connected":- return result(True, f"{entry['name']} is connected.")+ # Non-breaking extension (#66030): keep ok=True (the connection is genuinely up)+ # but surface the platform's auth posture so the UI can render yellow on+ # connected-but-unreachable, and say exactly what to configure.+ if posture is None:+ return result(True, f"{entry['name']} is connected.")+ return {+ "ok": True,+ "state": payload["state"],+ "message": posture["message"],+ "auth_posture": posture["posture"],+ }if payload.get("error_message"):return result(False, payload["error_message"])return result(False, "Setup looks complete, but the gateway has not reported a connection yet. Restart the gateway.")diff --git a/tests/hermes_cli/test_web_server_messaging_posture.py b/tests/hermes_cli/test_web_server_messaging_posture.pynew file mode 100644index 00000000000..c26d61eda69--- /dev/null+++ b/tests/hermes_cli/test_web_server_messaging_posture.py@@ -0,0 +1,187 @@+"""The Channels "Test" button must answer the auth-posture question too (#66030).++``POST /api/messaging/platforms/{platform_id}/test`` used to stop at connectivity:+a Telegram bot whose gateway denies every sender (no allowlists, no allow-all flag,+no pairing grants) still answered ``ok: true, "Telegram is connected."`` — a green+checkmark on a bot that ignores everyone. The test result now carries the platform's+access posture for the ACTIVE profile (allowlist / open / pairing / deny_all),+counting pairing grants, evaluated against the profile's own env/config/pairing+store — never the dashboard process's environment.+"""+import json+import os+from pathlib import Path++import pytest+++_VALID_BOT_TOKEN = "123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ_1234"+++def _gateway_state(home: Path) -> None:+ """A live gateway record: this pytest process's PID wearing a gateway command+ line, with the Telegram adapter reported ``connected``."""+ import gateway.status as _gw_status++ start_time = _gw_status._get_process_start_time(os.getpid())+ (home / "gateway.pid").write_text(+ json.dumps({"pid": os.getpid(), "hermes_home": str(home)}), encoding="utf-8"+ )+ (home / "gateway_state.json").write_text(json.dumps({+ "pid": os.getpid(), "hermes_home": str(home), "gateway_state": "running",+ "kind": "hermes-gateway", "start_time": start_time,+ "updated_at": "2026-01-01T00:00:00+00:00",+ "platforms": {"telegram": {"state": "connected", "writer_pid": os.getpid()}},+ }), encoding="utf-8")+++def client(monkeypatch, _isolate_hermes_home):+ from starlette.testclient import TestClient++ import hermes_state+ import hermes_constants+ import gateway.status as _gw_status+ from hermes_constants import get_hermes_home+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN++ home = get_hermes_home()+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", home / "state.db")+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)+ # Liveness is a verified identity: this pytest process passes as the gateway+ # only while its probed command line matches the home being asked about+ # (``_command_line_belongs_to_profile``). The worker test below re-points the+ # faked command line at ``-p worker`` before its request.+ cmdline = {"current": "hermes gateway run"}+ monkeypatch.setattr(+ _gw_status, "_read_process_cmdline", lambda pid: cmdline["current"]+ )+ # The dashboard process's own env must never authorize anyone here.+ for var in ("TELEGRAM_BOT_TOKEN", "TELEGRAM_ALLOWED_USERS", "GATEWAY_ALLOWED_USERS",+ "GATEWAY_ALLOW_ALL_USERS", "TELEGRAM_GROUP_ALLOWED_USERS",+ "TELEGRAM_GROUP_ALLOWED_CHATS"):+ monkeypatch.delenv(var, raising=False)++ (home / ".env").write_text(f"TELEGRAM_BOT_TOKEN={_VALID_BOT_TOKEN}\n", encoding="utf-8")+ (home / "config.yaml").write_text("platforms:\n telegram:\n enabled: true\n", encoding="utf-8")+ _gateway_state(home)+ c = TestClient(app)+ c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ return c+++def _test(client, **params):+ resp = client.post("/api/messaging/platforms/telegram/test", params=params)+ assert resp.status_code == 200, resp.text+ return resp.json()+++def test_connected_deny_all_reports_posture(client):+ """Connected, but nothing a user can do would reach the agent — the exact+ incident from the report (#66030): green "connected" for three days."""+ payload = _test(client)+ assert payload["ok"] is True+ assert payload["state"] == "connected"+ assert payload["auth_posture"] == "deny_all"+ assert "TELEGRAM_ALLOWED_USERS" in payload["message"]+++def test_connected_with_allowlist_reports_allowlist(client, monkeypatch):+ from hermes_constants import get_hermes_home++ monkeypatch.setenv("TELEGRAM_ALLOWED_USERS", "42, 43")+ payload = _test(client)+ assert payload["ok"] is True+ assert payload["auth_posture"] == "allowlist"+ assert "2 users allowlisted via TELEGRAM_ALLOWED_USERS" in payload["message"]+++def test_connected_with_global_allow_all_reports_open(client, monkeypatch):+ monkeypatch.setenv("GATEWAY_ALLOW_ALL_USERS", "true")+ payload = _test(client)+ assert payload["ok"] is True+ assert payload["auth_posture"] == "open"+++def test_connected_with_gateway_allowed_users_reports_allowlist(client, monkeypatch):+ monkeypatch.setenv("GATEWAY_ALLOWED_USERS", "42")+ payload = _test(client)+ assert payload["ok"] is True+ assert payload["auth_posture"] == "allowlist"+ assert "GATEWAY_ALLOWED_USERS" in payload["message"]+++def test_connected_with_pairing_grant_counts_it(client):+ """An approved pairing request is a first-class grant (authz union): a store+ with one approved user is reachable, not deny-all."""+ from gateway.pairing import PairingStore++ store = PairingStore()+ store._approve_user("telegram", "42", "operator")+ try:+ payload = _test(client)+ assert payload["auth_posture"] == "pairing"+ assert "1 user paired" in payload["message"]+ finally:+ store.revoke("telegram", "42")+++def test_connected_deny_all_mentions_pending_pairing_requests(client):+ import time as _time++ from gateway.pairing import PairingStore++ store = PairingStore()+ with store._lock:+ # A pending (unapproved) request is NOT a grant; the posture stays deny_all+ # and the message points the operator at the waiting request (fresh enough+ # to survive the store's TTL cleanup).+ pending = {"r1": {"user_id": "42", "user_name": "operator", "created_at": _time.time(),+ "hash": "0" * 64, "salt": "00" * 16}}+ store._save_json(store._pending_path("telegram"), pending)+ try:+ payload = _test(client)+ assert payload["auth_posture"] == "deny_all"+ assert "1 pairing request pending approval" in payload["message"]+ finally:+ store.clear_pending("telegram")+++def test_profile_scoped_posture_ignores_root_env_and_reports_profile_grants(+ client, monkeypatch, tmp_path+):+ """The dashboard process env belongs to the ROOT install: a named profile's+ Test must neither borrow the root's allowlist nor miss the profile's own.+ Regression for the false deny-all/false green in the #66055 review."""+ import gateway.status as _gw_status+ from hermes_cli import profiles as profiles_mod+ from hermes_constants import get_hermes_home++ default_home = get_hermes_home()+ profiles_root = default_home / "profiles"+ worker_home = profiles_root / "worker"+ worker_home.mkdir(parents=True)+ (worker_home / "config.yaml").write_text("platforms:\n telegram:\n enabled: true\n", encoding="utf-8")+ (worker_home / ".env").write_text(f"TELEGRAM_BOT_TOKEN={_VALID_BOT_TOKEN}\n", encoding="utf-8")+ _gateway_state(worker_home)+ monkeypatch.setattr(profiles_mod, "_get_default_hermes_home", lambda: default_home)+ monkeypatch.setattr(profiles_mod, "_get_profiles_root", lambda: profiles_root)+ # ROOT-env allowlist must not authorize the worker profile's bot.+ monkeypatch.setenv("TELEGRAM_ALLOWED_USERS", "111,222")+ # The verified gateway identity must belong to the WORKER home: a bare "gateway+ # run" belongs to the default profile, so the worker's liveness probe needs the+ # ``-p worker`` command line (same identity check ``hermes -p worker status`` runs).+ monkeypatch.setattr(+ _gw_status, "_read_process_cmdline", lambda pid: "hermes gateway run -p worker"+ )++ payload = _test(client, profile="worker")+ assert payload["auth_posture"] == "deny_all"++ # The profile's own allowlist wins when present.+ (worker_home / ".env").write_text(+ f"TELEGRAM_BOT_TOKEN={_VALID_BOT_TOKEN}\nTELEGRAM_ALLOWED_USERS=7\n", encoding="utf-8"+ )+ payload = _test(client, profile="worker")+ assert payload["auth_posture"] == "allowlist"+ assert "TELEGRAM_ALLOWED_USERS" in payload["message"]