Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 156 additions & 44 deletions agent/outbound_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,25 @@
Design notes
------------
* Delivery is fire-and-forget through a bounded in-process queue and a
single daemon worker thread. ``invoke_hook()`` runs inside the agent
single daemon worker thread. ``invoke_hook()`` runs inside the agent
loop, so callbacks must never block on network I/O — they serialize,
enqueue, and return ``None`` immediately. Outbound targets can never
enqueue, and return ``None`` immediately. Outbound targets can never
block a tool call, inject context, or otherwise influence agent flow.
* Payloads are signed with HMAC-SHA256 (GitHub-style
``X-Hermes-Signature-256: sha256=<hexdigest>`` over the raw body) when
a secret is configured. Receivers verify exactly like they verify
GitHub webhooks.
* The version-1 body is signed with HMAC-SHA256 when a secret reference
resolves. ``X-Hermes-Signature-256`` remains for compatibility;
``X-Hermes-Signature-V2`` binds the raw ``X-Hermes-Timestamp`` value,
a literal ``.`` byte, and the exact raw body.
* A configured ``secret_ref`` or compatibility ``secret_env`` is
fail-closed. An empty, malformed, unscoped, or unresolved reference
disables that target; Hermes never silently downgrades it to unsigned
delivery. Unsigned delivery is possible only when neither reference
field is present.
* Inline plaintext ``secret`` values are no longer accepted. Move the
value to the environment or active profile secret scope and configure
its name through ``secret_ref`` (preferred) or ``secret_env``.
* No consent prompt: unlike shell hooks, an outbound target executes no
code on this machine — it POSTs JSON to a URL the user themselves put
in config. ``HERMES_SAFE_MODE=1`` still skips registration, matching
in config. ``HERMES_SAFE_MODE=1`` still skips registration, matching
plugins / MCP / shell hooks.
* Registration is idempotent — safe to invoke from both the CLI entry
point and the gateway entry point.
Expand All @@ -35,16 +43,17 @@
outbound:
- url: https://ci.example.com/hermes-events
events: [on_session_end, subagent_stop]
# secret literal (discouraged) or env var name (preferred):
secret_env: HERMES_OUTBOUND_WEBHOOK_SECRET
# optional regex, honored for pre/post_tool_call only:
matcher: "terminal|delegate_task"
# Name of a secret in the active profile scope or environment.
secret_ref: HERMES_OUTBOUND_WEBHOOK_SECRET
# ``secret_env`` is accepted as a compatibility alias.
matcher: "terminal|delegate_task" # pre/post_tool_call only
timeout: 10 # per-attempt seconds, clamped to [1, 60]
name: ci-notify # optional label for logs / `hermes hooks list`

Wire format (POST body)::

{
"schema_version": 1,
"hook_event_name": "on_session_end",
"tool_name": null,
"tool_input": null,
Expand All @@ -58,10 +67,25 @@
Headers::

Content-Type: application/json
User-Agent: Hermes-Agent-Outbound-Webhook
User-Agent: Hermes-Agent-Outbound-Webhook/1
X-Hermes-Event: <hook event name>
X-Hermes-Delivery: <delivery_id>
X-Hermes-Signature-256: sha256=<hmac hexdigest> # only when secret set
X-Hermes-Schema-Version: 1
X-Hermes-Timestamp: <unix seconds>
X-Hermes-Signature-256: sha256=<HMAC(raw body)> # compatibility
X-Hermes-Signature-V2: sha256=<HMAC(timestamp + b"." + raw body)>

Receiver verification contract
------------------------------
``X-Hermes-Signature-V2`` makes replay checks possible; the receiver must
complete them before performing side effects. Parse ``X-Hermes-Timestamp``
as integer Unix seconds and reject requests outside a bounded freshness
window (300 seconds is the recommended default, with clock skew included).
Compute HMAC-SHA256 over the exact timestamp header bytes, ``b"."``, and
the untouched request body, then compare the full ``sha256=...`` value with
``hmac.compare_digest``. Finally, accept each ``X-Hermes-Delivery`` value at
most once for at least the freshness window. A valid HMAC without freshness
and delivery-ID deduplication is authenticated but still replayable.
"""

from __future__ import annotations
Expand All @@ -71,7 +95,6 @@
import hmac
import json
import logging
import os
import queue
import re
import threading
Expand All @@ -84,6 +107,8 @@
from urllib import error as urlerror
from urllib import request as urlrequest

from agent.secret_scope import UnscopedSecretError, get_secret

logger = logging.getLogger(__name__)

DEFAULT_TIMEOUT_SECONDS = 10
Expand All @@ -98,6 +123,17 @@
# kwargs promoted to top-level payload keys (mirrors shell hooks wire).
_TOP_LEVEL_PAYLOAD_KEYS = {"tool_name", "args", "session_id", "parent_session_id"}

_KNOWN_FIELDS = frozenset({
"url",
"events",
"name",
"secret_ref",
"secret_env",
"matcher",
"timeout",
})
_SECRET_REFERENCE_FIELDS = ("secret_ref", "secret_env")

# (event, url) pairs already wired to the plugin manager in this process.
_registered: Set[Tuple[str, str]] = set()
_registered_lock = threading.Lock()
Expand Down Expand Up @@ -156,7 +192,7 @@ def matches_tool(self, tool_name: Optional[str]) -> bool:
def register_from_config(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget]:
"""Register every configured outbound webhook on the plugin manager.

``cfg`` is the full parsed config dict. Missing, empty, or malformed
``cfg`` is the full parsed config dict. Missing, empty, or malformed
``hooks.outbound`` is treated as zero targets — config parsing never
raises, because a broken webhook entry must not crash the agent.

Expand Down Expand Up @@ -220,7 +256,7 @@ def iter_configured_targets(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget

def flush(timeout: float = 5.0) -> bool:
"""Block until all queued deliveries are done (or *timeout* elapses).
Returns ``True`` when the queue fully drained. Test/shutdown helper."""
Returns ``True`` when the queue fully drained. Test/shutdown helper."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
with _delivery_queue.all_tasks_done:
Expand All @@ -232,7 +268,7 @@ def flush(timeout: float = 5.0) -> bool:


def reset_for_tests() -> None:
"""Clear the idempotence set and drain the queue. Test-only helper."""
"""Clear the idempotence set and drain the queue. Test-only helper."""
with _registered_lock:
_registered.clear()
try:
Expand Down Expand Up @@ -275,6 +311,27 @@ def _parse_single_target(index: int, raw: Any) -> Optional[WebhookTarget]:
)
return None

unknown = sorted(set(raw) - _KNOWN_FIELDS)
if unknown:
if "secret" in unknown:
logger.error(
"hooks.outbound[%d].secret contains unsupported inline "
"plaintext. Move the value to the environment or active "
"profile secret scope and set secret_ref (preferred) or "
"secret_env to that name — target disabled",
index,
)
other_unknown = [field for field in unknown if field != "secret"]
if other_unknown:
logger.warning(
"hooks.outbound[%d] has unknown field(s) %s. Known fields: %s "
"— target disabled",
index,
", ".join(other_unknown),
", ".join(sorted(_KNOWN_FIELDS)),
)
return None

url = raw.get("url")
if not isinstance(url, str) or not url.strip():
logger.warning("hooks.outbound[%d] is missing a non-empty 'url'", index)
Expand Down Expand Up @@ -339,7 +396,9 @@ def _parse_single_target(index: int, raw: Any) -> Optional[WebhookTarget]:
timeout = DEFAULT_TIMEOUT_SECONDS
timeout = max(1, min(timeout, MAX_TIMEOUT_SECONDS))

secret = _resolve_secret(index, raw)
secret, usable = _resolve_secret(index, raw)
if not usable:
return None

name = raw.get("name")
if not isinstance(name, str):
Expand All @@ -355,22 +414,62 @@ def _parse_single_target(index: int, raw: Any) -> Optional[WebhookTarget]:
)


def _resolve_secret(index: int, raw: Dict[str, Any]) -> Optional[str]:
"""``secret_env`` (env var name, preferred) wins over inline ``secret``."""
secret_env = raw.get("secret_env")
if isinstance(secret_env, str) and secret_env.strip():
value = os.environ.get(secret_env.strip(), "")
if value:
return value
logger.warning(
"hooks.outbound[%d].secret_env=%r is not set in the environment "
"— deliveries will be UNSIGNED", index, secret_env.strip(),
def _resolve_secret(
index: int, raw: Dict[str, Any],
) -> Tuple[Optional[str], bool]:
"""Resolve one optional secret reference.

Returns ``(secret, usable)``. ``(None, True)`` means no secret field was
configured and unsigned delivery was intentionally requested.
``(None, False)`` means a reference was configured but could not be used,
so the caller must disable the target rather than downgrade it.
"""
configured = [field for field in _SECRET_REFERENCE_FIELDS if field in raw]
if not configured:
return None, True
if len(configured) != 1:
logger.error(
"hooks.outbound[%d] configures both secret_ref and secret_env. "
"Configure exactly one reference field — target disabled",
index,
)
return None
secret = raw.get("secret")
if isinstance(secret, str) and secret:
return secret
return None
return None, False

field_name = configured[0]
reference = raw.get(field_name)
if not isinstance(reference, str) or not reference.strip():
logger.error(
"hooks.outbound[%d].%s must be a non-empty secret name — target "
"disabled; Hermes will not send this webhook unsigned",
index,
field_name,
)
return None, False
reference = reference.strip()

try:
value = get_secret(reference, "")
except UnscopedSecretError as exc:
logger.error(
"hooks.outbound[%d] secret reference %r cannot be resolved "
"without an active profile secret scope (%s) — target disabled; "
"no process-environment fallback was attempted",
index,
reference,
exc,
)
return None, False

if value:
return str(value), True

logger.error(
"hooks.outbound[%d] secret reference %r did not resolve — target "
"disabled; Hermes will not send this webhook unsigned",
index,
reference,
)
return None, False


# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -404,19 +503,21 @@ def _callback(**kwargs: Any) -> None:
def _serialize_payload(
event: str, kwargs: Dict[str, Any], delivery_id: str,
) -> bytes:
"""Render the POST body. Same top-level shape as shell hooks' stdin
(documented in :mod:`agent.shell_hooks`), plus delivery metadata.
"""Render the version-1 POST body.

``delivery_id`` is shared with the ``X-Hermes-Delivery`` header so
receivers can dedupe on either — and since it (plus ``timestamp``)
lives inside the HMAC-signed body, it doubles as replay protection.
The shape mirrors shell hooks' stdin (documented in
:mod:`agent.shell_hooks`) plus delivery metadata. ``delivery_id`` is shared
with ``X-Hermes-Delivery`` so receivers can deduplicate. Replay protection
is complete only when the receiver also validates the V2 timestamp and
rejects a delivery ID it has already accepted.
"""
extras = {k: v for k, v in kwargs.items() if k not in _TOP_LEVEL_PAYLOAD_KEYS}
try:
cwd = str(Path.cwd())
except OSError:
cwd = ""
payload = {
"schema_version": 1,
"hook_event_name": event,
"tool_name": kwargs.get("tool_name"),
"tool_input": kwargs.get("args") if isinstance(kwargs.get("args"), dict) else None,
Expand All @@ -434,17 +535,28 @@ def _serialize_payload(
def _build_delivery(
event: str, target: WebhookTarget, body: bytes, delivery_id: str,
) -> Dict[str, Any]:
timestamp = str(int(time.time()))
headers = {
"Content-Type": "application/json",
"User-Agent": "Hermes-Agent-Outbound-Webhook",
"User-Agent": "Hermes-Agent-Outbound-Webhook/1",
"X-Hermes-Event": event,
"X-Hermes-Delivery": delivery_id,
"X-Hermes-Schema-Version": "1",
"X-Hermes-Timestamp": timestamp,
}
if target.secret:
digest = hmac.new(
# Compatibility header for existing receivers.
legacy = hmac.new(
target.secret.encode("utf-8"), body, hashlib.sha256
).hexdigest()
headers["X-Hermes-Signature-256"] = f"sha256={digest}"
headers["X-Hermes-Signature-256"] = f"sha256={legacy}"

# V2 binds time + body so receivers can enforce bounded freshness.
signed = timestamp.encode("ascii") + b"." + body
digest = hmac.new(
target.secret.encode("utf-8"), signed, hashlib.sha256
).hexdigest()
headers["X-Hermes-Signature-V2"] = f"sha256={digest}"
return {
"url": target.url,
"label": target.label,
Expand Down Expand Up @@ -480,7 +592,7 @@ def _ensure_worker() -> None:
# The worker is a daemon thread, so a short-lived process (a `-q`
# CLI run, a cron session) can exit right after enqueuing the
# final events — silently dropping on_session_end, the headline
# use case. Drain the queue at interpreter shutdown, bounded so
# use case. Drain the queue at interpreter shutdown, bounded so
# a dead endpoint can only delay exit, never hang it.
atexit.register(flush, timeout=5.0)

Expand All @@ -506,7 +618,7 @@ class _NoRedirectHandler(urlrequest.HTTPRedirectHandler):

urllib's default handler converts a redirected POST into a body-less
GET — the signed payload would be silently dropped and the headers
re-sent to a location the user never configured. Treat any 3xx as a
re-sent to a location the user never configured. Treat any 3xx as a
delivery failure instead (surfaced as HTTPError by returning None).
"""

Expand All @@ -518,7 +630,7 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102


def _deliver(delivery: Dict[str, Any]) -> None:
"""POST with bounded retries. Retries on connection errors and 5xx;
"""POST with bounded retries. Retries on connection errors and 5xx;
4xx is the receiver telling us the request itself is wrong — no retry.
3xx redirects are never followed (misconfiguration — fix the URL)."""
last_error = ""
Expand Down
Loading
Loading