Skip to content

The agent that grows with you

fix(webhook): transact subscription mutations

FroRaut3082d00c8281
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.py
index 404008299a3..2a5096408dc 100644
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@ -61,6 +61,7 @@ DEFAULT_HOST = None
DEFAULT_PORT = 8644
_INSECURE_NO_AUTH = "INSECURE_NO_AUTH"
_DYNAMIC_ROUTES_FILENAME = "webhook_subscriptions.json"
+_DYNAMIC_ROUTES_UNLOADED = object()
_RATE_WINDOW_SECONDS = 60.0
# Hosts that only serve same-machine connections; anything else is a public bind.
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "ip6-localhost", "ip6-loopback"})
@@ -197,7 +198,7 @@ class WebhookAdapter(BasePlatformAdapter):
self._global_secret: str = extra.get("secret", "")
self._static_routes: Dict[str, dict] = extra.get("routes", {})
self._dynamic_routes: Dict[str, dict] = {}
- self._dynamic_routes_mtime: float = 0.0
+ self._dynamic_routes_revision: object = _DYNAMIC_ROUTES_UNLOADED
self._routes: Dict[str, dict] = dict(self._static_routes)
self._runner = None
self._v1_signature_warned: set[str] = set() # routes already warned about legacy V1 (once per route)
@@ -395,25 +396,19 @@ class WebhookAdapter(BasePlatformAdapter):
return True
def _reload_dynamic_routes(self) -> None:
- """Reload agent-created subscriptions from disk if the file changed."""
- from hermes_constants import get_hermes_home
- subs_path = get_hermes_home() / _DYNAMIC_ROUTES_FILENAME
- if not subs_path.exists():
- if self._dynamic_routes:
- self._dynamic_routes, self._routes = {}, dict(self._static_routes)
- logger.debug("[webhook] Dynamic subscriptions file removed, cleared dynamic routes")
- return
+ """Publish one coherent, lock-held subscription snapshot when its content changes."""
try:
- mtime = subs_path.stat().st_mtime
- if mtime <= self._dynamic_routes_mtime:
+ from hermes_cli.webhook import _load_subscriptions_snapshot
+
+ data, revision = _load_subscriptions_snapshot()
+ if revision == self._dynamic_routes_revision:
return # No change
- data = json.loads(subs_path.read_text(encoding="utf-8-sig"))
- if not isinstance(data, dict):
- return
self._dynamic_routes = { # static routes take precedence
- k: v for k, v in data.items() if k not in self._static_routes and self._dynamic_route_allowed(k, v)}
+ k: v for k, v in data.items()
+ if isinstance(v, dict) and k not in self._static_routes and self._dynamic_route_allowed(k, v)
+ }
self._routes = {**self._dynamic_routes, **self._static_routes}
- self._dynamic_routes_mtime = mtime
+ self._dynamic_routes_revision = revision
logger.info("[webhook] Reloaded %d dynamic route(s): %s", len(self._dynamic_routes),
", ".join(self._dynamic_routes.keys()) or "(none)")
except Exception as e:
diff --git a/hermes_cli/subcommands/webhook.py b/hermes_cli/subcommands/webhook.py
index 7870a22dfab..1b85b7d2536 100644
--- a/hermes_cli/subcommands/webhook.py
+++ b/hermes_cli/subcommands/webhook.py
@@ -30,6 +30,7 @@ def build_webhook_parser(subparsers, *, cmd_webhook: Callable) -> None:
"--route-profile", dest="route_profile", default=None, metavar="PROFILE",
help="Bind the route to a multiplexed profile: only POSTs to /p/PROFILE/webhooks/<name> "
"are accepted and the agent runs as that profile (default: default; kept on update). "
+ "Changing an existing route's profile rotates its HMAC secret unless a different --secret is supplied. "
"Distinct from the global -p/--profile, which picks the gateway whose subscriptions "
"file is written.")
wh_sub.add_argument(
diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py
index 838ab680272..d14660894e3 100644
--- a/hermes_cli/web_routers/ops.py
+++ b/hermes_cli/web_routers/ops.py
@@ -208,6 +208,12 @@ async def create_webhook(body: WebhookCreate, profile: Optional[str] = None):
status_code=400, detail="Direct delivery requires a real target (telegram, discord, …), not 'log'.",
)
+ def _snapshot():
+ subscriptions = wh._load_subscriptions()
+ return subscriptions.get(name, wh._MISSING_SUBSCRIPTION)
+
+ expected = await config_scoped_to_thread(profile, _snapshot)
+
secret = body.secret or secrets.token_urlsafe(32)
route: Dict[str, Any] = {
"description": body.description or f"Dashboard-created subscription: {name}",
@@ -224,11 +230,14 @@ async def create_webhook(body: WebhookCreate, profile: Optional[str] = None):
route["deliver_only"] = True
if body.deliver_chat_id:
route["deliver_extra"] = {"chat_id": body.deliver_chat_id}
+ if isinstance(expected, dict) and expected.get("enabled") is False:
+ route["enabled"] = False
def _save():
- subs = wh._load_subscriptions()
- subs[name] = route
- wh._save_subscriptions(subs)
+ try:
+ wh._replace_subscription(name, route, expected)
+ except wh.SubscriptionMutationConflict as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
return _webhook_route_summary(name, route, wh._get_webhook_base_url())
summary = await config_scoped_to_thread(profile, _save)
@@ -236,16 +245,12 @@ async def create_webhook(body: WebhookCreate, profile: Optional[str] = None):
return summary
-def _webhook_subs_with(name: str):
- """(module, subscriptions, key) for an existing route; 404 otherwise. Call inside the
- request's profile scope — ``_load_subscriptions`` resolves the home at call time."""
- import hermes_cli.webhook as wh
-
+def _webhook_key_in(subscriptions: Dict[str, dict], name: str) -> str:
+ """Normalized key for an existing route in a lock-held subscription snapshot."""
key = (name or "").strip().lower()
- subs = wh._load_subscriptions()
- if key not in subs:
+ if key not in subscriptions:
raise HTTPException(status_code=404, detail=f"No subscription named '{key}'")
- return wh, subs, key
+ return key
@router.delete("/api/webhooks/{name}")
@@ -253,9 +258,12 @@ async def delete_webhook(name: str, profile: Optional[str] = None):
profile = destructive_profile(profile, "DELETE /api/webhooks/{name}")
def _run():
- wh, subs, key = _webhook_subs_with(name)
- del subs[key]
- wh._save_subscriptions(subs)
+ import hermes_cli.webhook as wh
+
+ def remove(subscriptions):
+ del subscriptions[_webhook_key_in(subscriptions, name)]
+
+ wh._mutate_subscriptions(remove)
await config_scoped_to_thread(profile, _run)
return {"ok": True}
@@ -266,10 +274,14 @@ async def set_webhook_enabled(name: str, body: WebhookEnabledToggle, profile: Op
"""Disabled routes stay on disk (re-enable later) but the gateway rejects
their events with 403; it hot-reloads the file, so no restart is needed."""
def _run():
- wh, subs, key = _webhook_subs_with(name)
- subs[key]["enabled"] = bool(body.enabled)
- wh._save_subscriptions(subs)
- return key
+ import hermes_cli.webhook as wh
+
+ def toggle(subscriptions):
+ key = _webhook_key_in(subscriptions, name)
+ subscriptions[key]["enabled"] = bool(body.enabled)
+ return key
+
+ return wh._mutate_subscriptions(toggle)
key = await config_scoped_to_thread(profile, _run)
return {"ok": True, "name": key, "enabled": bool(body.enabled)}
diff --git a/hermes_cli/webhook.py b/hermes_cli/webhook.py
index e89b6de1895..11a92ff7b43 100644
--- a/hermes_cli/webhook.py
+++ b/hermes_cli/webhook.py
@@ -5,10 +5,12 @@ import hmac
import json
import re
import secrets
+import threading
import time
import urllib.request
+from contextlib import contextmanager
from pathlib import Path
-from typing import Dict
+from typing import Any, Callable, Dict
from hermes_constants import display_hermes_home
from utils import atomic_json_write
@@ -17,6 +19,13 @@ from hermes_cli.config import cfg_get
_SUBSCRIPTIONS_FILENAME = "webhook_subscriptions.json"
_SUBSCRIPTIONS_FILE_MODE = 0o600
+_SUBSCRIPTIONS_LOCK_FILENAME = ".webhook_subscriptions.lock"
+_SUBSCRIPTIONS_THREAD_LOCK = threading.RLock()
+_MISSING_SUBSCRIPTION = object()
+
+
+class SubscriptionMutationConflict(RuntimeError):
+ """The route changed after a caller took the snapshot it intended to replace."""
def _subscriptions_path() -> Path:
@@ -24,23 +33,84 @@ def _subscriptions_path() -> Path:
return get_hermes_home() / _SUBSCRIPTIONS_FILENAME
-def _load_subscriptions() -> Dict[str, dict]:
+def _subscriptions_lock_path() -> Path:
+ return _subscriptions_path().with_name(_SUBSCRIPTIONS_LOCK_FILENAME)
+
+
+@contextmanager
+def _subscriptions_lock():
+ """Serialize subscription snapshots and mutations across threads and processes."""
+ from hermes_cli.active_sessions import _FileLock
+
+ with _SUBSCRIPTIONS_THREAD_LOCK:
+ with _FileLock(_subscriptions_lock_path()):
+ yield
+
+
+def _load_subscriptions_unlocked() -> tuple[Dict[str, dict], str | None]:
+ """Return one file snapshot and its content revision. Caller holds the store lock."""
path = _subscriptions_path()
- if not path.exists():
- return {}
try:
- data = json.loads(path.read_text(encoding="utf-8-sig"))
- return data if isinstance(data, dict) else {}
+ raw = path.read_bytes()
+ except FileNotFoundError:
+ return {}, None
except Exception:
- return {}
+ return {}, None
+ revision = hashlib.sha256(raw).hexdigest()
+ try:
+ data = json.loads(raw.decode("utf-8-sig"))
+ return (data if isinstance(data, dict) else {}), revision
+ except Exception:
+ return {}, revision
-def _save_subscriptions(subs: Dict[str, dict]) -> None:
+def _load_subscriptions_snapshot() -> tuple[Dict[str, dict], str | None]:
+ """Read a coherent store snapshot; the revision changes with the file content."""
+ with _subscriptions_lock():
+ return _load_subscriptions_unlocked()
+
+
+def _load_subscriptions() -> Dict[str, dict]:
+ return _load_subscriptions_snapshot()[0]
+
+
+def _save_subscriptions_unlocked(subs: Dict[str, dict]) -> None:
# The file holds per-route HMAC secrets: atomic_json_write fchmods the temp file 0o600 BEFORE the
# rename (no umask window) and re-asserts the mode on the destination afterwards.
atomic_json_write(_subscriptions_path(), subs, mode=_SUBSCRIPTIONS_FILE_MODE)
+def _save_subscriptions(subs: Dict[str, dict]) -> None:
+ """Replace the whole store under its writer lock."""
+ with _subscriptions_lock():
+ _save_subscriptions_unlocked(subs)
+
+
+def _mutate_subscriptions(mutate: Callable[[Dict[str, dict]], Any]) -> Any:
+ """Lock, re-read, mutate and atomically publish one complete store snapshot."""
+ with _subscriptions_lock():
+ subscriptions, _ = _load_subscriptions_unlocked()
+ result = mutate(subscriptions)
+ _save_subscriptions_unlocked(subscriptions)
+ return result
+
+
+def _replace_subscription(name: str, route: dict, expected: object) -> None:
+ """CAS one route so a stale update cannot recreate a removed or disabled record."""
+ def replace(subscriptions: Dict[str, dict]) -> None:
+ current = subscriptions.get(name, _MISSING_SUBSCRIPTION)
+ expected_missing = expected is _MISSING_SUBSCRIPTION
+ if (current is _MISSING_SUBSCRIPTION) != expected_missing or (
+ not expected_missing and current != expected
+ ):
+ raise SubscriptionMutationConflict(
+ f"Webhook subscription '{name}' changed concurrently; retry the operation."
+ )
+ subscriptions[name] = route
+
+ _mutate_subscriptions(replace)
+
+
def _get_webhook_config() -> dict:
"""Load webhook platform config. Returns {} if not configured."""
try:
@@ -117,8 +187,9 @@ def _cmd_subscribe(args):
return
subs = _load_subscriptions()
- is_update = name in subs
- existing = subs.get(name, {})
+ expected = subs.get(name, _MISSING_SUBSCRIPTION)
+ is_update = expected is not _MISSING_SUBSCRIPTION
+ existing = expected if isinstance(expected, dict) else {}
profile_arg = getattr(args, "route_profile", None)
if profile_arg is None:
profile = existing.get("profile", "default")
@@ -133,7 +204,19 @@ def _cmd_subscribe(args):
if not profile_exists(profile):
print(f"Error: Profile '{profile}' does not exist.")
return
- secret = args.secret or existing.get("secret") or secrets.token_urlsafe(32)
+ existing_profile = existing.get("profile", "default")
+ profile_changed = is_update and profile != existing_profile
+ if profile_changed and args.secret and args.secret == existing.get("secret"):
+ print(
+ "Error: Rebinding a webhook route requires a new HMAC secret. "
+ "Omit --secret to generate one automatically, or provide a different secret."
+ )
+ return
+ secret = (
+ (args.secret or secrets.token_urlsafe(32))
+ if profile_changed
+ else (args.secret or existing.get("secret") or secrets.token_urlsafe(32))
+ )
events = [e.strip() for e in args.events.split(",")] if args.events else []
route = {
"description": args.description or f"Agent-created subscription: {name}",
@@ -144,6 +227,10 @@ def _cmd_subscribe(args):
"deliver": args.deliver or "log",
"profile": profile,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
+ # A general subscription update is not an enable operation. Preserve an explicit revocation;
+ # only the dashboard's dedicated enabled endpoint may lift it.
+ if existing.get("enabled") is False:
+ route["enabled"] = False
if getattr(args, "deliver_only", False):
if getattr(args, "cron_job", ""):
@@ -180,8 +267,11 @@ def _cmd_subscribe(args):
route["script"] = script
if args.deliver_chat_id:
route["deliver_extra"] = {"chat_id": args.deliver_chat_id}
- subs[name] = route
- _save_subscriptions(subs)
+ try:
+ _replace_subscription(name, route, expected)
+ except SubscriptionMutationConflict as exc:
+ print(f"Error: {exc}")
+ return
print(f"\n {'Updated' if is_update else 'Created'} webhook subscription: {name}")
print(f" URL: {_route_url(name, route)}")
@@ -236,13 +326,18 @@ def _cmd_list(args):
def _cmd_remove(args):
name = args.name.strip().lower()
- subs = _load_subscriptions()
- if name not in subs:
+
+ def remove(subscriptions: Dict[str, dict]) -> None:
+ if name not in subscriptions:
+ raise KeyError(name)
+ del subscriptions[name]
+
+ try:
+ _mutate_subscriptions(remove)
+ except KeyError:
print(f" No subscription named '{name}'.")
print(" Note: Static routes from config.yaml cannot be removed here.")
return
- del subs[name]
- _save_subscriptions(subs)
print(f" Removed webhook subscription: {name}")
diff --git a/tests/hermes_cli/test_webhook_cli.py b/tests/hermes_cli/test_webhook_cli.py
index 7bd44023a38..fc16845b3f1 100644
--- a/tests/hermes_cli/test_webhook_cli.py
+++ b/tests/hermes_cli/test_webhook_cli.py
@@ -4,6 +4,7 @@ import json
import os
import pytest
import stat
+import threading
from argparse import Namespace
from hermes_cli.webhook import (
@@ -91,6 +92,119 @@ class TestSubscribe:
assert _load_subscriptions()["notifier"]["secret"] == "original"
+ def test_stale_update_cannot_restore_concurrently_removed_or_disabled_route(self, monkeypatch):
+ import hermes_cli.webhook as webhook_module
+
+ webhook_command(_make_args(
+ webhook_action="subscribe", name="notifier", secret="original"
+ ))
+ original_load = _load_subscriptions
+ pause = {"loaded": threading.Event(), "allow": threading.Event()}
+ errors = []
+
+ def load_with_paused_update():
+ subscriptions = original_load()
+ if threading.current_thread().name == "stale-webhook-update":
+ pause["loaded"].set()
+ if not pause["allow"].wait(timeout=5):
+ raise AssertionError("timed out waiting to resume stale update")
+ return subscriptions
+
+ monkeypatch.setattr("hermes_cli.webhook._load_subscriptions", load_with_paused_update)
+
+ def update_route():
+ try:
+ webhook_command(_make_args(
+ webhook_action="subscribe", name="notifier", description="stale update"
+ ))
+ except BaseException as exc: # surfaced in the test thread below
+ errors.append(exc)
+
+ def start_stale_update():
+ worker = threading.Thread(target=update_route, name="stale-webhook-update")
+ worker.start()
+ assert pause["loaded"].wait(timeout=5)
+ return worker
+
+ worker = start_stale_update()
+ webhook_command(_make_args(webhook_action="remove", name="notifier"))
+ pause["allow"].set()
+ worker.join(timeout=5)
+
+ assert not worker.is_alive()
+ assert errors == []
+ assert "notifier" not in original_load()
+
+ webhook_command(_make_args(
+ webhook_action="subscribe", name="notifier", secret="replacement"
+ ))
+ pause = {"loaded": threading.Event(), "allow": threading.Event()}
+ worker = start_stale_update()
+
+ def disable(subscriptions):
+ subscriptions["notifier"]["enabled"] = False
+
+ webhook_module._mutate_subscriptions(disable)
+ pause["allow"].set()
+ worker.join(timeout=5)
+
+ assert not worker.is_alive()
+ assert errors == []
+ assert original_load()["notifier"]["enabled"] is False
+
+ def test_profile_rebind_rotates_secret_without_exposing_mixed_record(
+ self, tmp_path, monkeypatch
+ ):
+ from gateway.config import PlatformConfig
+ from gateway.platforms.webhook import WebhookAdapter
+
+ profile_dir = tmp_path / "profiles" / "compta"
+ profile_dir.mkdir(parents=True)
+ (profile_dir / "config.yaml").write_text("{}\n") # identity marker
+ webhook_command(_make_args(
+ webhook_action="subscribe", name="notifier", secret="old-profile-secret"
+ ))
+
+ old_record = _load_subscriptions()["notifier"]
+ old_state = (old_record["profile"], old_record["secret"])
+ adapter = WebhookAdapter(PlatformConfig(enabled=True, extra={"secret": "global"}))
+ adapter._reload_dynamic_routes()
+ initial_stat = _subscriptions_path().stat()
+ observed = [old_state]
+ stop = threading.Event()
+ monkeypatch.setattr("hermes_cli.webhook.secrets.token_urlsafe", lambda _n: "rotated-profile-secret")
+
+ def read_records():
+ while not stop.is_set():
+ record = _load_subscriptions()["notifier"]
+ observed.append((record["profile"], record["secret"]))
+
+ reader = threading.Thread(target=read_records)
+ reader.start()
+ webhook_command(_make_args(
+ webhook_action="subscribe", name="notifier", route_profile="compta"
+ ))
+ stop.set()
+ reader.join(timeout=5)
+
+ new_record = _load_subscriptions()["notifier"]
+ new_state = (new_record["profile"], new_record["secret"])
+ observed.append(new_state)
+ # A coarse or restored mtime must not leave a revoked snapshot live in the gateway.
+ os.utime(
+ _subscriptions_path(),
+ ns=(initial_stat.st_atime_ns, initial_stat.st_mtime_ns),
+ )
+ adapter._reload_dynamic_routes()
+ assert not reader.is_alive()
+ assert new_state == ("compta", "rotated-profile-secret")
+ assert new_record["secret"] != old_record["secret"]
+ assert set(observed) <= {old_state, new_state}
+ assert (
+ adapter._routes["notifier"]["profile"],
+ adapter._routes["notifier"]["secret"],
+ ) == new_state
+
class TestCronJobSubscribe:
"""--cron-job: event-triggered cron jobs."""
diff --git a/website/docs/user-guide/messaging/webhooks.md b/website/docs/user-guide/messaging/webhooks.md
index 85ed2851f8b..64ea65a8aae 100644
--- a/website/docs/user-guide/messaging/webhooks.md
+++ b/website/docs/user-guide/messaging/webhooks.md
@@ -530,9 +530,11 @@ hermes webhook test github-issues --payload '{"issue": {"number": 42, "title": "
### How dynamic subscriptions work
- Subscriptions are stored in `~/.hermes/webhook_subscriptions.json`
-- The webhook adapter hot-reloads this file on each incoming request (mtime-gated, negligible overhead)
+- The webhook adapter hot-reloads a coherent snapshot of this file on each incoming request (content-revision-gated)
- Static routes from `config.yaml` always take precedence over dynamic ones with the same name
- Dynamic subscriptions use the same route format and capabilities as static routes (events, prompt templates, skills, delivery)
+- Create, update, enable/disable, and remove operations are serialized and atomically replace the store; a stale concurrent update is rejected rather than restoring a route another operation removed or disabled
+- Rebinding an existing route with `--route-profile` rotates its HMAC secret automatically. A caller with the old profile's secret cannot authenticate the rebound route; pass a different `--secret` only when the receiving service requires an operator-chosen value
- No gateway restart required — subscribe and it's immediately live
### Agent-driven subscriptions