|
| 1 | +from ipaddress import ip_address |
| 2 | +from urllib.parse import urlparse |
| 3 | + |
| 4 | +from fastapi import FastAPI, HTTPException, Query |
| 5 | +import httpx |
| 6 | + |
| 7 | +app = FastAPI(title="Hardened webhook tester") |
| 8 | + |
| 9 | +ALLOWED_WEBHOOK_HOSTS = {"hooks.stripe.com", "api.github.com", "discord.com"} |
| 10 | + |
| 11 | + |
| 12 | +def validate_webhook_url(url: str) -> str: |
| 13 | + parsed = urlparse(url) |
| 14 | + |
| 15 | + # FIX: allow only HTTPS and an explicit host allowlist. This prevents users |
| 16 | + # from turning the API into a proxy for arbitrary internal services. |
| 17 | + if parsed.scheme != "https": |
| 18 | + raise HTTPException(status_code=400, detail="Webhook URL must use HTTPS") |
| 19 | + if parsed.hostname not in ALLOWED_WEBHOOK_HOSTS: |
| 20 | + raise HTTPException(status_code=400, detail="Webhook host is not allowed") |
| 21 | + |
| 22 | + # FIX: reject literal private, loopback, and link-local IP addresses. Host |
| 23 | + # allowlists are still the main control; this blocks obvious bypass attempts. |
| 24 | + try: |
| 25 | + host_ip = ip_address(parsed.hostname) |
| 26 | + except ValueError: |
| 27 | + return url |
| 28 | + |
| 29 | + if host_ip.is_private or host_ip.is_loopback or host_ip.is_link_local: |
| 30 | + raise HTTPException(status_code=400, detail="Webhook host is not allowed") |
| 31 | + return url |
| 32 | + |
| 33 | + |
| 34 | +@app.get("/webhook/test") |
| 35 | +async def test_webhook(url: str = Query(..., max_length=300)): |
| 36 | + safe_url = validate_webhook_url(url) |
| 37 | + |
| 38 | + try: |
| 39 | + async with httpx.AsyncClient( |
| 40 | + timeout=httpx.Timeout(3.0), |
| 41 | + follow_redirects=False, |
| 42 | + ) as client: |
| 43 | + response = await client.get(safe_url) |
| 44 | + except httpx.HTTPError as exc: |
| 45 | + raise HTTPException(status_code=502, detail="Webhook test failed") from exc |
| 46 | + |
| 47 | + # FIX: return only minimal metadata. Do not proxy response bodies or headers |
| 48 | + # from third-party systems back to the caller. |
| 49 | + return {"status_code": response.status_code, "reachable": response.is_success} |
0 commit comments