From c396ce2d5e4eee64b9f28c875b1c8099dcc7a92b Mon Sep 17 00:00:00 2001 From: OpenBot Date: Tue, 13 Oct 2026 16:05:42 +0800 Subject: [PATCH] feat(admin): auth + four data panels (sessions/conversations/approvals/config) - HTTP Basic auth from config http.admin (constant-time compare; absent config -> UI/api fail-closed 503, legacy JSON endpoints stay open) - GET /api/sessions: bindings + pinned model + idle - GET /api/conversations: hub-side text logs (tail 50/binding) - GET /api/approvals: pending permission requests incl. options/presented - GET /api/config: effective config with secret-looking values redacted - UI: tabbed layout (Overview/Sessions/Conversations/Approvals/Config), approvals tab shows pending count badge --- src/agenthub/admin_data.py | 131 +++++++++++++++++++++++++++++++ src/agenthub/admin_ui.py | 157 +++++++++++++++++++++++++------------ src/agenthub/http_admin.py | 100 +++++++++++++++++++---- src/agenthub/runtime.py | 8 +- tests/test_admin_ui.py | 124 ++++++++++++++++++++++------- 5 files changed, 423 insertions(+), 97 deletions(-) create mode 100644 src/agenthub/admin_data.py diff --git a/src/agenthub/admin_data.py b/src/agenthub/admin_data.py new file mode 100644 index 0000000..65e1d1a --- /dev/null +++ b/src/agenthub/admin_data.py @@ -0,0 +1,131 @@ +"""Admin UI data endpoints + auth for agenthub (added to StatusHTTP). + +Auth: HTTP Basic. Credentials live in config["http"]["admin"] = {"username", +"password"} (config.json / agenthub-etc/config.json, 0600 — secrets never in +code or docs). If admin block is absent, UI+data endpoints serve 503 with a +hint (fail-closed); /healthz and /status stay open (nginx already gates them). + +New read-only endpoints (all auth-gated): + GET /api/conversations -> hub-side conversation text per binding + GET /api/approvals -> pending permission requests + GET /api/sessions -> bindings + pinned model config + GET /api/config -> sanitized effective config +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import time +from typing import Any + + +def check_auth(header_value: str | None, admin_cfg: dict[str, Any] | None) -> bool: + """Constant-time Basic auth check. Fail-closed when admin_cfg is None/empty.""" + if not admin_cfg or not admin_cfg.get("username") or not admin_cfg.get("password"): + return False + if not header_value or not header_value.startswith("Basic "): + return False + try: + raw = base64.b64decode(header_value[6:]).decode("utf-8", "replace") + user, _, pw = raw.partition(":") + except Exception: # noqa: BLE001 + return False + ok_u = hmac.compare_digest(user, str(admin_cfg["username"])) + ok_p = hmac.compare_digest(pw, str(admin_cfg["password"])) + return ok_u and ok_p + + +def sanitize_config(cfg: dict[str, Any]) -> dict[str, Any]: + """Config view for the UI: structure only, secret-looking values redacted.""" + SECRET_KEYS = {"secret", "password", "token", "key", "app_secret", "api_key"} + + def redact(obj: Any, parent_key: str = "") -> Any: + if isinstance(obj, dict): + out = {} + for k, v in obj.items(): + if any(s in k.lower() for s in SECRET_KEYS) and isinstance(v, str) and v: + out[k] = v[:4] + "…[REDACTED]" + else: + out[k] = redact(v, k) + return out + if isinstance(obj, list): + return [redact(x) for x in obj] + return obj + + return redact(cfg) + + +def conversations_payload(mgr: Any) -> dict[str, Any]: + """Hub-side text logs (SessionRecord.text_log), newest first, tail-limited.""" + items = [] + with mgr._lock: + for key, rec in getattr(mgr, "_records", {}).items(): + log = rec.text_log[-50:] + items.append( + { + "binding_key": key, + "agent": rec.agent, + "acp_session_id": rec.acp_session_id, + "updated_at": rec.updated_at, + "turns": len(rec.text_log), + "log": log, + } + ) + items.sort(key=lambda x: x["updated_at"], reverse=True) + return {"conversations": items} + + +def approvals_payload(mgr: Any) -> dict[str, Any]: + """Pending permission requests (live memory state).""" + now = time.time() + items = [] + with mgr._lock: + for rid, p in getattr(mgr, "_pending_permissions", {}).items(): + items.append( + { + "request_id": rid, + "agent": p.agent, + "session_id": p.session_id, + "key": p.key, + "tool_title": p.tool_title, + "tool_kind": p.tool_kind, + "options": p.options, + "presented": p.presented, + "age_s": round(now - p.created_at, 1), + "answered": p.answered.is_set(), + "choice": p.choice, + } + ) + items.sort(key=lambda x: x["age_s"], reverse=True) + return {"approvals": items} + + +def sessions_payload(mgr: Any) -> dict[str, Any]: + """Bindings enriched with the pinned per-session model (if known).""" + out = [] + with mgr._lock: + bindings = list(mgr._bindings.items()) + for (channel, chat_id), b in bindings: + cfg_model = None + try: + sc = mgr._session_config(b) # {"model": {"current": ..., "options": [...]}} + cfg_model = sc.get("model", {}).get("current") + except Exception: # noqa: BLE001 + pass + out.append( + { + "channel": channel, + "chat_id": chat_id, + "agent": b.agent, + "acp_session_id": b.acp_session_id, + "model": cfg_model, + "created_at": b.created_at, + "last_active": b.last_active, + "idle_s": round(time.time() - b.last_active, 1), + } + ) + out.sort(key=lambda x: x["last_active"], reverse=True) + return {"sessions": out} diff --git a/src/agenthub/admin_ui.py b/src/agenthub/admin_ui.py index e4f3191..32192c0 100644 --- a/src/agenthub/admin_ui.py +++ b/src/agenthub/admin_ui.py @@ -1,40 +1,57 @@ """Admin UI for agenthub — single-file dashboard served by StatusHTTP. Design: dark terminal-inspired theme, pure stdlib (no build step), auto-refresh. -Panels: service health, channels (connection state), agents (running procs), -live session bindings. All data comes from the existing /status + /sessions -endpoints — the UI is a static HTML string that fetches JSON client-side. +Tabs: Overview (health/channels/agents/bindings), Sessions (pinned models, +idle), Conversations (hub-side text logs), Approvals (pending permission +requests), Config (sanitized effective config). Data from /status, /sessions +and auth-gated /api/* endpoints; browser caches Basic credentials per session. """ DARK_CSS = """ :root{--bg:#0d1117;--panel:#161b22;--border:#30363d;--fg:#e6edf3;--muted:#8b949e; ---green:#3fb950;--red:#f85149;--amber:#d29922;--blue:#58a6ff;--mono:ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace} +--green:#3fb950;--red:#f85149;--amber:#d29922;--blue:#58a6ff; +--mono:ui-monospace,'SF Mono','Cascadia Code',Menlo,monospace} *{box-sizing:border-box;margin:0;padding:0} -body{background:var(--bg);color:var(--fg);font-family:var(--mono);font-size:14px;padding:24px;max-width:1200px;margin:0 auto} +body{background:var(--bg);color:var(--fg);font-family:var(--mono);font-size:14px;padding:24px;max-width:1280px;margin:0 auto} h1{font-size:18px;font-weight:600;display:flex;align-items:center;gap:10px;margin-bottom:4px} h1 .sub{font-size:12px;color:var(--muted);font-weight:400} +.tabs{display:flex;gap:4px;margin-top:16px;border-bottom:1px solid var(--border)} +.tab{padding:8px 16px;cursor:pointer;color:var(--muted);border:1px solid transparent;border-bottom:none;border-radius:6px 6px 0 0;font-size:13px} +.tab:hover{color:var(--fg)} +.tab.on{color:var(--fg);background:var(--panel);border-color:var(--border);position:relative;top:1px} .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:16px;margin-top:18px} -.card{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:16px} +.card{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:16px;margin-bottom:16px} .card h2{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:12px;display:flex;justify-content:space-between;align-items:center} .pill{font-size:11px;padding:2px 8px;border-radius:10px;font-weight:600} .pill.ok{background:#12351d;color:var(--green)} .pill.bad{background:#3d1418;color:var(--red)} .pill.warn{background:#33290c;color:var(--amber)} -.row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--border)} +.row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--border);gap:8px} .row:last-child{border-bottom:none} .row .k{color:var(--muted)} -.dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:8px} +.dot{width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:8px;flex-shrink:0} .dot.ok{background:var(--green)}.dot.bad{background:var(--red)}.dot.warn{background:var(--amber)}.dot.idle{background:var(--muted)} .kv{font-size:22px;font-weight:600} .meta{color:var(--muted);font-size:12px;margin-top:6px} table{width:100%;border-collapse:collapse;font-size:13px} th{color:var(--muted);text-align:left;font-weight:500;padding:6px 8px;border-bottom:1px solid var(--border);font-size:11px;text-transform:uppercase;letter-spacing:.06em} -td{padding:8px;border-bottom:1px solid var(--border)} +td{padding:8px;border-bottom:1px solid var(--border);vertical-align:top} tr:last-child td{border-bottom:none} code{background:#21262d;padding:1px 6px;border-radius:4px;font-size:12px;color:var(--blue)} #refresh{color:var(--muted);font-size:11px;cursor:pointer;user-select:none} #refresh:hover{color:var(--blue)} .empty{color:var(--muted);font-style:italic;padding:12px 0;font-size:13px} +.msg{padding:6px 10px;border-left:3px solid var(--border);margin:6px 0;border-radius:0 6px 6px 0;font-size:13px;white-space:pre-wrap;word-break:break-word} +.msg.user{border-color:var(--blue);background:rgba(88,166,255,.06)} +.msg.assistant{border-color:var(--green);background:rgba(63,185,80,.05)} +.msg .who{font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);display:block;margin-bottom:2px} +.opts{margin-top:6px;font-size:12px;color:var(--muted)} +.badge{display:inline-block;padding:1px 7px;border-radius:8px;font-size:11px;background:#21262d;color:var(--muted);margin-right:4px} +.badge.kind-deny{background:#3d1418;color:var(--red)} +.badge.kind-allow{background:#12351d;color:var(--green)} +pre.config{font-size:12px;color:var(--muted);white-space:pre-wrap;word-break:break-all;max-height:520px;overflow:auto} +.age{color:var(--muted);font-size:12px;font-weight:400;text-transform:none;letter-spacing:0} +.stale{color:var(--amber)} """ HTML = """ @@ -44,53 +61,95 @@ HTML = """

⚡ agenthub ACP bridge · IM ⇄ NATS ⇄ agents

refreshed — · ↻ refresh · auto 10s
-
-

Service …

-
-
—
agents
-
—
sessions
-
—
uptime
-
+
+
-

Channels

- -

Agents

- -

Live Bindings

-
""" diff --git a/src/agenthub/http_admin.py b/src/agenthub/http_admin.py index 4c17a57..34a3f56 100644 --- a/src/agenthub/http_admin.py +++ b/src/agenthub/http_admin.py @@ -1,11 +1,18 @@ -"""Minimal HTTP surface for nginx reverse proxy (/agents). +"""HTTP surface for nginx reverse proxy (/agents). -Endpoints (read-only): - GET /agents/ -> service overview {status, agents, uptime} - GET /agents/status -> same as above - GET /agents/sessions -> live bindings - GET /agents/healthz -> liveness (200) - POST /agents/prompt -> {channel, chat_id, text, agent?, cwd?} (ops tool; loopback-guarded) +Endpoints (JSON, programmatic — open, nginx-level gating applies): + GET /agents/status -> {status, agents, channels, uptime} + GET /agents/sessions -> live bindings (legacy; superseded by /api/sessions) + GET /agents/healthz -> liveness (200) + POST /agents/prompt -> {channel, chat_id, text, agent?, cwd?} (ops tool) + +Admin UI (auth-gated via HTTP Basic from config http.admin; fail-closed 503 +when http.admin is absent): + GET /agents/ , /ui -> dashboard HTML + GET /agents/api/conversations -> hub-side conversation logs + GET /agents/api/approvals -> pending permission requests + GET /agents/api/sessions -> bindings + pinned model + GET /agents/api/config -> sanitized effective config Runs a ThreadingHTTPServer in-thread; bound to loopback by default — nginx on the same host proxies https://api.vxquant.com/agents/ to it. @@ -20,14 +27,29 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any from urllib.parse import parse_qs, urlparse +from agenthub.admin_data import ( + approvals_payload, + check_auth, + conversations_payload, + sanitize_config, + sessions_payload, +) from agenthub.admin_ui import render_index class StatusHTTP: - def __init__(self, mgr: Any, host: str = "127.0.0.1", port: int = 30990): + def __init__( + self, + mgr: Any, + host: str = "127.0.0.1", + port: int = 30990, + admin_cfg: dict[str, Any] | None = None, + ): self.mgr = mgr self.host = host self.port = port + self.admin_cfg = admin_cfg # {"username","password"} or None (fail-closed) + self.effective_cfg: dict[str, Any] = {} # injected by runtime.main() self.started = time.time() self.channels: list = [] # injected by runtime.main() after build_channels self._server: ThreadingHTTPServer | None = None @@ -46,6 +68,28 @@ class StatusHTTP: self.end_headers() self.wfile.write(data) + def _html(self, data: bytes) -> None: + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _require_auth(self) -> bool: + if check_auth(self.headers.get("Authorization"), outer.admin_cfg): + return True + if outer.admin_cfg: + self.send_response(401) + self.send_header("WWW-Authenticate", 'Basic realm="agenthub"') + self.send_header("Content-Length", "0") + self.end_headers() + else: + self._json( + 503, + {"error": "admin auth not configured; set http.admin in config.json"}, + ) + return False + def _route_get(self, path: str, qs: dict) -> None: m = outer.mgr if path in ("/", "/status"): @@ -87,6 +131,26 @@ class StatusHTTP: } ) self._json(200, {"bindings": bindings}) + elif path in ("/ui", "/index.html"): + if not self._require_auth(): + return + self._html(render_index().encode()) + elif path == "/api/conversations": + if not self._require_auth(): + return + self._json(200, conversations_payload(m)) + elif path == "/api/approvals": + if not self._require_auth(): + return + self._json(200, approvals_payload(m)) + elif path == "/api/sessions": + if not self._require_auth(): + return + self._json(200, sessions_payload(m)) + elif path == "/api/config": + if not self._require_auth(): + return + self._json(200, {"config": sanitize_config(outer.effective_cfg)}) else: self._json(404, {"error": "not found"}) @@ -110,17 +174,19 @@ class StatusHTTP: def do_GET(self): parsed = urlparse(self.path) path = parsed.path.rstrip("/") or "/" - if path in ("/", "/ui", "/index.html"): - # Admin UI (browser-facing): the same nginx /agents/ prefix - # serves it; JSON endpoints remain for programmatic access. - data = render_index().encode() - self.send_response(200) - self.send_header("Content-Type", "text/html; charset=utf-8") - self.send_header("Content-Length", str(len(data))) - self.end_headers() - self.wfile.write(data) + if path == "/": + # With auth configured, / serves the dashboard (browser entry). + # Without auth config, keep the legacy open JSON status so + # existing scripts don't break. + if outer.admin_cfg is not None: + if not self._require_auth(): + return + self._html(render_index().encode()) + return + self._route_get(path, parse_qs(parsed.query)) return self._route_get(path, parse_qs(parsed.query)) + def do_POST(self): length = int(self.headers.get("Content-Length", 0)) self._route_post(urlparse(self.path).path.rstrip("/"), self.rfile.read(length)) diff --git a/src/agenthub/runtime.py b/src/agenthub/runtime.py index ace5965..aa46bc7 100644 --- a/src/agenthub/runtime.py +++ b/src/agenthub/runtime.py @@ -194,8 +194,14 @@ def main(argv: list[str] | None = None) -> None: from .http_admin import StatusHTTP http_cfg = cfg.get("http", {}) - http = StatusHTTP(mgr, host=http_cfg.get("listen_host", "127.0.0.1"), port=int(http_cfg.get("port", 30990))) + http = StatusHTTP( + mgr, + host=http_cfg.get("listen_host", "127.0.0.1"), + port=int(http_cfg.get("port", 30990)), + admin_cfg=http_cfg.get("admin"), # None -> UI/api fail-closed 503 + ) http.channels = chans # /status reports per-channel connection state + http.effective_cfg = cfg # /api/config (sanitized at render time) http.start() log.info(f"status http on {http.host}:{http.port}") except Exception as e: # noqa: BLE001 diff --git a/tests/test_admin_ui.py b/tests/test_admin_ui.py index 7d4abde..57e980b 100644 --- a/tests/test_admin_ui.py +++ b/tests/test_admin_ui.py @@ -1,15 +1,20 @@ -"""Tests for the admin UI endpoint (served on / and /ui).""" +"""Tests for admin UI + auth + data endpoints (served on /, /ui, /api/*).""" +import base64 import json import threading import time +import urllib.error import urllib.request from unittest.mock import MagicMock import pytest +from agenthub.admin_data import check_auth, sanitize_config from agenthub.http_admin import StatusHTTP +ADMIN = {"username": "ops", "password": "s3cret"} + class FakeBinding: def __init__(self, channel, chat_id, agent, acp_session_id): @@ -17,58 +22,117 @@ class FakeBinding: self.chat_id = chat_id self.agent = agent self.acp_session_id = acp_session_id + self.created_at = time.time() self.last_active = time.time() -@pytest.fixture -def server(): +class FakeRecord: + def __init__(self, key, agent, sid, log): + self.binding_key = key + self.agent = agent + self.acp_session_id = sid + self.text_log = log + self.updated_at = time.time() + + +def make_mgr(): mgr = MagicMock() mgr.list_agents.return_value = [ {"name": "opencode", "cmd": "opencode acp", "running": True}, - {"name": "codex", "cmd": "codex acp", "running": False}, ] - mgr._bindings = { - ("wecom", "c1"): FakeBinding("wecom", "c1", "opencode", "s1"), + b = FakeBinding("wecom", "c1", "opencode", "s1") + mgr._bindings = {("wecom", "c1"): b} + mgr._records = { + "wecom:c1": FakeRecord( + "wecom:c1", "opencode", "s1", + [{"role": "user", "text": "hi"}, {"role": "assistant", "text": "hello"}], + ) } + mgr._pending_permissions = {} mgr._lock = threading.Lock() - http = StatusHTTP(mgr, host="127.0.0.1", port=0) # port 0 = ephemeral + mgr._session_config.return_value = {"model": {"current": "opencode/mimo-v2.6-flash-free"}} + return mgr + + +@pytest.fixture +def auth_server(): + http = StatusHTTP(make_mgr(), host="127.0.0.1", port=0, admin_cfg=ADMIN) http.start() port = http._server.server_address[1] yield f"http://127.0.0.1:{port}" http.stop() -def _get(url): - with urllib.request.urlopen(url, timeout=5) as r: - return r.status, r.read() +@pytest.fixture +def open_server(): + http = StatusHTTP(make_mgr(), host="127.0.0.1", port=0, admin_cfg=None) + http.start() + port = http._server.server_address[1] + yield f"http://127.0.0.1:{port}" + http.stop() -def test_root_serves_html(server): - code, body = _get(server + "/") - assert code == 200 - assert b"text/html" not in body # header not in body; content check below - assert b"agenthub" in body - assert b"" in body +def _get(url, auth=None): + req = urllib.request.Request(url) + if auth: + req.add_header("Authorization", "Basic " + base64.b64encode(auth.encode()).decode()) + try: + with urllib.request.urlopen(req, timeout=5) as r: + return r.status, r.read() + except urllib.error.HTTPError as e: + return e.code, e.read() -def test_ui_alias(server): - code, body = _get(server + "/ui") +# --- auth unit --- + +def test_check_auth_ok_and_bad(): + assert check_auth("Basic " + base64.b64encode(b"ops:s3cret").decode(), ADMIN) + assert not check_auth("Basic " + base64.b64encode(b"ops:wrong").decode(), ADMIN) + assert not check_auth(None, ADMIN) + assert not check_auth("Basic abc", ADMIN) # malformed b64 -> False + assert not check_auth("Basic " + base64.b64encode(b"ops:s3cret").decode(), None) # fail-closed + + +def test_sanitize_config_redacts_secrets(): + cfg = {"channels": [{"name": "wecom", "secret": "abcdef123456"}], "http": {"port": 30990}} + out = sanitize_config(cfg) + assert out["channels"][0]["secret"].endswith("[REDACTED]") + assert "abcdef123456" not in json.dumps(out) + assert out["http"]["port"] == 30990 + + +# --- auth-gated server --- + +def test_root_requires_auth(auth_server): + code, _ = _get(auth_server + "/") + assert code == 401 + + +def test_ui_ok_with_auth(auth_server): + code, body = _get(auth_server + "/ui", auth="ops:s3cret") assert code == 200 and b"" in body -def test_json_endpoints_still_work(server): - code, body = _get(server + "/status") +def test_api_endpoints(auth_server): + code, body = _get(auth_server + "/api/sessions", auth="ops:s3cret") d = json.loads(body) - assert d["service"] == "agenthub" - assert len(d["agents"]) == 2 - code, body = _get(server + "/sessions") + assert d["sessions"][0]["model"] == "opencode/mimo-v2.6-flash-free" + code, body = _get(auth_server + "/api/conversations", auth="ops:s3cret") d = json.loads(body) - assert d["bindings"][0]["agent"] == "opencode" + assert d["conversations"][0]["turns"] == 2 + assert d["conversations"][0]["log"][0]["text"] == "hi" + code, body = _get(auth_server + "/api/approvals", auth="ops:s3cret") + assert json.loads(body)["approvals"] == [] -def test_html_references_fetch_targets(server): - _, body = _get(server + "/") - # UI fetches status/sessions relatively — must not hardcode hosts - assert b"fetch('status')" in body - assert b"fetch('sessions')" in body - assert b"botflow_truncated" not in body # sanity: unrelated content absent +def test_open_server_ui_fail_closed(open_server): + code, body = _get(open_server + "/ui") + assert code == 503 + assert b"not configured" in body + + +def test_open_server_legacy_json_survives(open_server): + code, body = _get(open_server + "/status") + assert code == 200 + code, body = _get(open_server + "/sessions") + assert code == 200 and b"bindings" in body