Skip to content
Open
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
25 changes: 25 additions & 0 deletions openhands/automation/event_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
body-derived ID inherits verification of the raw body
- Teams verifies the body but does not check timestamp freshness. Its
replay protection lasts only while the event deduplication row is retained

Handshakes:
- A `slack_v0` webhook answers Slack's Events API URL verification: the
signed `{"type": "url_verification", "challenge": ...}` delivery is
acknowledged with the raw challenge string
"""

import json
Expand All @@ -51,6 +56,7 @@
)
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import PlainTextResponse

from openhands.automation.acknowledgements import (
TEAMS_ACKNOWLEDGEMENT,
Expand All @@ -73,6 +79,7 @@
)
from openhands.automation.observability import span
from openhands.automation.providers import (
SLACK_VERIFIER,
WebhookVerifier,
get_header,
get_verifier,
Expand Down Expand Up @@ -207,6 +214,9 @@ async def receive_event(
The payload signature is verified using:
- AUTOMATION_WEBHOOK_SECRET for github (builtin, header: X-Hub-Signature-256)
- Per-org webhook_secret for custom sources (header configured per webhook)

A slack_v0 webhook answers Slack's signed URL verification challenge before
any event processing.
"""
# 1. Read raw body for signature verification
body = await request.body()
Expand Down Expand Up @@ -287,6 +297,21 @@ async def receive_event(
_log_rejection(source, org_id, "unrecognized_activity")
raise HTTPException(400, "Unrecognized Teams message activity")

# Slack Events API URL verification: the first delivery to a newly
# registered URL is a signed challenge that must be answered with the raw
# challenge string. It carries no event, so it is answered before delivery
# ID and admission policies only real events can satisfy.
if (
config.signature_scheme == SLACK_VERIFIER
and isinstance(payload, dict)
and payload.get("type") == "url_verification"
):
challenge = payload.get("challenge")
if not isinstance(challenge, str) or not challenge:
_log_rejection(source, org_id, "invalid_url_verification")
raise HTTPException(400, "Invalid URL verification challenge")
return PlainTextResponse(challenge)

# Extract IDs only from authenticated bytes, never silently dropping an
# invalid body ID and accepting without deduplication.
provider_event_id = (
Expand Down
3 changes: 2 additions & 1 deletion openhands/automation/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

DEFAULT_VERIFIER: Final[str] = "hmac_sha256_hex"
TEAMS_VERIFIER: Final[str] = "teams_hmac_sha256"
SLACK_VERIFIER: Final[str] = "slack_v0"
DEFAULT_BUILTIN_SIGNATURE_HEADER: Final[str] = "X-Hub-Signature-256"
# The OpenHands server forwards every built-in source's delivery id in GitHub's
# header name, as it signs every source into GitHub's signature header.
Expand Down Expand Up @@ -316,7 +317,7 @@ def verify(
{
"hmac_sha256_hex": HmacSha256HexVerifier(),
"standard_webhooks": StandardWebhooksVerifier(),
"slack_v0": SlackV0Verifier(),
SLACK_VERIFIER: SlackV0Verifier(),
TEAMS_VERIFIER: TeamsHmacSha256Verifier(),
}
)
Expand Down
4 changes: 3 additions & 1 deletion openhands/automation/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1001,7 +1001,9 @@ class CustomWebhookCreate(BaseModel):
"reads the webhook-id and webhook-timestamp headers. 'slack_v0' is "
"the Slack Events API scheme and also reads "
"X-Slack-Request-Timestamp. The timestamped schemes reject "
"deliveries outside a 5-minute replay window. 'teams_hmac_sha256' "
"deliveries outside a 5-minute replay window. A slack_v0 webhook "
"answers Slack's URL verification handshake automatically. "
"'teams_hmac_sha256' "
"verifies a Teams-issued base64 token over the raw activity body; "
"it requires Authorization, teams_message acknowledgement, "
"admission_expr and event_id_expr. Teams replay protection is "
Expand Down
145 changes: 145 additions & 0 deletions tests/test_event_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import hashlib
import hmac
import json
import time
import uuid

import jmespath
Expand Down Expand Up @@ -1238,3 +1239,147 @@ async def test_redelivered_custom_event_creates_runs_once(
events = (await async_session.execute(select(IntegrationEvent))).scalars().all()
assert len(events) == 1
assert events[0].provider_event_id == "72d3162e-cc78-11e3-81ab-4c9367dc0958"


def _slack_headers(body: bytes, secret: str = "s3cret-value") -> dict[str, str]:
"""Sign a body the way Slack's Events API does."""
now = str(int(time.time()))
signed = b"v0:" + now.encode() + b":" + body
digest = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return {
"X-Slack-Signature": f"v0={digest}",
"X-Slack-Request-Timestamp": now,
"Content-Type": "application/json",
}


async def _add_slack_webhook(async_session, org_id: uuid.UUID, source: str) -> None:
"""A Slack Events API webhook: v0 signing and a body-derived delivery id."""
async_session.add(
CustomWebhook(
org_id=org_id,
name=source,
source=source,
webhook_secret="s3cret-value",
event_key_expr="type",
signature_header="X-Slack-Signature",
signature_scheme="slack_v0",
# Real events dedupe on the event ts; a URL verification carries none.
event_id_expr="event.ts",
)
)
await async_session.commit()


@pytest.mark.asyncio
async def test_slack_url_verification_challenge_is_echoed(
async_client: AsyncClient,
org_id: uuid.UUID,
async_session,
mock_authenticated_user,
):
"""A signed URL verification is answered with its challenge, verbatim.

Slack's first delivery to a new webhook URL must be answered with the raw
challenge string, before any event parsing or body-ID extraction (the
verification payload has no event.ts).
"""
await _add_slack_webhook(async_session, org_id, "slack")

body = json.dumps(
{"type": "url_verification", "challenge": "3eZbrw1a6mfsZjFAdZuk"}
).encode()
response = await async_client.post(
f"/api/automation/v1/events/{org_id}/slack",
content=body,
headers=_slack_headers(body),
)

assert response.status_code == 200
assert response.text == "3eZbrw1a6mfsZjFAdZuk"
assert response.headers["content-type"].startswith("text/plain")

events = (await async_session.execute(select(IntegrationEvent))).scalars().all()
assert events == []


@pytest.mark.asyncio
async def test_slack_url_verification_rejects_a_missing_challenge(
async_client: AsyncClient,
org_id: uuid.UUID,
async_session,
):
"""A verification without a challenge is a bad request, not a run."""
await _add_slack_webhook(async_session, org_id, "slack")

body = json.dumps({"type": "url_verification"}).encode()
response = await async_client.post(
f"/api/automation/v1/events/{org_id}/slack",
content=body,
headers=_slack_headers(body),
)

assert response.status_code == 400


@pytest.mark.asyncio
async def test_slack_url_verification_requires_a_valid_signature(
async_client: AsyncClient,
org_id: uuid.UUID,
async_session,
):
"""The challenge is echoed only to a delivery Slack signed."""
await _add_slack_webhook(async_session, org_id, "slack")

body = json.dumps(
{"type": "url_verification", "challenge": "3eZbrw1a6mfsZjFAdZuk"}
).encode()
headers = _slack_headers(body)
headers["X-Slack-Signature"] = "v0=" + "0" * 64
response = await async_client.post(
f"/api/automation/v1/events/{org_id}/slack",
content=body,
headers=headers,
)

assert response.status_code == 401


@pytest.mark.asyncio
async def test_slack_events_still_route_after_verification(
async_client: AsyncClient,
org_id: uuid.UUID,
async_session,
mock_authenticated_user,
):
"""A signed event on the same webhook still parses, dedupes and routes."""
await _add_slack_webhook(async_session, org_id, "slack")
async_session.add(
Automation(
id=uuid.uuid4(),
user_id=mock_authenticated_user.user_id,
org_id=org_id,
name="On slack mentions",
tarball_path="oh-internal://uploads/test.tar.gz",
entrypoint="python main.py",
trigger={"type": "event", "source": "slack", "on": "app_mention"},
)
)
await async_session.commit()

body = json.dumps(
{
"type": "app_mention",
"event": {"type": "app_mention", "ts": "1725864000.000100"},
}
).encode()
response = await async_client.post(
f"/api/automation/v1/events/{org_id}/slack",
content=body,
headers=_slack_headers(body),
)

assert response.status_code == 200
assert response.json()["matched"] == 1
events = (await async_session.execute(select(IntegrationEvent))).scalars().all()
assert [event.provider_event_id for event in events] == ["1725864000.000100"]
Loading