Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

refactor(backend/integrations): consolidate webhook signature verification + fix Exa/Airtable bugs (#13135)

Krzysztof Czerwinski7f08a16deed5
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.py
index b959b0a8bf..1fc61cade7 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py
@@ -568,6 +568,23 @@ async def webhook_ingress_generic(
logger.warning(f"Webhook payload received for unknown webhook #{webhook_id}")
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
logger.debug(f"Webhook #{webhook_id}: {webhook}")
+
+ # Run provider signature verification (no-op for providers whose protocol
+ # has no signing scheme). 403 on failure; not 404 — that would leak
+ # webhook existence.
+ try:
+ await webhook_manager.verify_signature(webhook, request)
+ except HTTPException:
+ raise
+ except Exception:
+ logger.exception(
+ f"Signature verification failed for webhook #{webhook_id} ({provider.value})"
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Invalid webhook signature",
+ )
+
payload, event_type = await webhook_manager.validate_payload(
webhook, request, credentials
)
diff --git a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py
new file mode 100644
index 0000000000..e9851e7106
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py
@@ -0,0 +1,480 @@
+"""
+Tests for the webhook ingress endpoint's signature verification path.
+
+The endpoint is intentionally unauthenticated and delegates per-provider
+signature checks to each manager's `verify_signature`. This file pins:
+
+* Providers that DO sign (GitHub, Telegram, Exa, Airtable) reject
+ missing/invalid sigs and accept valid ones, including correct use of the
+ platform-issued signing secret (Exa's `config["exa_secret"]`, Airtable's
+ base64-decoded `config["mac_secret"]`).
+* Generic webhook honors an optional `secret_token` on the triggered block:
+ passes through when unset, enforces when set.
+* Providers without a signing scheme (Compass, Slant3D) pass through.
+* `verify_signature` runs before `validate_payload` (call ordering).
+"""
+
+import base64
+import hashlib
+import hmac
+from contextlib import ExitStack
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import fastapi
+import fastapi.testclient
+
+from backend.api.features.integrations.router import router
+from backend.data.integrations import WebhookWithRelations
+from backend.integrations.providers import ProviderName
+
+app = fastapi.FastAPI()
+app.include_router(router)
+# Surface downstream provider errors (e.g. ValueError from a payload-schema
+# check) as 500 responses rather than propagating, so we can assert on
+# response codes here. The contract under test is signature verification.
+client = fastapi.testclient.TestClient(app, raise_server_exceptions=False)
+
+
+WEBHOOK_ID = "wh-12345"
+WEBHOOK_SECRET = "s" * 64
+USER_ID = "user-1"
+
+
+def _make_webhook(
+ provider: ProviderName,
+ *,
+ secret: str = WEBHOOK_SECRET,
+ config: dict | None = None,
+ triggered_nodes=None,
+ triggered_presets=None,
+) -> WebhookWithRelations:
+ # `model_construct` skips field validation so we can pass duck-typed
+ # stubs for `triggered_nodes`/`triggered_presets` instead of full
+ # NodeModel / LibraryAgentPreset instances. The generic webhook manager
+ # only reads `.input_default` / `.inputs` from those, so simple
+ # MagicMocks suffice.
+ return WebhookWithRelations.model_construct(
+ id=WEBHOOK_ID,
+ user_id=USER_ID,
+ provider=provider,
+ credentials_id="",
+ webhook_type="test",
+ resource="",
+ events=[],
+ config=config or {},
+ secret=secret,
+ provider_webhook_id="",
+ triggered_nodes=triggered_nodes or [],
+ triggered_presets=triggered_presets or [],
+ )
+
+
+def _patch_ingress(webhook):
+ # Important: every downstream DB-touching call on the success path must be
+ # mocked. Real Prisma calls inside FastAPI TestClient's blocking portal
+ # would open connections on the portal's event loop, corrupting Prisma's
+ # global client state for any session-scoped async fixture that runs
+ # later in the suite (e.g. `oauth_test.py::test_user`).
+ return [
+ patch(
+ "backend.api.features.integrations.router.get_webhook",
+ AsyncMock(return_value=webhook),
+ ),
+ patch("backend.api.features.integrations.router.creds_manager"),
+ patch(
+ "backend.api.features.integrations.router.publish_webhook_event",
+ AsyncMock(),
+ ),
+ patch(
+ "backend.api.features.integrations.router.complete_onboarding_step",
+ AsyncMock(),
+ ),
+ patch(
+ "backend.api.features.integrations.router._execute_webhook_node_trigger",
+ AsyncMock(),
+ ),
+ patch(
+ "backend.api.features.integrations.router._execute_webhook_preset_trigger",
+ AsyncMock(),
+ ),
+ ]
+
+
+def _post(provider: str, headers: dict | None = None, body: bytes = b"{}"):
+ return client.post(
+ f"/{provider}/webhooks/{WEBHOOK_ID}/ingress",
+ content=body,
+ headers={"Content-Type": "application/json", **(headers or {})},
+ )
+
+
+def _manager(provider: ProviderName):
+ if provider == ProviderName.COMPASS:
+ from backend.integrations.webhooks.compass import CompassWebhookManager
+
+ return CompassWebhookManager()
+ if provider == ProviderName.SLANT3D:
+ from backend.integrations.webhooks.slant3d import Slant3DWebhooksManager
+
+ return Slant3DWebhooksManager()
+ if provider == ProviderName.GITHUB:
+ from backend.integrations.webhooks.github import GithubWebhooksManager
+
+ return GithubWebhooksManager()
+ if provider == ProviderName.TELEGRAM:
+ from backend.integrations.webhooks.telegram import TelegramWebhooksManager
+
+ return TelegramWebhooksManager()
+ if provider == ProviderName("exa"):
+ from backend.blocks.exa._webhook import ExaWebhookManager
+
+ return ExaWebhookManager()
+ if provider == ProviderName("airtable"):
+ from backend.blocks.airtable._webhook import AirtableWebhookManager
+
+ return AirtableWebhookManager()
+ if provider == ProviderName("generic_webhook"):
+ from backend.blocks.generic_webhook._webhook import GenericWebhooksManager
+
+ return GenericWebhooksManager()
+ raise ValueError(f"No manager mapping for {provider}")
+
+
+def _run(webhook, provider_path: str, **kwargs):
+ """Boilerplate: patch the router's deps, set the right manager, fire request."""
+ patches = _patch_ingress(webhook) + [
+ patch(
+ "backend.api.features.integrations.router.get_webhook_manager",
+ return_value=_manager(webhook.provider),
+ )
+ ]
+ # ExitStack guarantees previously started patchers are stopped even if
+ # a later one's __enter__ raises.
+ with ExitStack() as stack:
+ for p in patches:
+ stack.enter_context(p)
+ return _post(provider_path, **kwargs)
+
+
+# ---------------------------------------------------------------------------
+# Unsigned providers: default no-op verify, ingress passes through.
+# ---------------------------------------------------------------------------
+
+
+class TestUnsignedProvidersPassThrough:
+ """Compass and Slant3D have no upstream signing scheme. The router must
+ not 403 their deliveries — the default no-op `verify_signature` covers
+ them, and 403'ing here would break every legitimate delivery from those
+ devices/services."""
+
+ def test_compass_accepts_unsigned_request(self):
+ webhook = _make_webhook(ProviderName.COMPASS)
+ resp = _run(webhook, "compass")
+ assert resp.status_code != 403, resp.text
+
+ def test_slant3d_accepts_unsigned_request(self):
+ webhook = _make_webhook(ProviderName.SLANT3D)
+ # Use a Slant3D-shaped payload so the provider's own payload check
+ # doesn't 500; the assertion is about signature, not schema.
+ body = (
+ b'{"orderId":"o","status":"shipped","trackingNumber":"t","carrierCode":"c"}'
+ )
+ resp = _run(webhook, "slant3d", body=body)
+ assert resp.status_code != 403, resp.text
+
+
+# ---------------------------------------------------------------------------
+# Always-signed providers (GitHub, Telegram): existing contract is intact.
+# ---------------------------------------------------------------------------
+
+
+class TestAlwaysSignedProviders:
+ def test_github_missing_signature_403(self):
+ webhook = _make_webhook(ProviderName.GITHUB)
+ resp = _run(webhook, "github", headers={"X-GitHub-Event": "push"})
+ assert resp.status_code == 403, resp.text
+
+ def test_github_wrong_signature_403(self):
+ webhook = _make_webhook(ProviderName.GITHUB)
+ body = b'{"x":1}'
+ # HMAC over the same body but using a different secret — well-formed
+ # `sha256=...` header, wrong digest.
+ wrong_sig = (
+ "sha256=" + hmac.new(b"other-secret", body, hashlib.sha256).hexdigest()
+ )
+ resp = _run(
+ webhook,
+ "github",
+ body=body,
+ headers={"X-Hub-Signature-256": wrong_sig, "X-GitHub-Event": "push"},
+ )
+ assert resp.status_code == 403, resp.text
+
+ def test_github_correct_signature_accepted(self):
+ webhook = _make_webhook(ProviderName.GITHUB)
+ body = b'{"x":1}'
+ sig = (
+ "sha256="
+ + hmac.new(WEBHOOK_SECRET.encode(), body, hashlib.sha256).hexdigest()
+ )
+ resp = _run(
+ webhook,
+ "github",
+ body=body,
+ headers={"X-Hub-Signature-256": sig, "X-GitHub-Event": "push"},
+ )
+ assert resp.status_code != 403, resp.text
+
+ def test_telegram_missing_signature_403(self):
+ webhook = _make_webhook(ProviderName.TELEGRAM)
+ resp = _run(webhook, "telegram")
+ assert resp.status_code == 403, resp.text
+
+ def test_telegram_wrong_token_403(self):
+ webhook = _make_webhook(ProviderName.TELEGRAM)
+ resp = _run(
+ webhook,
+ "telegram",
+ headers={"X-Telegram-Bot-Api-Secret-Token": "wrong-token"},
+ )
+ assert resp.status_code == 403, resp.text
+
+ def test_telegram_correct_signature_accepted(self):
+ webhook = _make_webhook(ProviderName.TELEGRAM)
+ resp = _run(
+ webhook,
+ "telegram",
+ headers={"X-Telegram-Bot-Api-Secret-Token": WEBHOOK_SECRET},
+ )
+ assert resp.status_code != 403, resp.text
+
+
+# ---------------------------------------------------------------------------
+# Exa signature verification.
+# ---------------------------------------------------------------------------
+
+
+class TestExaSignature:
+ """Exa enforces a correct `Exa-Signature` header of the form
+ `t=<ts>,v1=<hex>`, where the signed payload is `<ts>.<raw body>` and the
+ HMAC key is `config["exa_secret"]`.
+ See https://docs.exa.ai/websets/api/webhooks/verifying-signatures"""
+
+ EXA_SECRET = "exa-signing-secret-deadbeef"
+ TS = "1234567890"
+
+ def _webhook(self):
+ return _make_webhook(
+ ProviderName("exa"), config={"exa_secret": self.EXA_SECRET}
+ )
+
+ def _header(self, body: bytes, ts: str | None = None) -> str:
+ ts = ts or self.TS
+ sig = hmac.new(
+ self.EXA_SECRET.encode(), f"{ts}.".encode() + body, hashlib.sha256
+ ).hexdigest()
+ return f"t={ts},v1={sig}"
+
+ def test_missing_signature_403(self):
+ resp = _run(self._webhook(), "exa")
+ assert resp.status_code == 403, resp.text
+
+ def test_malformed_signature_403(self):
+ resp = _run(self._webhook(), "exa", headers={"Exa-Signature": "nope"})
+ assert resp.status_code == 403, resp.text
+
+ def test_wrong_signature_403(self):
+ resp = _run(
+ self._webhook(),
+ "exa",
+ headers={"Exa-Signature": f"t={self.TS},v1=deadbeef"},
+ )
+ assert resp.status_code == 403, resp.text
+
+ def test_signature_over_body_only_rejected(self):
+ """A signature computed over the raw body WITHOUT the `<ts>.` prefix
+ (the previous broken implementation) must NOT verify."""
+ body = b'{"eventType":"webset.created"}'
+ body_only_sig = hmac.new(
+ self.EXA_SECRET.encode(), body, hashlib.sha256
+ ).hexdigest()
+ resp = _run(
+ self._webhook(),
+ "exa",
+ body=body,
+ headers={"Exa-Signature": f"t={self.TS},v1={body_only_sig}"},
+ )
+ assert resp.status_code == 403, resp.text
+
+ def test_correct_signature_accepted(self):
+ body = b'{"eventType":"webset.created"}'
+ resp = _run(
+ self._webhook(),
+ "exa",
+ body=body,
+ headers={"Exa-Signature": self._header(body)},
+ )
+ assert resp.status_code != 403, resp.text
+
+ def test_missing_config_secret_403(self):
+ """If a stored Exa webhook somehow lacks `config["exa_secret"]`
+ (e.g. legacy DB row), we must fail-closed rather than silently
+ accept."""
+ wh = _make_webhook(ProviderName("exa"), config={})
+ resp = _run(wh, "exa", headers={"Exa-Signature": f"t={self.TS},v1=anything"})
+ assert resp.status_code == 403, resp.text
+
+
+# ---------------------------------------------------------------------------
+# Airtable signature verification.
+# ---------------------------------------------------------------------------
+
+
+class TestAirtableSignature:
+ """Airtable's signing key is stored base64-encoded as Airtable returns it
+ — must be decoded before use as the HMAC key. Header format is
+ `hmac-sha256=<hex>`."""
+
+ AIRTABLE_RAW_KEY = b"airtable-binary-signing-key-32-byte-x"
+ AIRTABLE_B64_KEY = base64.b64encode(AIRTABLE_RAW_KEY).decode()
+
+ def _webhook(self, config_override: dict | None = None):
+ cfg = (
+ {"mac_secret": self.AIRTABLE_B64_KEY}
+ if config_override is None
+ else config_override
+ )
+ return _make_webhook(ProviderName("airtable"), config=cfg)
+
+ def _expected_header(self, body: bytes) -> str:
+ return (
+ "hmac-sha256="
+ + hmac.new(self.AIRTABLE_RAW_KEY, body, hashlib.sha256).hexdigest()
+ )
+
+ def test_missing_signature_403(self):
+ resp = _run(self._webhook(), "airtable")
+ assert resp.status_code == 403, resp.text
+
+ def test_correct_signature_accepted(self):
+ body = b'{"base":{"id":"app"},"webhook":{"id":"w"},"timestamp":"t"}'
+ resp = _run(
+ self._webhook(),
+ "airtable",
+ body=body,
+ headers={"X-Airtable-Content-MAC": self._expected_header(body)},
+ )
+ assert resp.status_code != 403, resp.text
+
+ def test_missing_config_mac_secret_403(self):
+ """Symmetric with the Exa case: a stored Airtable webhook lacking
+ `config["mac_secret"]` (legacy/corrupted row) must fail-closed, not
+ silently accept the request."""
+ wh = self._webhook(config_override={})
+ resp = _run(
+ wh,
+ "airtable",
+ headers={"X-Airtable-Content-MAC": "hmac-sha256=anything"},
+ )
+ assert resp.status_code == 403, resp.text
+
+ def test_base64_string_used_as_key_would_fail(self):
+ """Regression: the previous implementation used the base64 STRING as
+ the HMAC key. A signature built that way must NOT verify under the
+ new (correct) implementation that base64-decodes first."""
+ body = b'{"base":{"id":"app"},"webhook":{"id":"w"},"timestamp":"t"}'
+ wrong_sig = (
+ "hmac-sha256="
+ + hmac.new(self.AIRTABLE_B64_KEY.encode(), body, hashlib.sha256).hexdigest()
+ )
+ resp = _run(
+ self._webhook(),
+ "airtable",
+ body=body,
+ headers={"X-Airtable-Content-MAC": wrong_sig},
+ )
+ assert resp.status_code == 403, resp.text
+
+
+# ---------------------------------------------------------------------------
+# Generic webhook: optional secret_token on the triggered block.
+# ---------------------------------------------------------------------------
+
+
+class TestGenericWebhookOptionalToken:
+ """Generic webhook is unauthenticated by default. When the user sets a
+ `secret_token` on the trigger block, the manager requires inbound
+ requests to echo it in `X-Webhook-Secret`."""
+
+ def _webhook(self, secret_token: str | None = None):
+ nodes = []
+ if secret_token is not None:
+ n = MagicMock()
+ n.input_default = {"secret_token": secret_token}
+ nodes.append(n)
+ return _make_webhook(ProviderName("generic_webhook"), triggered_nodes=nodes)
+
+ def test_no_token_configured_accepts_unsigned(self):
+ resp = _run(self._webhook(secret_token=None), "generic_webhook")
+ assert resp.status_code != 403, resp.text
+
+ def test_empty_token_configured_accepts_unsigned(self):
+ """An empty string for `secret_token` is treated as 'not set' — back
+ compat for users who left the field blank."""
+ resp = _run(self._webhook(secret_token=""), "generic_webhook")
+ assert resp.status_code != 403, resp.text
+
+ def test_token_configured_missing_header_403(self):
+ resp = _run(self._webhook(secret_token="t0ken"), "generic_webhook")
+ assert resp.status_code == 403, resp.text
+
+ def test_token_configured_wrong_header_403(self):
+ resp = _run(
+ self._webhook(secret_token="t0ken"),
+ "generic_webhook",
+ headers={"X-Webhook-Secret": "nope"},
+ )
+ assert resp.status_code == 403, resp.text
+
+ def test_token_configured_correct_header_accepted(self):
+ resp = _run(
+ self._webhook(secret_token="t0ken"),
+ "generic_webhook",
+ headers={"X-Webhook-Secret": "t0ken"},
+ )
+ assert resp.status_code != 403, resp.text
+
+
+# ---------------------------------------------------------------------------
+# Ordering: verify_signature runs BEFORE validate_payload.
+# ---------------------------------------------------------------------------
+
+
+class TestVerificationOrder:
+ """A future refactor must not invert these two calls — otherwise a
+ payload parser (e.g. Airtable's `list_webhook_payloads` API call) could
+ fire before the request is authenticated."""
+
+ def test_validate_payload_not_called_on_bad_signature(self):
+ webhook = _make_webhook(ProviderName.GITHUB)
+
+ mock_manager = MagicMock()
+ mock_manager.verify_signature = AsyncMock(
+ side_effect=fastapi.HTTPException(status_code=403, detail="nope")
+ )
+ mock_manager.validate_payload = AsyncMock(return_value=({}, "evt"))
+
+ patches = _patch_ingress(webhook) + [
+ patch(
+ "backend.api.features.integrations.router.get_webhook_manager",
+ return_value=mock_manager,
+ )
+ ]
+ with ExitStack() as stack:
+ for p in patches:
+ stack.enter_context(p)
+ resp = _post("github")
+
+ assert resp.status_code == 403
+ mock_manager.verify_signature.assert_awaited_once()
+ mock_manager.validate_payload.assert_not_called()
diff --git a/autogpt_platform/backend/backend/blocks/airtable/_webhook.py b/autogpt_platform/backend/backend/blocks/airtable/_webhook.py
index 7eed7bb263..b30e7748d8 100644
--- a/autogpt_platform/backend/backend/blocks/airtable/_webhook.py
+++ b/autogpt_platform/backend/backend/blocks/airtable/_webhook.py
@@ -2,12 +2,14 @@
Webhook management for Airtable blocks.
"""
+import base64
import hashlib
import hmac
import logging
from enum import Enum
from typing import cast
+from fastapi import HTTPException, Request
from prisma.types import Serializable
from backend.sdk import (
@@ -41,35 +43,49 @@ class AirtableWebhookManager(BaseWebhooksManager):
PROVIDER_NAME = ProviderName("airtable")
+ @classmethod
+ async def verify_signature(cls, webhook: Webhook, request: Request) -> None:
+ # Airtable returns the signing secret base64-encoded as `macSecretBase64`
+ # (stored in `config["mac_secret"]`); it must be base64-decoded before
+ # use as the HMAC key.
+ mac_secret_b64 = webhook.config.get("mac_secret")
+ if not mac_secret_b64:
+ raise HTTPException(
+ status_code=403,
+ detail="Webhook is missing Airtable MAC secret; re-register the webhook",
+ )
+
+ signature = request.headers.get("X-Airtable-Content-MAC")
+ if not signature:
+ raise HTTPException(
+ status_code=403, detail="Missing X-Airtable-Content-MAC header"
+ )
+
+ try:
+ mac_secret = base64.b64decode(mac_secret_b64)
+ except Exception:
+ raise HTTPException(
+ status_code=403, detail="Stored Airtable MAC secret is not valid base64"
+ )
+
+ body = await request.body()
+ hmac_obj = hmac.new(mac_secret, body, hashlib.sha256)
+ expected_mac = f"hmac-sha256={hmac_obj.hexdigest()}"
+
+ if not hmac.compare_digest(signature, expected_mac):
+ raise HTTPException(status_code=403, detail="Invalid webhook signature")
+
@classmethod
async def validate_payload(
cls, webhook: Webhook, request, credentials: Credentials | None
) -> tuple[dict, str]:
- """Validate incoming webhook payload and signature."""
+ """Validate incoming webhook payload structure."""
if not credentials:
raise ValueError("Missing credentials in webhook metadata")
payload = await request.json()
- # Verify webhook signature using HMAC-SHA256
- if webhook.secret:
- mac_secret = webhook.config.get("mac_secret")
- if mac_secret:
- # Get the raw body for signature verification
- body = await request.body()
-
- # Calculate expected signature
- mac_secret_decoded = mac_secret.encode()
- hmac_obj = hmac.new(mac_secret_decoded, body, hashlib.sha256)
- expected_mac = f"hmac-sha256={hmac_obj.hexdigest()}"
-
- # Get signature from headers
- signature = request.headers.get("X-Airtable-Content-MAC")
-
- if signature and not hmac.compare_digest(signature, expected_mac):
- raise ValueError("Invalid webhook signature")
-
# Validate payload structure
required_fields = ["base", "webhook", "timestamp"]
if not all(field in payload for field in required_fields):
@@ -85,11 +101,14 @@ class AirtableWebhookManager(BaseWebhooksManager):
response = await list_webhook_payloads(credentials, base_id, webhook_id, cursor)
- # update webhook config
+ # Merge cursor update into existing config — `update_webhook` does a
+ # full replace on the config blob, and dropping `mac_secret`/other
+ # fields here would break subsequent signature verification.
await update_webhook(
webhook.id,
config=cast(
- dict[str, Serializable], {"base_id": base_id, "cursor": response.cursor}
+ dict[str, Serializable],
+ {**webhook.config, "base_id": base_id, "cursor": response.cursor},
),
)
diff --git a/autogpt_platform/backend/backend/blocks/exa/_webhook.py b/autogpt_platform/backend/backend/blocks/exa/_webhook.py
index 2b248d2f12..8a5d566789 100644
--- a/autogpt_platform/backend/backend/blocks/exa/_webhook.py
+++ b/autogpt_platform/backend/backend/blocks/exa/_webhook.py
@@ -6,6 +6,8 @@ import hashlib
import hmac
from enum import Enum
+from fastapi import HTTPException, Request
+
from backend.data.model import Credentials
from backend.sdk import (
APIKeyCredentials,
@@ -50,30 +52,57 @@ class ExaWebhookManager(BaseWebhooksManager):
class WebhookType(str, Enum):
WEBSET = "webset"
+ @classmethod
+ async def verify_signature(cls, webhook: Webhook, request: Request) -> None:
+ # Exa signs deliveries with the secret it returns at registration time,
+ # stored in `config["exa_secret"]` (not `webhook.secret`). The
+ # `Exa-Signature` header carries a timestamp and one or more signatures:
+ # `t=<unix_ts>,v1=<hex>[,v1=<hex>...]`. The signed payload is
+ # `<timestamp>.<raw body>`, HMAC-SHA256 keyed with the secret.
+ # See https://docs.exa.ai/websets/api/webhooks/verifying-signatures
+ signing_secret = webhook.config.get("exa_secret")
+ if not signing_secret:
+ raise HTTPException(
+ status_code=403,
+ detail="Webhook is missing Exa signing secret; re-register the webhook",
+ )
+
+ signature_header = request.headers.get("Exa-Signature")
+ if not signature_header:
+ raise HTTPException(status_code=403, detail="Missing Exa-Signature header")
+
+ timestamp: str | None = None
+ provided_signatures: list[str] = []
+ for part in signature_header.split(","):
+ key, _, value = part.strip().partition("=")
+ if key == "t":
+ timestamp = value
+ elif key == "v1":
+ provided_signatures.append(value)
+
+ if not timestamp or not provided_signatures:
+ raise HTTPException(
+ status_code=403, detail="Malformed Exa-Signature header"
+ )
+
+ body = await request.body()
+ signed_payload = f"{timestamp}.".encode() + body
+ expected_signature = hmac.new(
+ signing_secret.encode(), signed_payload, hashlib.sha256
+ ).hexdigest()
+
+ if not any(
+ hmac.compare_digest(expected_signature, sig) for sig in provided_signatures
+ ):
+ raise HTTPException(status_code=403, detail="Invalid webhook signature")
+
@classmethod
async def validate_payload(
cls, webhook: Webhook, request, credentials: Credentials | None
) -> tuple[dict, str]:
- """Validate incoming webhook payload and signature."""
+ """Validate incoming webhook payload."""
payload = await request.json()
-
- # Get event type from payload
event_type = payload.get("eventType", "unknown")
-
- # Verify webhook signature if secret is available
- if webhook.secret:
- signature = request.headers.get("X-Exa-Signature")
- if signature:
- # Compute expected signature
- body = await request.body()
- expected_signature = hmac.new(
- webhook.secret.encode(), body, hashlib.sha256
- ).hexdigest()
-
- # Compare signatures
- if not hmac.compare_digest(signature, expected_signature):
- raise ValueError("Invalid webhook signature")
-
return payload, event_type
async def _register_webhook(
diff --git a/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.py b/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.py
index 9dd4b8c2c7..243bf4b7c1 100644
--- a/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.py
+++ b/autogpt_platform/backend/backend/blocks/generic_webhook/_webhook.py
@@ -1,8 +1,11 @@
+import hmac
import logging
-from fastapi import Request
+from fastapi import HTTPException, Request
+from pydantic import SecretStr
from strenum import StrEnum
+from backend.data.integrations import WebhookWithRelations
from backend.sdk import Credentials, ManualWebhookManagerBase, Webhook
logger = logging.getLogger(__name__)
@@ -15,6 +18,71 @@ class GenericWebhookType(StrEnum):
class GenericWebhooksManager(ManualWebhookManagerBase):
WebhookType = GenericWebhookType
+ # Name of the input field on `GenericWebhookTriggerBlock` that carries the
+ # optional user-chosen secret. Read here at verification time rather than
+ # snapshotted at webhook registration so a later change to the secret on
+ # the block takes effect immediately.
+ SECRET_TOKEN_INPUT = "secret_token"
+ SECRET_HEADER = "X-Webhook-Secret"
+
+ @classmethod
+ async def verify_signature(
+ cls, webhook: WebhookWithRelations, request: Request
+ ) -> None:
+ # Find any non-empty `secret_token` configured on a triggered node or
+ # preset attached to this webhook. The webhook is loaded via
+ # `get_webhook(..., include_relations=True)` in the router so these
+ # relations are already populated.
+ expected = cls._configured_secret(webhook)
+ if not expected:
+ # No secret configured — back-compat with unauthenticated generic
+ # webhooks. Webhook URL is the only credential.
+ return
+
+ provided = request.headers.get(cls.SECRET_HEADER)
+ # constant-time compare to prevent timing side-channel
+ if not provided or not hmac.compare_digest(provided, expected):
+ raise HTTPException(
+ status_code=403,
+ detail=f"Invalid or missing {cls.SECRET_HEADER} header",
+ )
+
+ @classmethod
+ def _configured_secret(cls, webhook: WebhookWithRelations) -> str | None:
+ sources = [node.input_default for node in webhook.triggered_nodes] + [
+ preset.inputs for preset in webhook.triggered_presets
+ ]
+
+ found: list[str] = []
+ for src in sources:
+ value = src.get(cls.SECRET_TOKEN_INPUT)
+ # Stored values may arrive as plain strings or as SecretStr
+ # depending on serialization path; normalize.
+ if isinstance(value, SecretStr):
+ value = value.get_secret_value()
+ if isinstance(value, str) and value.strip():
+ found.append(value)
+
+ if not found:
+ return None
+ # Compute the distinct-count before logging so the secret values
+ # themselves don't flow into the logger call args (CodeQL's
+ # clear-text-logging taint analysis flags any expression that
+ # derives from a secret-typed variable, even just its length).
+ distinct_count = len(set(found))
+ if distinct_count > 1:
+ # Multiple attached targets configured different tokens. We only
+ # have one HMAC comparison to make, so log loudly — the first
+ # token wins but the user almost certainly didn't intend this.
+ logger.warning(
+ "Webhook %s has %d distinct secret_token values across "
+ "attached targets; using the first one. All targets attached "
+ "to the same webhook must share the same secret.",
+ webhook.id,
+ distinct_count,
+ )
+ return found[0]
+
@classmethod
async def validate_payload(
cls, webhook: Webhook, request: Request, credentials: Credentials | None = None
diff --git a/autogpt_platform/backend/backend/blocks/generic_webhook/triggers.py b/autogpt_platform/backend/backend/blocks/generic_webhook/triggers.py
index 56a4c3d99d..0ae07f1b12 100644
--- a/autogpt_platform/backend/backend/blocks/generic_webhook/triggers.py
+++ b/autogpt_platform/backend/backend/blocks/generic_webhook/triggers.py
@@ -27,6 +27,18 @@ class GenericWebhookTriggerBlock(Block):
description="The constants to be set when the block is put on the graph",
default_factory=dict,
)
+ secret_token: str | None = SchemaField(
+ title="Secret token",
+ description=(
+ "Optional. If set, the platform will only accept incoming "
+ "webhook requests that include this exact value in the "
+ "'X-Webhook-Secret' header. Leave empty for unauthenticated "
+ "webhooks (the URL itself is the only credential)."
+ ),
+ default=None,
+ secret=True,
+ advanced=False,
+ )
class Output(BlockSchemaOutput):
payload: dict = SchemaField(
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/_base.py b/autogpt_platform/backend/backend/integrations/webhooks/_base.py
index 95981b41d5..b4fc25d521 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/_base.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/_base.py
@@ -116,6 +116,34 @@ class BaseWebhooksManager(ABC, Generic[WT]):
logger.info(f"Webhook #{webhook_id} deleted as it had no remaining triggers")
return True
+ # --8<-- [start:BaseWebhooksManager6]
+ @classmethod
+ async def verify_signature(
+ cls,
+ webhook: integrations.WebhookWithRelations,
+ request: Request,
+ ) -> None:
+ """
+ Verify the authenticity of an incoming webhook request.
+
+ Default is a no-op: not every provider's webhook protocol supports
+ signing, so unsigned providers (e.g. Compass, Slant3D) don't override
+ this. Providers whose protocol does sign deliveries (GitHub, Telegram,
+ Exa, Airtable) override and raise `fastapi.HTTPException(403)` on
+ missing or invalid signatures, using `hmac.compare_digest` for any
+ secret comparison. Overrides that only need the stored `secret` /
+ `config` may widen the parameter to `integrations.Webhook`.
+
+ Params:
+ webhook: Configured webhook including stored `secret` / config,
+ with `triggered_nodes` / `triggered_presets` relations loaded.
+ request: Incoming FastAPI `Request`. Read with `await request.body()`
+ for HMAC computation; Starlette caches the body so a second
+ read inside `validate_payload` is safe.
+ """
+
+ # --8<-- [end:BaseWebhooksManager6]
+
# --8<-- [start:BaseWebhooksManager3]
@classmethod
@abstractmethod
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/github.py b/autogpt_platform/backend/backend/integrations/webhooks/github.py
index ef9bd9c680..c178215c82 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/github.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/github.py
@@ -30,17 +30,11 @@ class GithubWebhooksManager(BaseWebhooksManager):
GITHUB_API_DEFAULT_HEADERS = {"Accept": "application/vnd.github.v3+json"}
@classmethod
- async def validate_payload(
+ async def verify_signature(
cls,
webhook: integrations.Webhook,
request: Request,
- credentials: Credentials | None,
- ) -> tuple[dict, str]:
- if not (event_type := request.headers.get("X-GitHub-Event")):
- raise HTTPException(
- status_code=400, detail="X-GitHub-Event header is missing!"
- )
-
+ ) -> None:
if not (signature_header := request.headers.get("X-Hub-Signature-256")):
raise HTTPException(
status_code=403, detail="X-Hub-Signature-256 header is missing!"
@@ -57,6 +51,18 @@ class GithubWebhooksManager(BaseWebhooksManager):
status_code=403, detail="Request signatures didn't match!"
)
+ @classmethod
+ async def validate_payload(
+ cls,
+ webhook: integrations.Webhook,
+ request: Request,
+ credentials: Credentials | None,
+ ) -> tuple[dict, str]:
+ if not (event_type := request.headers.get("X-GitHub-Event")):
+ raise HTTPException(
+ status_code=400, detail="X-GitHub-Event header is missing!"
+ )
+
payload = await request.json()
if action := payload.get("action"):
event_type += f".{action}"
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/telegram.py b/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
index 7a9d3fdf47..a1ae80baaa 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
@@ -100,6 +100,21 @@ class TelegramWebhooksManager(BaseWebhooksManager):
credentials=credentials,
)
+ @classmethod
+ async def verify_signature(
+ cls,
+ webhook: integrations.Webhook,
+ request: Request,
+ ) -> None:
+ # Telegram sends X-Telegram-Bot-Api-Secret-Token when secret_token was
+ # set in the setWebhook call (we always set it; see _register_webhook).
+ secret_header = request.headers.get("X-Telegram-Bot-Api-Secret-Token")
+ if not secret_header or not hmac.compare_digest(secret_header, webhook.secret):
+ raise HTTPException(
+ status_code=403,
+ detail="Invalid or missing X-Telegram-Bot-Api-Secret-Token",
+ )
+
@classmethod
async def validate_payload(
cls,
@@ -110,20 +125,9 @@ class TelegramWebhooksManager(BaseWebhooksManager):
"""
Validates incoming Telegram webhook request.
- Telegram sends X-Telegram-Bot-Api-Secret-Token header when secret_token
- was set in setWebhook call.
-
Returns:
tuple: (payload dict, event_type string)
"""
- # Verify secret token header
- secret_header = request.headers.get("X-Telegram-Bot-Api-Secret-Token")
- if not secret_header or not hmac.compare_digest(secret_header, webhook.secret):
- raise HTTPException(
- status_code=403,
- detail="Invalid or missing X-Telegram-Bot-Api-Secret-Token",
- )
-
payload = await request.json()
# Determine event type based on update content
diff --git a/docs/integrations/block-integrations/generic_webhook/triggers.md b/docs/integrations/block-integrations/generic_webhook/triggers.md
index 3ca6562438..0e8eda94e3 100644
--- a/docs/integrations/block-integrations/generic_webhook/triggers.md
+++ b/docs/integrations/block-integrations/generic_webhook/triggers.md
@@ -20,6 +20,7 @@ Constants can be configured to pass additional static values alongside the dynam
| Input | Description | Type | Required |
|-------|-------------|------|----------|
| constants | The constants to be set when the block is put on the graph | Dict[str, Any] | No |
+| secret_token | Optional. If set, the platform will only accept incoming webhook requests that include this exact value in the 'X-Webhook-Secret' header. Leave empty for unauthenticated webhooks (the URL itself is the only credential). | str | No |
### Outputs
diff --git a/docs/platform/new_blocks.md b/docs/platform/new_blocks.md
index c84f864684..61f8d06e84 100644
--- a/docs/platform/new_blocks.md
+++ b/docs/platform/new_blocks.md
@@ -562,8 +562,19 @@ To add support for a new webhook provider, you'll need to create a WebhooksManag
--8<-- "autogpt_platform/backend/backend/integrations/webhooks/_base.py:BaseWebhooksManager3"
--8<-- "autogpt_platform/backend/backend/integrations/webhooks/_base.py:BaseWebhooksManager4"
--8<-- "autogpt_platform/backend/backend/integrations/webhooks/_base.py:BaseWebhooksManager5"
+--8<-- "autogpt_platform/backend/backend/integrations/webhooks/_base.py:BaseWebhooksManager6"
```
+!!! info "Signature verification (`verify_signature`)"
+ If the upstream provider signs its deliveries (e.g. GitHub's
+ `X-Hub-Signature-256`, Airtable's `X-Airtable-Content-MAC`), override
+ `verify_signature` and use `hmac.compare_digest` for the comparison.
+ Raise `fastapi.HTTPException(403)` on missing/invalid signatures.
+
+ If the provider has no signing scheme (consumer wearables, simple
+ "POST to this URL" tools), leave the default in place. The webhook
+ URL's UUID is then the bearer secret — document that for users.
+
And add a reference to your `WebhooksManager` class in `load_webhook_managers`:
```python title="backend/integrations/webhooks/__init__.py"