fix: WebSub hardening from the adversarial review (v2.10.1)
- Per-item error handling in the worker; hard time limits on requests - Notes with photos announced after attach; feed cache/ETag follow content_version - Keep failing subscriptions until lease end; retry DNS and render errors; hub.mode=denied for gone topics - Spec 5.1: decode unreserved chars, echo requested topic, ignore lease and secret on unsubscribe, case-insensitive Content-Type, refuse empty secret - Limits count pending requests per callback address; callback validation; request_id guards the verification race (migration 017) - Render once per topic per pass; likes only push /likes; Vary: Accept Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
409b8b31b4
commit
b2043286fa
17 files changed
+825
-151
No files matched your search
@@ -16,6 +16,7 @@ References:
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
@@ -40,6 +41,11 @@ class SSRFBlockedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ResolutionError(ValueError):
|
||||
"""The host name could not be resolved (may be temporary; v2.10.1)"""
|
||||
pass
|
||||
|
||||
|
||||
class FetchTooLargeError(Exception):
|
||||
"""Raised when a response is larger than the limit"""
|
||||
pass
|
||||
@@ -132,7 +138,7 @@ def validate_url_for_fetch(url: str) -> str:
|
||||
try:
|
||||
return safe_resolve(parsed.hostname)
|
||||
except socket.gaierror as e:
|
||||
raise ValueError(f"Could not resolve {parsed.hostname}: {e}")
|
||||
raise ResolutionError(f"Could not resolve {parsed.hostname}: {e}")
|
||||
|
||||
|
||||
def _pinned_request(client: httpx.Client, method: str, url: str, headers: dict,
|
||||
@@ -158,6 +164,38 @@ def _pinned_request(client: httpx.Client, method: str, url: str, headers: dict,
|
||||
)
|
||||
|
||||
|
||||
class _Watchdog:
|
||||
"""
|
||||
Close a client when its deadline passes (v2.10.1)
|
||||
|
||||
httpx timeouts apply per read, so a server sending one byte at a time
|
||||
could hold a request for hours; closing the client ends it.
|
||||
"""
|
||||
|
||||
def __init__(self, client: httpx.Client, seconds: float):
|
||||
self.fired = False
|
||||
|
||||
def fire():
|
||||
self.fired = True
|
||||
try:
|
||||
client.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._timer = threading.Timer(max(seconds, 0.01), fire)
|
||||
self._timer.daemon = True
|
||||
|
||||
def __enter__(self):
|
||||
self._timer.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
self._timer.cancel()
|
||||
if self.fired and exc_type is not None and not isinstance(exc, httpx.TimeoutException):
|
||||
raise httpx.TimeoutException("Exceeded time limit") from exc
|
||||
return False
|
||||
|
||||
|
||||
@dataclass
|
||||
class FetchResult:
|
||||
"""A fetched response, after redirects"""
|
||||
@@ -177,28 +215,34 @@ class FetchResult:
|
||||
|
||||
def safe_post(url: str, data: Optional[dict] = None, headers: Optional[dict] = None,
|
||||
timeout: float = TIMEOUT, content: Optional[bytes] = None,
|
||||
max_bytes: int = 64 * 1024) -> FetchResult:
|
||||
max_bytes: int = 4096) -> FetchResult:
|
||||
"""
|
||||
POST form data (or a raw body) to a checked, pinned address.
|
||||
|
||||
Redirects are not followed. Only the first max_bytes of the response are
|
||||
read (callers need the status and maybe an error message).
|
||||
Redirects are not followed. `timeout` bounds the whole exchange, so a
|
||||
server trickling its response can't hold the caller (v2.10.1). Only the
|
||||
first max_bytes of the response are read (callers need the status and
|
||||
maybe an error message).
|
||||
|
||||
Raises:
|
||||
SSRFBlockedError, ValueError: URL is not allowed
|
||||
httpx.HTTPError: Network errors
|
||||
"""
|
||||
kwargs = {'content': content} if content is not None else {'data': data}
|
||||
with httpx.Client(follow_redirects=False, transport=TRANSPORT, timeout=timeout) as client:
|
||||
deadline = time.monotonic() + timeout
|
||||
with httpx.Client(follow_redirects=False, transport=TRANSPORT, timeout=timeout) as client, \
|
||||
_Watchdog(client, timeout):
|
||||
request = _pinned_request(client, 'POST', url, headers or {}, **kwargs)
|
||||
response = client.send(request, stream=True)
|
||||
try:
|
||||
body = b''
|
||||
for chunk in response.iter_bytes(chunk_size=8192):
|
||||
for chunk in response.iter_bytes(chunk_size=1024):
|
||||
body += chunk
|
||||
if len(body) >= max_bytes:
|
||||
body = body[:max_bytes]
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
raise httpx.TimeoutException("Response exceeded time limit")
|
||||
return FetchResult(url=url, status_code=response.status_code, headers=response.headers,
|
||||
content=body, encoding=response.charset_encoding or 'utf-8')
|
||||
finally:
|
||||
@@ -227,7 +271,8 @@ def safe_get(url: str, headers: dict, max_bytes: int = MAX_BYTES,
|
||||
"""
|
||||
deadline = time.monotonic() + timeout
|
||||
|
||||
with httpx.Client(follow_redirects=False, transport=TRANSPORT) as client:
|
||||
with httpx.Client(follow_redirects=False, transport=TRANSPORT) as client, \
|
||||
_Watchdog(client, timeout):
|
||||
for _ in range(max_redirects + 1):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
|
||||
Reference in new issue
Block a user