The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(webhook): keep the secret classifier private to the webhook adapter
kshitijk4poor6e6657e1ab4a
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex aaa6465fbde..d91aa16ef4c 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -35,7 +35,6 @@ except ImportError:web = None # type: ignore[assignment]from gateway.config import Platform, PlatformConfig-from gateway.relay.auth import is_usable_secretfrom gateway.platforms.base import BasePlatformAdapter, SendResultfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.platforms.tcp_site import start_tcp_site@@ -110,6 +109,16 @@ def _hex_hmac(secret: str, data: bytes) -> str:return hmac.new(secret.encode(), data, hashlib.sha256).hexdigest()+def _is_usable_secret(secret: object) -> bool:+ """True when ``secret`` is a string with at least one non-space character.++ A whitespace-only value is what an unset key looks like in config. It is+ falsy to a person and truthy to ``if not secret``, so a bare falsy check+ lets it through. Non-strings are rejected for the same reason.+ """+ return isinstance(secret, str) and bool(secret.strip())++def _timestamp_fresh(raw: str, stale_msg: str, *args) -> bool:"""True when integer timestamp header *raw* is within the replay window; unparseable → False,stale → warn ``stale_msg % args`` and False."""@@ -226,7 +235,7 @@ class WebhookAdapter(BasePlatformAdapter):def _validate_route(self, name: str, route: dict) -> None:"""Startup validation: secret required; INSECURE_NO_AUTH only on loopback (crash early on a public footgun)."""secret = route.get("secret", self._global_secret)- if not is_usable_secret(secret):+ if not _is_usable_secret(secret):raise ValueError(f"[webhook] Route '{name}' has no HMAC secret. Set 'secret' on the route or globally. "f"For testing without auth, set secret to '{_INSECURE_NO_AUTH}'.")if secret == _INSECURE_NO_AUTH and not _is_loopback_host(self._host):@@ -379,7 +388,7 @@ class WebhookAdapter(BasePlatformAdapter):"""An empty effective secret would make _handle_webhook skip HMAC validation → reject suchdynamic routes; INSECURE_NO_AUTH is loopback-only."""effective_secret = route.get("secret", self._global_secret)- if not is_usable_secret(effective_secret):+ if not _is_usable_secret(effective_secret):logger.warning("[webhook] Dynamic route '%s' skipped: 'secret' is missing or empty. Set a valid HMAC ""secret, or use '%s' to explicitly disable auth (testing only).", name, _INSECURE_NO_AUTH)return False@@ -504,7 +513,7 @@ class WebhookAdapter(BasePlatformAdapter):# Missing/empty secrets fail closed here too (not only in connect()), so direct handler reuse# cannot become an unauthenticated dispatch surface.secret = route_config.get("secret", self._global_secret)- if not is_usable_secret(secret):+ if not _is_usable_secret(secret):logger.error("[webhook] Route %s has no HMAC secret; refusing request", route_name)return None, _json_error("Webhook route is missing an HMAC secret", 403)if secret != _INSECURE_NO_AUTH and not self._validate_signature(request, raw_body, secret):diff --git a/gateway/relay/auth.py b/gateway/relay/auth.pyindex cfa6d2cceae..ca23ab1c5d1 100644--- a/gateway/relay/auth.py+++ b/gateway/relay/auth.py@@ -22,16 +22,6 @@ def sign(payload: str, secret: str) -> str:return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()-def is_usable_secret(secret: object) -> bool:- """True when ``secret`` is a string with at least one non-space character.-- A whitespace-only value is what an unset key looks like in config. It is- falsy to a person and truthy to ``if not secret``, so a bare falsy check- lets it through. Non-strings are rejected for the same reason.- """- return isinstance(secret, str) and bool(secret.strip())--def make_token(payload: str, secret: str, ttl_seconds: int = 0) -> str:"""``base64url(f"{payload}:{exp}:{sig}")``; ``exp`` unix seconds (0 = never).diff --git a/tests/gateway/relay/test_auth.py b/tests/gateway/relay/test_auth.pyindex 5ecd9c2a712..04ee7f1386b 100644--- a/tests/gateway/relay/test_auth.py+++ b/tests/gateway/relay/test_auth.py@@ -13,9 +13,7 @@ drift). Regenerate with:from __future__ import annotations-import pytest--from gateway.relay.auth import is_usable_secret, make_token, make_upgrade_token+from gateway.relay.auth import make_token, make_upgrade_token# A fixed 256-bit hex secret used for the frozen connector vector below._SECRET = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"@@ -30,13 +28,3 @@ def test_upgrade_token_is_make_token_of_gateway_id():def test_python_make_token_matches_connector_byte_for_byte():assert make_token("gw-instance-1", _SECRET, 0) == _CONN_TOKEN--- "value,usable",- [(_SECRET, True), ("x", True), (" x ", True),- ("", False), (" ", False), ("\t\n", False),- (None, False), (b"bytes", False), (123, False)],-)-def test_is_usable_secret_classifies_configured_secrets(value, usable):- assert is_usable_secret(value) is usablediff --git a/tests/gateway/test_webhook_adapter.py b/tests/gateway/test_webhook_adapter.pyindex d80574d5215..f1a219b03b1 100644--- a/tests/gateway/test_webhook_adapter.py+++ b/tests/gateway/test_webhook_adapter.py@@ -31,6 +31,7 @@ from gateway.platforms.base import SendResultfrom gateway.platforms.webhook import (WebhookAdapter,_INSECURE_NO_AUTH,+ _is_usable_secret,)@@ -1256,3 +1257,13 @@ class TestBlankRouteSecretFailsClosed:adapter = _make_adapter(routes={"hook": {"secret": blank}})with pytest.raises(ValueError, match="HMAC secret"):asyncio.run(adapter.connect())+++ "value,usable",+ [("s3cret", True), ("x", True), (" x ", True),+ ("", False), (" ", False), ("\t\n", False),+ (None, False), (b"bytes", False), (123, False)],+)+def test_is_usable_secret_classifies_configured_secrets(value, usable):+ assert _is_usable_secret(value) is usable