diff --git a/.env.example b/.env.example index baaa456..304ff5c 100644 --- a/.env.example +++ b/.env.example @@ -33,6 +33,11 @@ MONERO_DAEMON_URL=http://xmr-node.cakewallet.com:18081 # Admin panel (generate with: openssl rand -base64 32 | tr -d '=' | head -c 32) ADMIN_API_KEY= +# Webhook targets must resolve to public addresses. List exact hostnames here +# (comma separated) that may resolve to a private address, such as a receiver +# reached over the LAN. Empty refuses every private target. +WEBHOOK_ALLOWED_PRIVATE_HOSTS= + # Registration (set to false to require manual merchant onboarding) OPEN_REGISTRATION=true diff --git a/api/app/btcpay_webhooks.py b/api/app/btcpay_webhooks.py index a1fcb85..1630086 100644 --- a/api/app/btcpay_webhooks.py +++ b/api/app/btcpay_webhooks.py @@ -6,20 +6,16 @@ import json import logging import time from datetime import datetime, timezone -from urllib.parse import urljoin -import requests from requests import RequestException from sqlalchemy.orm import Session from .models import BtcpayWebhook, Invoice, InvoiceTransfer from .security import decrypt_secret +from .webhook_targets import WebhookTargetRefused, post_webhook logger = logging.getLogger(__name__) -_REDIRECT_STATUSES = {301, 302, 303, 307, 308} - - def dispatch_btcpay_webhooks( db: Session, user_id: str, @@ -61,13 +57,13 @@ def dispatch_btcpay_webhooks( last_response = None for attempt in range(3): try: - last_response = _post_with_redirects( + last_response = post_webhook( hook.url, data=body, headers=headers, timeout=10, ) - if last_response is not None and last_response.status_code < 500: + if last_response.status_code < 500: break except RequestException: if attempt == 2: @@ -75,12 +71,9 @@ def dispatch_btcpay_webhooks( if attempt < 2: time.sleep(1.0 * (attempt + 1)) if last_response is None: - logger.warning( - "BTCPay webhook delivery failed after retries (redirect loop)", - extra={"webhook_id": str(hook.id), "event": event_type, "url": hook.url}, - ) continue - if last_response.status_code >= 400: + # Redirects are not followed, so a 3xx is a failed delivery. + if last_response.status_code >= 300: logger.warning( "BTCPay webhook delivered non-success status", extra={ @@ -89,6 +82,12 @@ def dispatch_btcpay_webhooks( "http_status": last_response.status_code, }, ) + except WebhookTargetRefused as exc: + logger.warning( + "BTCPay webhook target refused: %s", + exc, + extra={"webhook_id": str(hook.id), "event": event_type}, + ) except RequestException as exc: logger.error( "BTCPay webhook delivery failed after 3 attempts: %s", @@ -179,29 +178,3 @@ def _after_expiration(invoice: Invoice) -> bool: def _sign_payload(body: bytes, secret: str) -> str: return hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest() - - -def _post_with_redirects( - url: str, - *, - data: bytes, - headers: dict[str, str], - timeout: int, - max_redirects: int = 3, -) -> requests.Response | None: - current_url = url - for _ in range(max_redirects + 1): - response = requests.post( - current_url, - data=data, - headers=headers, - timeout=timeout, - allow_redirects=False, - ) - if response.status_code not in _REDIRECT_STATUSES: - return response - location = response.headers.get("Location") - if not location: - return response - current_url = urljoin(current_url, location) - return None diff --git a/api/app/config.py b/api/app/config.py index 579633a..8ddb047 100644 --- a/api/app/config.py +++ b/api/app/config.py @@ -47,3 +47,12 @@ FOUNDER_PAYMENT_ADDRESS = os.getenv("FOUNDER_PAYMENT_ADDRESS", "") FOUNDER_VIEW_KEY = os.getenv("FOUNDER_VIEW_KEY", "") QR_STORAGE_DIR = os.getenv("QR_STORAGE_DIR", "/qr") ADMIN_API_KEY = os.getenv("ADMIN_API_KEY", "").strip() + +# Webhook targets must resolve to public addresses. Hostnames listed here may +# resolve to private addresses, for a merchant receiver reached over a LAN. +# Exact hostnames, comma separated; empty refuses every private target. +WEBHOOK_ALLOWED_PRIVATE_HOSTS = frozenset( + host.strip().lower().rstrip(".") + for host in os.getenv("WEBHOOK_ALLOWED_PRIVATE_HOSTS", "").split(",") + if host.strip() +) diff --git a/api/app/routes.py b/api/app/routes.py index 116e2aa..d98c101 100644 --- a/api/app/routes.py +++ b/api/app/routes.py @@ -8,7 +8,6 @@ import json from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status from fastapi.responses import RedirectResponse, StreamingResponse -import requests from requests import RequestException from sqlalchemy import func, or_ from sqlalchemy.sql import cast @@ -60,6 +59,7 @@ from .security import ( require_api_key, ) from .webhooks import build_webhook_payload, dispatch_webhooks +from .webhook_targets import WebhookTargetRefused, delivery_error_message, post_webhook from .qr_codes import ensure_invoice_qr_png, invoice_qr_url, resolve_qr_settings router = APIRouter() @@ -740,15 +740,15 @@ def redeliver_webhook_delivery( status_code = None error_message = None try: - response = requests.post( + response = post_webhook( delivery.url, json=payload, headers={"X-Webhook-Secret": webhook_secret}, timeout=5, ) status_code = response.status_code - except RequestException as exc: - error_message = str(exc) + except (RequestException, WebhookTargetRefused) as exc: + error_message = delivery_error_message(exc) redelivery = WebhookDelivery( user_id=user.id, diff --git a/api/app/webhook_targets.py b/api/app/webhook_targets.py new file mode 100644 index 0000000..ba04c57 --- /dev/null +++ b/api/app/webhook_targets.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +import ipaddress +import socket +from typing import Any +from urllib.parse import urlsplit + +import requests + +from .config import WEBHOOK_ALLOWED_PRIVATE_HOSTS + + +class WebhookTargetRefused(Exception): + """The webhook URL points somewhere this service must not send requests.""" + + +def _is_public(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: + if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None: + address = address.ipv4_mapped + return address.is_global and not ( + address.is_private + or address.is_loopback + or address.is_link_local + or address.is_multicast + or address.is_reserved + or address.is_unspecified + ) + + +def _resolve(host: str, port: int) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]: + try: + infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) + except socket.gaierror as exc: + raise WebhookTargetRefused("webhook host does not resolve") from exc + return [ipaddress.ip_address(info[4][0].split("%", 1)[0]) for info in infos] + + +def check_webhook_target(url: str, *, allowed_private_hosts: frozenset[str] | None = None) -> None: + """Refuse a URL that is not http(s) or that resolves to a non-public address. + + Every resolved address must be public, so a name with one private record is + refused. Hosts in allowed_private_hosts (default: WEBHOOK_ALLOWED_PRIVATE_HOSTS) + skip the address check. + """ + allowed = WEBHOOK_ALLOWED_PRIVATE_HOSTS if allowed_private_hosts is None else allowed_private_hosts + parts = urlsplit(url) + if parts.scheme not in ("http", "https"): + raise WebhookTargetRefused("webhook URL must use http or https") + host = (parts.hostname or "").lower().rstrip(".") + if not host: + raise WebhookTargetRefused("webhook URL has no host") + if parts.username or parts.password: + raise WebhookTargetRefused("webhook URL must not carry credentials") + if host in allowed: + return + try: + port = parts.port or (443 if parts.scheme == "https" else 80) + except ValueError as exc: + raise WebhookTargetRefused("webhook URL has an invalid port") from exc + addresses = _resolve(host, port) + if not addresses or not all(_is_public(address) for address in addresses): + raise WebhookTargetRefused("webhook host resolves to a non-public address") + + +def post_webhook(url: str, **kwargs: Any) -> requests.Response: + """Check the target, then POST once without following redirects.""" + check_webhook_target(url) + kwargs["allow_redirects"] = False + return requests.post(url, **kwargs) + + +def delivery_error_message(exc: Exception) -> str: + """A delivery error safe to store and show: never the raw exception text.""" + if isinstance(exc, WebhookTargetRefused): + return f"refused: {exc}" + return f"delivery failed ({type(exc).__name__})" diff --git a/api/app/webhooks.py b/api/app/webhooks.py index 9a44cff..1abf900 100644 --- a/api/app/webhooks.py +++ b/api/app/webhooks.py @@ -4,13 +4,13 @@ import logging import uuid from datetime import datetime -import requests from requests import RequestException from sqlalchemy.orm import Session from .formatting import format_xmr_amount from .models import Invoice, User, Webhook, WebhookDelivery from .security import decrypt_secret, encrypt_secret, generate_webhook_secret +from .webhook_targets import WebhookTargetRefused, delivery_error_message, post_webhook logger = logging.getLogger(__name__) @@ -73,10 +73,10 @@ def dispatch_webhooks( error_message = None try: headers = {"X-Webhook-Secret": webhook_secret} if webhook_secret else None - response = requests.post(target_url, json=payload, headers=headers, timeout=5) + response = post_webhook(target_url, json=payload, headers=headers, timeout=5) status_code = response.status_code - except RequestException as exc: - error_message = str(exc) + except (RequestException, WebhookTargetRefused) as exc: + error_message = delivery_error_message(exc) logger.warning( "Webhook delivery failed", extra={"webhook_id": str(hook.id), "event": event}, diff --git a/api/tests/test_webhook_targets.py b/api/tests/test_webhook_targets.py new file mode 100644 index 0000000..68240d6 --- /dev/null +++ b/api/tests/test_webhook_targets.py @@ -0,0 +1,112 @@ +import socket +import unittest +from unittest import mock + +from requests import ConnectionError as RequestsConnectionError + +from app import webhook_targets +from app.webhook_targets import ( + WebhookTargetRefused, + check_webhook_target, + delivery_error_message, + post_webhook, +) + + +def _resolves_to(*addresses): + def fake(host, port, type=0): + return [(socket.AF_INET6 if ":" in a else socket.AF_INET, type, 6, "", (a, port)) for a in addresses] + return fake + + +class WebhookTargetTests(unittest.TestCase): + def _check(self, url, *addresses, allowed=frozenset()): + with mock.patch.object(webhook_targets.socket, "getaddrinfo", side_effect=_resolves_to(*addresses)): + check_webhook_target(url, allowed_private_hosts=allowed) + + def test_internal_targets_are_refused(self): + for address in [ + "127.0.0.1", + "10.1.2.3", + "172.17.0.5", + "192.168.88.10", + "169.254.169.254", + "100.64.0.1", + "0.0.0.0", + "::1", + "fd00::1", + "fe80::1", + "::ffff:127.0.0.1", + ]: + with self.subTest(address=address), self.assertRaises(WebhookTargetRefused): + self._check("https://merchant.example/hook", address) + + def test_one_private_record_among_public_ones_is_refused(self): + with self.assertRaises(WebhookTargetRefused): + self._check("https://merchant.example/hook", "93.184.216.34", "10.0.0.1") + + def test_a_public_target_is_accepted(self): + self._check("https://merchant.example/hook", "93.184.216.34") + + def test_an_allowlisted_host_may_resolve_privately(self): + self._check("http://receiver.lan.example/hook", "192.168.1.20", allowed=frozenset({"receiver.lan.example"})) + + def test_non_http_schemes_and_embedded_credentials_are_refused(self): + for url in ["file:///etc/passwd", "gopher://merchant.example/", "https://user:pw@merchant.example/"]: + with self.subTest(url=url), self.assertRaises(WebhookTargetRefused): + self._check(url, "93.184.216.34") + + def test_delivery_never_follows_redirects(self): + with mock.patch.object(webhook_targets.socket, "getaddrinfo", side_effect=_resolves_to("93.184.216.34")), \ + mock.patch.object(webhook_targets.requests, "post") as post: + post_webhook("https://merchant.example/hook", data=b"{}", allow_redirects=True, timeout=5) + self.assertIs(post.call_args.kwargs["allow_redirects"], False) + + def test_a_refused_target_is_never_contacted(self): + with mock.patch.object(webhook_targets.socket, "getaddrinfo", side_effect=_resolves_to("10.0.0.1")), \ + mock.patch.object(webhook_targets.requests, "post") as post: + with self.assertRaises(WebhookTargetRefused): + post_webhook("https://merchant.example/hook", data=b"{}", timeout=5) + post.assert_not_called() + + def test_stored_errors_do_not_echo_the_exception_text(self): + detail = "HTTPConnectionPool(host='10.0.0.7', port=5432): secret internal detail" + message = delivery_error_message(RequestsConnectionError(detail)) + self.assertNotIn("10.0.0.7", message) + self.assertNotIn("5432", message) + + +class DeliveryPathTests(unittest.TestCase): + """The real delivery code must route every request through the guard.""" + + def test_native_webhooks_refuse_internal_targets(self): + from app import webhooks + + hook = mock.Mock(events=["invoice.created"], event_urls={}, url="http://10.0.0.5:5432/x", id="h") + db = mock.Mock() + db.query.return_value.filter.return_value.all.return_value = [hook] + db.query.return_value.filter.return_value.first.return_value = None + invoice = mock.MagicMock() + with mock.patch.object(webhook_targets.socket, "getaddrinfo", side_effect=_resolves_to("10.0.0.5")), \ + mock.patch.object(webhook_targets.requests, "post") as post, \ + mock.patch.object(webhooks, "build_webhook_payload", return_value={}): + webhooks.dispatch_webhooks(db, "00000000-0000-0000-0000-000000000001", "invoice.created", invoice) + post.assert_not_called() + + def test_btcpay_webhooks_refuse_internal_targets(self): + from app import btcpay_webhooks + + hook = mock.Mock(url="http://169.254.169.254/latest", id="h", authorized_events={"everything": True}) + db = mock.Mock() + db.query.return_value.filter.return_value.all.return_value = [hook] + with mock.patch.object(webhook_targets.socket, "getaddrinfo", side_effect=_resolves_to("169.254.169.254")), \ + mock.patch.object(webhook_targets.requests, "post") as post, \ + mock.patch.object(btcpay_webhooks, "_build_payload", return_value={}), \ + mock.patch.object(btcpay_webhooks, "decrypt_secret", return_value="s" * 32), \ + mock.patch.object(btcpay_webhooks.time, "sleep"): + btcpay_webhooks.dispatch_btcpay_webhooks(db, "u", "InvoiceSettled", mock.MagicMock()) + post.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/docker-compose.yml b/docker-compose.yml index 9a3903a..9ac605b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -26,6 +26,7 @@ services: DONATIONS_ENABLED: ${DONATIONS_ENABLED:-false} OPEN_REGISTRATION: ${OPEN_REGISTRATION:-true} ADMIN_API_KEY: ${ADMIN_API_KEY:-} + WEBHOOK_ALLOWED_PRIVATE_HOSTS: ${WEBHOOK_ALLOWED_PRIVATE_HOSTS:-} QR_STORAGE_DIR: ${QR_STORAGE_DIR:-/qr} MONERO_WALLET_RPC_URLS: ${MONERO_WALLET_RPC_URLS:-http://wallet-rpc-reconciler-1:18083,http://wallet-rpc-reconciler-2:18083,http://wallet-rpc-reconciler-3:18083} MONERO_WALLET_RPC_USER: ${MONERO_WALLET_RPC_USER} @@ -50,6 +51,7 @@ services: API_KEY_ENCRYPTION_KEY: ${API_KEY_ENCRYPTION_KEY} INVOICE_RECONCILE_INTERVAL_SECONDS: ${INVOICE_RECONCILE_INTERVAL_SECONDS} LOG_LEVEL: ${LOG_LEVEL:-INFO} + WEBHOOK_ALLOWED_PRIVATE_HOSTS: ${WEBHOOK_ALLOWED_PRIVATE_HOSTS:-} MONERO_WALLET_RPC_URLS: ${MONERO_WALLET_RPC_URLS:-http://wallet-rpc-reconciler-1:18083,http://wallet-rpc-reconciler-2:18083,http://wallet-rpc-reconciler-3:18083} MONERO_WALLET_RPC_USER: ${MONERO_WALLET_RPC_USER} MONERO_WALLET_RPC_PASSWORD: ${MONERO_WALLET_RPC_PASSWORD}