fix(webhooks): authenticate deliveries via WEBHOOK_SECRET; review nits
Adds optional shared-secret authentication for /webhooks/nextcloud, addressing the security follow-up flagged in #747. Behavior: - WEBHOOK_SECRET set: registrations pass authMethod="header" with authData={"Authorization": "Bearer <secret>"} (encrypted at-rest in Nextcloud's DB and forwarded on every delivery). The receiver validates the same header with hmac.compare_digest before parsing any payload; missing/invalid → 401. - WEBHOOK_SECRET unset: registrations stay on authMethod="none" and the receiver accepts unauthenticated POSTs (logging a one-time startup warning). Backward compatible — operators can roll out at their own pace. Implementation notes: - WebhooksClient.create_webhook gains an `auth_data` parameter mapped to NC's `authData` body field; this is distinct from the existing `headers` parameter (`headers` is plaintext static request headers, `authData` is encrypted at-rest in NC and only emitted when authMethod="header"). The previous `auth_method="bearer"` mention in the docstring was incorrect — NC supports only "none" and "header". - A small `webhook_auth_pair()` helper in auth/webhook_routes.py centralises the secret→(auth_method, auth_data) resolution so the preset flow and the Astrolabe-facing /api/v1/webhooks endpoint stay in sync. Also addresses the smaller review points from #747: - f-string → lazy %s formatting in webhook_receiver.py and webhook_routes.py. - Move `int(time)` inside webhook_parser's try/except so a malformed `time` field returns None instead of raising ValueError. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
2e2a098bee
commit
224428fca5
@@ -18,6 +18,7 @@ from nextcloud_mcp_server.api.management import (
|
||||
extract_bearer_token,
|
||||
validate_token_and_get_user,
|
||||
)
|
||||
from nextcloud_mcp_server.auth.webhook_routes import webhook_auth_pair
|
||||
from nextcloud_mcp_server.client.webhooks import WebhooksClient
|
||||
|
||||
from ..http import nextcloud_httpx_client
|
||||
@@ -213,10 +214,16 @@ async def create_webhook(request: Request) -> JSONResponse:
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=30.0,
|
||||
) as client:
|
||||
# Use WebhooksClient to create webhook
|
||||
# Use WebhooksClient to create webhook. Inject auth headers when
|
||||
# WEBHOOK_SECRET is configured so deliveries are authenticated.
|
||||
webhooks_client = WebhooksClient(client, user_id)
|
||||
auth_method, auth_data = webhook_auth_pair()
|
||||
webhook_data = await webhooks_client.create_webhook(
|
||||
event=event, uri=uri, event_filter=event_filter
|
||||
event=event,
|
||||
uri=uri,
|
||||
event_filter=event_filter,
|
||||
auth_method=auth_method,
|
||||
auth_data=auth_data,
|
||||
)
|
||||
|
||||
return JSONResponse({"webhook": webhook_data})
|
||||
|
||||
@@ -14,6 +14,7 @@ from starlette.responses import HTMLResponse
|
||||
|
||||
from nextcloud_mcp_server.auth.permissions import is_nextcloud_admin
|
||||
from nextcloud_mcp_server.client.webhooks import WebhooksClient
|
||||
from nextcloud_mcp_server.config import get_settings
|
||||
from nextcloud_mcp_server.server.webhook_presets import (
|
||||
WEBHOOK_PRESETS,
|
||||
filter_presets_by_installed_apps,
|
||||
@@ -111,13 +112,33 @@ def _get_webhook_uri() -> str:
|
||||
service_name = os.getenv("NEXTCLOUD_MCP_SERVICE_NAME", "mcp")
|
||||
port = os.getenv("NEXTCLOUD_MCP_PORT", "8000")
|
||||
logger.debug(
|
||||
f"Docker environment detected, using internal URL: http://{service_name}:{port}"
|
||||
"Docker environment detected, using internal URL: http://%s:%s",
|
||||
service_name,
|
||||
port,
|
||||
)
|
||||
return f"http://{service_name}:{port}/webhooks/nextcloud"
|
||||
|
||||
return "http://localhost:8000/webhooks/nextcloud"
|
||||
|
||||
|
||||
def webhook_auth_pair() -> tuple[str, dict[str, str] | None]:
|
||||
"""Resolve ``(auth_method, auth_data)`` for new webhook registrations.
|
||||
|
||||
When ``WEBHOOK_SECRET`` is set, returns
|
||||
``("header", {"Authorization": f"Bearer {secret}"})`` so NC stores the
|
||||
credential encrypted at-rest and forwards it on every delivery. When
|
||||
unset, returns ``("none", None)`` — backward-compatible with deployments
|
||||
that haven't rolled out webhook auth yet.
|
||||
|
||||
Shared by both registration call sites: the ``/app/webhooks`` preset
|
||||
flow and the Astrolabe-facing ``/api/v1/webhooks`` endpoint.
|
||||
"""
|
||||
secret = get_settings().webhook_secret
|
||||
if not secret:
|
||||
return ("none", None)
|
||||
return ("header", {"Authorization": f"Bearer {secret}"})
|
||||
|
||||
|
||||
async def _get_authenticated_client(request: Request) -> httpx.AsyncClient:
|
||||
"""Get an authenticated HTTP client for Nextcloud API calls.
|
||||
|
||||
@@ -400,11 +421,14 @@ async def enable_webhook_preset(request: Request) -> HTMLResponse:
|
||||
webhook_uri = _get_webhook_uri()
|
||||
registered_ids = []
|
||||
|
||||
auth_method, auth_data = webhook_auth_pair()
|
||||
for event_config in preset["events"]:
|
||||
webhook_data = await webhooks_client.create_webhook(
|
||||
event=event_config["event"],
|
||||
uri=webhook_uri,
|
||||
event_filter=event_config["filter"] if event_config["filter"] else None,
|
||||
auth_method=auth_method,
|
||||
auth_data=auth_data,
|
||||
)
|
||||
webhook_id = webhook_data["id"]
|
||||
registered_ids.append(webhook_id)
|
||||
|
||||
@@ -41,6 +41,7 @@ class WebhooksClient(BaseNextcloudClient):
|
||||
http_method: str = "POST",
|
||||
auth_method: str = "none",
|
||||
headers: Optional[Dict[str, str]] = None,
|
||||
auth_data: Optional[Dict[str, str]] = None,
|
||||
event_filter: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Register a new webhook for the specified event.
|
||||
@@ -49,8 +50,14 @@ class WebhooksClient(BaseNextcloudClient):
|
||||
event: Fully qualified event class name (e.g., "OCP\\Files\\Events\\Node\\NodeCreatedEvent")
|
||||
uri: Webhook endpoint URL to receive event notifications
|
||||
http_method: HTTP method for webhook delivery (default: "POST")
|
||||
auth_method: Authentication method ("none", "bearer", etc.)
|
||||
headers: Custom headers to include in webhook requests (e.g., Authorization header)
|
||||
auth_method: Authentication method. Nextcloud's webhook_listeners
|
||||
app accepts only ``"none"`` or ``"header"``.
|
||||
headers: Optional static request headers attached to every
|
||||
delivery (stored in clear text on the NC side).
|
||||
auth_data: When ``auth_method="header"``, a dict of headers
|
||||
holding the auth credentials. Stored encrypted at-rest in
|
||||
Nextcloud's database and merged into the delivery request
|
||||
at send time. Required when ``auth_method="header"``.
|
||||
event_filter: JSON object specifying event filters (e.g., {"user.uid": "bob"})
|
||||
|
||||
Returns:
|
||||
@@ -66,6 +73,9 @@ class WebhooksClient(BaseNextcloudClient):
|
||||
if headers:
|
||||
data["headers"] = headers
|
||||
|
||||
if auth_data:
|
||||
data["authData"] = auth_data
|
||||
|
||||
if event_filter:
|
||||
data["eventFilter"] = event_filter
|
||||
|
||||
|
||||
@@ -53,6 +53,10 @@ _DEFAULTS: dict[str, Any] = {
|
||||
# None = ephemeral per-process tempfile (see get_token_db_path()).
|
||||
# Set TOKEN_STORAGE_DB to persist tokens across restarts.
|
||||
"token_storage_db": None,
|
||||
# Webhook delivery authentication (ADR-010): when set, registrations
|
||||
# tell NC to add `Authorization: Bearer <secret>` to webhook deliveries
|
||||
# and the receiver rejects unauthenticated requests.
|
||||
"webhook_secret": None,
|
||||
# Vector sync
|
||||
"vector_sync_scan_interval": 300,
|
||||
"vector_sync_processor_workers": 3,
|
||||
@@ -430,6 +434,13 @@ class Settings:
|
||||
token_encryption_key: str | None = None
|
||||
token_storage_db: str | None = None
|
||||
|
||||
# Webhook delivery authentication (ADR-010).
|
||||
# When set, the registrar passes Authorization: Bearer <secret> as the
|
||||
# webhook authData and the receiver validates the same header on each
|
||||
# delivery. When unset, registration uses authMethod="none" and the
|
||||
# receiver accepts unauthenticated POSTs (backward-compatible).
|
||||
webhook_secret: str | None = None
|
||||
|
||||
# Vector sync settings (ADR-007)
|
||||
vector_sync_enabled: bool = False
|
||||
vector_sync_scan_interval: int = 300 # seconds (5 minutes)
|
||||
@@ -767,6 +778,8 @@ def get_settings() -> Settings:
|
||||
# Token and webhook storage settings
|
||||
"token_encryption_key": "TOKEN_ENCRYPTION_KEY",
|
||||
"token_storage_db": "TOKEN_STORAGE_DB",
|
||||
# Webhook auth (ADR-010)
|
||||
"webhook_secret": "WEBHOOK_SECRET",
|
||||
# Vector sync settings (ADR-007)
|
||||
"vector_sync_scan_interval": "VECTOR_SYNC_SCAN_INTERVAL",
|
||||
"vector_sync_processor_workers": "VECTOR_SYNC_PROCESSOR_WORKERS",
|
||||
|
||||
@@ -38,8 +38,9 @@ def extract_document_task(payload: dict) -> DocumentTask | None:
|
||||
event = payload["event"]
|
||||
event_class = event["class"]
|
||||
user_id = payload["user"]["uid"]
|
||||
except (KeyError, TypeError):
|
||||
logger.debug("Webhook payload missing user/event/class fields")
|
||||
time = int(payload.get("time", 0) or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
logger.debug("Webhook payload has missing or malformed envelope fields")
|
||||
return None
|
||||
|
||||
if event_class in (
|
||||
@@ -47,7 +48,7 @@ def extract_document_task(payload: dict) -> DocumentTask | None:
|
||||
_FILE_EVENT_WRITTEN,
|
||||
_FILE_EVENT_BEFORE_DELETED,
|
||||
):
|
||||
return _parse_file_event(event_class, event, user_id, payload.get("time", 0))
|
||||
return _parse_file_event(event_class, event, user_id, time)
|
||||
|
||||
logger.debug("Ignoring webhook for unsupported event: %s", event_class)
|
||||
return None
|
||||
@@ -82,5 +83,5 @@ def _parse_file_event(
|
||||
doc_id=str(node_id),
|
||||
doc_type="note",
|
||||
operation=operation,
|
||||
modified_at=int(time),
|
||||
modified_at=time,
|
||||
)
|
||||
|
||||
@@ -5,15 +5,37 @@ The receiver is registered as a Starlette route at ``/webhooks/nextcloud``
|
||||
in :mod:`nextcloud_mcp_server.app`.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
|
||||
from nextcloud_mcp_server.config import get_settings
|
||||
from nextcloud_mcp_server.vector.webhook_parser import extract_document_task
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_warned_about_missing_secret = False
|
||||
|
||||
|
||||
def _warn_missing_secret_once() -> None:
|
||||
"""Log a one-time WARNING when WEBHOOK_SECRET is unset.
|
||||
|
||||
The receiver still accepts unauthenticated POSTs in this case so existing
|
||||
deployments keep working, but the operator should know they're running
|
||||
without webhook auth.
|
||||
"""
|
||||
global _warned_about_missing_secret
|
||||
if _warned_about_missing_secret:
|
||||
return
|
||||
_warned_about_missing_secret = True
|
||||
logger.warning(
|
||||
"WEBHOOK_SECRET is not set; /webhooks/nextcloud accepts "
|
||||
"unauthenticated requests. Set WEBHOOK_SECRET and re-register "
|
||||
"webhooks to enable Authorization: Bearer validation."
|
||||
)
|
||||
|
||||
|
||||
async def handle_nextcloud_webhook(request: Request) -> JSONResponse:
|
||||
"""Receive a Nextcloud webhook and queue a DocumentTask for vector sync.
|
||||
@@ -21,11 +43,29 @@ async def handle_nextcloud_webhook(request: Request) -> JSONResponse:
|
||||
Returns quickly so NC's webhook worker is not blocked. The send-stream is
|
||||
read from ``request.app.state.document_send_stream``; when vector sync
|
||||
isn't running we return 503 so NC retries delivery.
|
||||
|
||||
When ``WEBHOOK_SECRET`` is set, the request must carry
|
||||
``Authorization: Bearer <secret>`` (registered via ``authData`` so NC
|
||||
forwards it on every delivery); requests without a valid header are
|
||||
rejected with 401 before any further work.
|
||||
"""
|
||||
secret = get_settings().webhook_secret
|
||||
if secret:
|
||||
provided = request.headers.get("authorization", "")
|
||||
expected = f"Bearer {secret}"
|
||||
if not provided or not hmac.compare_digest(provided, expected):
|
||||
logger.warning("Webhook rejected: missing or invalid Authorization header")
|
||||
return JSONResponse(
|
||||
{"status": "unauthorized"},
|
||||
status_code=401,
|
||||
)
|
||||
else:
|
||||
_warn_missing_secret_once()
|
||||
|
||||
try:
|
||||
payload = await request.json()
|
||||
except Exception as e:
|
||||
logger.warning(f"Webhook payload was not valid JSON: {e}")
|
||||
logger.warning("Webhook payload was not valid JSON: %s", e)
|
||||
return JSONResponse(
|
||||
{"status": "error", "message": "invalid JSON"},
|
||||
status_code=400,
|
||||
|
||||
Reference in New Issue
Block a user