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
+152
-49
@@ -97,17 +97,44 @@ def topic_for_request(response=None) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
_UNRESERVED = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
|
||||
|
||||
|
||||
def decode_unreserved(value: str) -> str:
|
||||
"""
|
||||
Decode percent-encoded unreserved characters (%66 -> f), leaving the rest
|
||||
|
||||
Spec 5.1.1: hubs MUST always decode non-reserved characters in URL
|
||||
parameters, so /%66eed.atom and /feed.atom are the same topic.
|
||||
"""
|
||||
out, i = [], 0
|
||||
while i < len(value):
|
||||
if value[i] == "%" and i + 3 <= len(value):
|
||||
try:
|
||||
char = chr(int(value[i + 1:i + 3], 16))
|
||||
except ValueError:
|
||||
char = None
|
||||
if char is not None and char in _UNRESERVED:
|
||||
out.append(char)
|
||||
i += 3
|
||||
continue
|
||||
out.append(value[i])
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def canonical_topic(url: str) -> Optional[str]:
|
||||
"""
|
||||
A subscription's hub.topic as one of this site's topics, or None
|
||||
|
||||
Tag topics must name an existing tag.
|
||||
Unreserved percent-encodings are decoded and the scheme and host are
|
||||
compared case-insensitively. Tag topics must name an existing tag.
|
||||
"""
|
||||
if not url:
|
||||
return None
|
||||
site = urlparse(site_url())
|
||||
parsed = urlparse(url.strip())
|
||||
if (parsed.scheme, parsed.netloc.lower()) != (site.scheme, site.netloc.lower()):
|
||||
parsed = urlparse(decode_unreserved(url.strip()))
|
||||
if (parsed.scheme.lower(), parsed.netloc.lower()) != (site.scheme, site.netloc.lower()):
|
||||
return None
|
||||
path = parsed.path or "/"
|
||||
if parsed.query or parsed.fragment:
|
||||
@@ -115,8 +142,9 @@ def canonical_topic(url: str) -> Optional[str]:
|
||||
if path in set(PAGE_TOPICS.values()) | set(FEED_TOPICS.values()):
|
||||
return topic_url(path)
|
||||
if path.startswith("/tag/"):
|
||||
from urllib.parse import unquote
|
||||
from starpunk.tags import get_tag_by_name, normalize_tag
|
||||
name = normalize_tag(path[len("/tag/"):])[0]
|
||||
name = normalize_tag(unquote(path[len("/tag/"):]))[0]
|
||||
if name and get_tag_by_name(name):
|
||||
return tag_topic(name)
|
||||
return None
|
||||
@@ -214,9 +242,11 @@ def note_changed(note, was_public: bool = False, old_tags: Iterable[str] = ()) -
|
||||
tags = set()
|
||||
tags |= set(old_tags)
|
||||
|
||||
topics = [topic_url(p) for p in ("/", "/feed.atom", "/feed.rss", "/feed.json")]
|
||||
# Likes appear on /likes, not on the home page or in the feeds
|
||||
if getattr(note, "like_of", None):
|
||||
topics.append(topic_url("/likes"))
|
||||
topics = [topic_url("/likes")]
|
||||
else:
|
||||
topics = [topic_url(p) for p in ("/", "/feed.atom", "/feed.rss", "/feed.json")]
|
||||
topics += [tag_topic(name) for name in sorted(tags)]
|
||||
queue_topics(db, topics)
|
||||
|
||||
@@ -249,6 +279,50 @@ def queue_topics(db, topics: Iterable[str]) -> int:
|
||||
|
||||
# --- Hub: subscription requests (spec 5.1) -------------------------------------
|
||||
|
||||
MAX_CALLBACK_LENGTH = 2048
|
||||
MAX_PENDING_INTENTS = 200
|
||||
ALLOWED_PORTS = {80, 443} # plus any port from 1024 up
|
||||
|
||||
|
||||
def _clean_callback(callback: str) -> str:
|
||||
"""
|
||||
Check a hub.callback and return it with an ASCII (IDNA) host
|
||||
|
||||
Raises:
|
||||
SubscriptionError: if it is not an acceptable callback URL
|
||||
"""
|
||||
import httpx
|
||||
|
||||
if not callback or len(callback) > MAX_CALLBACK_LENGTH:
|
||||
raise SubscriptionError(f"hub.callback must be a URL of at most {MAX_CALLBACK_LENGTH} characters")
|
||||
if any(ord(c) < 0x20 or ord(c) == 0x7f for c in callback) or " " in callback:
|
||||
raise SubscriptionError("hub.callback contains spaces or control characters")
|
||||
parsed = urlparse(callback)
|
||||
if parsed.scheme.lower() not in ("http", "https") or not parsed.hostname:
|
||||
raise SubscriptionError("hub.callback must be an absolute http(s) URL")
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
raise SubscriptionError("hub.callback has an invalid port")
|
||||
if port is not None and port not in ALLOWED_PORTS and port < 1024:
|
||||
raise SubscriptionError("hub.callback may not use that port")
|
||||
|
||||
try:
|
||||
host = parsed.hostname.encode("idna").decode("ascii")
|
||||
except UnicodeError:
|
||||
raise SubscriptionError("hub.callback has an invalid host name")
|
||||
netloc = host + (f":{port}" if port is not None else "")
|
||||
callback = parsed._replace(scheme=parsed.scheme.lower(), netloc=netloc).geturl()
|
||||
|
||||
if host.lower() == (urlparse(site_url()).hostname or "").lower():
|
||||
raise SubscriptionError("hub.callback may not be on this site")
|
||||
try:
|
||||
httpx.URL(callback)
|
||||
except Exception:
|
||||
raise SubscriptionError("hub.callback is not a valid URL")
|
||||
return callback
|
||||
|
||||
|
||||
def accept_subscription_request(form, db) -> None:
|
||||
"""
|
||||
Validate a subscription request and queue it for verification
|
||||
@@ -258,71 +332,100 @@ def accept_subscription_request(form, db) -> None:
|
||||
"""
|
||||
from starpunk.webmention_ssrf import SSRFBlockedError, validate_url_for_fetch
|
||||
|
||||
if external_hub():
|
||||
raise SubscriptionError("This site uses another hub: " + external_hub(), 400)
|
||||
|
||||
mode = (form.get("hub.mode") or "").strip()
|
||||
if mode not in ("subscribe", "unsubscribe"):
|
||||
raise SubscriptionError("hub.mode must be subscribe or unsubscribe")
|
||||
if mode == "subscribe" and external_hub():
|
||||
# Unsubscribes are still taken, so old subscribers can leave
|
||||
raise SubscriptionError("This site uses another hub: " + external_hub(), 400)
|
||||
|
||||
callback = (form.get("hub.callback") or "").strip()
|
||||
parsed = urlparse(callback)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
||||
raise SubscriptionError("hub.callback must be an absolute http(s) URL")
|
||||
callback = _clean_callback((form.get("hub.callback") or "").strip())
|
||||
try:
|
||||
validate_url_for_fetch(callback)
|
||||
callback_ip = validate_url_for_fetch(callback)
|
||||
except (SSRFBlockedError, ValueError) as e:
|
||||
raise SubscriptionError(f"hub.callback is not reachable: {e}")
|
||||
|
||||
topic = canonical_topic(form.get("hub.topic") or "")
|
||||
requested_topic = (form.get("hub.topic") or "").strip()
|
||||
topic = canonical_topic(requested_topic)
|
||||
if not topic:
|
||||
raise SubscriptionError("hub.topic is not a topic of this site; use the rel=self URL")
|
||||
|
||||
secret = form.get("hub.secret")
|
||||
if mode == "unsubscribe":
|
||||
secret = None # MUST be ignored for unsubscriptions
|
||||
if secret is not None and len(secret.encode("utf-8")) >= MAX_SECRET_BYTES:
|
||||
raise SubscriptionError("hub.secret must be less than 200 bytes")
|
||||
|
||||
lease = LEASE_DEFAULT
|
||||
if form.get("hub.lease_seconds"):
|
||||
try:
|
||||
lease = int(form["hub.lease_seconds"])
|
||||
except ValueError:
|
||||
raise SubscriptionError("hub.lease_seconds must be a number")
|
||||
lease = max(LEASE_MIN, min(lease, LEASE_MAX))
|
||||
|
||||
secret, lease = None, None
|
||||
if mode == "subscribe":
|
||||
existing = db.execute(
|
||||
"SELECT 1 FROM websub_subscriptions WHERE topic = ? AND callback = ?", (topic, callback)
|
||||
).fetchone()
|
||||
if not existing:
|
||||
total = db.execute("SELECT COUNT(*) FROM websub_subscriptions").fetchone()[0]
|
||||
if total >= current_app.config.get("WEBSUB_MAX_SUBSCRIPTIONS", 1000):
|
||||
raise SubscriptionError("This hub has reached its subscription limit", 429)
|
||||
host = parsed.hostname.lower()
|
||||
per_host = sum(
|
||||
1 for (cb,) in db.execute("SELECT callback FROM websub_subscriptions")
|
||||
if (urlparse(cb).hostname or "").lower() == host
|
||||
)
|
||||
if per_host >= current_app.config.get("WEBSUB_MAX_PER_HOST", 25):
|
||||
raise SubscriptionError(f"Too many subscriptions for {host}", 429)
|
||||
# hub.secret and hub.lease_seconds MUST be ignored for unsubscriptions
|
||||
secret = form.get("hub.secret")
|
||||
if secret is not None:
|
||||
if secret == "":
|
||||
raise SubscriptionError("hub.secret may not be empty")
|
||||
if len(secret.encode("utf-8")) >= MAX_SECRET_BYTES:
|
||||
raise SubscriptionError("hub.secret must be less than 200 bytes")
|
||||
lease = LEASE_DEFAULT
|
||||
if form.get("hub.lease_seconds"):
|
||||
try:
|
||||
lease = int(form["hub.lease_seconds"])
|
||||
except ValueError:
|
||||
raise SubscriptionError("hub.lease_seconds must be a number")
|
||||
lease = max(LEASE_MIN, min(lease, LEASE_MAX))
|
||||
_check_limits(db, topic, callback, callback_ip)
|
||||
|
||||
# The latest request for a topic and callback replaces any pending one
|
||||
# Each request gets its own id; the latest replaces any pending one
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO websub_intents (topic, callback, mode, secret, lease_seconds)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
INSERT INTO websub_intents
|
||||
(topic, callback, mode, secret, lease_seconds, request_id, requested_topic, callback_ip)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(topic, callback) DO UPDATE SET
|
||||
mode = excluded.mode, secret = excluded.secret,
|
||||
lease_seconds = excluded.lease_seconds, attempts = 0,
|
||||
next_attempt_at = CURRENT_TIMESTAMP, created_at = CURRENT_TIMESTAMP
|
||||
lease_seconds = excluded.lease_seconds, request_id = excluded.request_id,
|
||||
requested_topic = excluded.requested_topic, callback_ip = excluded.callback_ip,
|
||||
attempts = 0, next_attempt_at = CURRENT_TIMESTAMP, created_at = CURRENT_TIMESTAMP
|
||||
""",
|
||||
(topic, callback, mode, secret, lease),
|
||||
(topic, callback, mode, secret, lease, secrets.token_hex(16), requested_topic, callback_ip),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _check_limits(db, topic: str, callback: str, callback_ip: str) -> None:
|
||||
"""
|
||||
Subscription limits, counting pending requests too (ADR-071 4)
|
||||
|
||||
Per callback address rather than host name, so many subdomains on one
|
||||
server share a limit. Renewing an existing subscription is always fine.
|
||||
"""
|
||||
if db.execute("SELECT 1 FROM websub_subscriptions WHERE topic = ? AND callback = ?",
|
||||
(topic, callback)).fetchone():
|
||||
return
|
||||
|
||||
pending = db.execute("SELECT COUNT(*) FROM websub_intents").fetchone()[0]
|
||||
if pending >= MAX_PENDING_INTENTS:
|
||||
raise SubscriptionError("Too many subscription requests waiting; try again later", 429)
|
||||
|
||||
total = db.execute(
|
||||
"""
|
||||
SELECT COUNT(*) FROM (
|
||||
SELECT topic, callback FROM websub_subscriptions
|
||||
UNION
|
||||
SELECT topic, callback FROM websub_intents WHERE mode = 'subscribe'
|
||||
)
|
||||
"""
|
||||
).fetchone()[0]
|
||||
if total >= current_app.config.get("WEBSUB_MAX_SUBSCRIPTIONS", 1000):
|
||||
raise SubscriptionError("This hub has reached its subscription limit", 429)
|
||||
|
||||
per_address = db.execute(
|
||||
"""
|
||||
SELECT COUNT(*) FROM (
|
||||
SELECT topic, callback FROM websub_subscriptions WHERE callback_ip = ?
|
||||
UNION
|
||||
SELECT topic, callback FROM websub_intents WHERE mode = 'subscribe' AND callback_ip = ?
|
||||
)
|
||||
""",
|
||||
(callback_ip, callback_ip),
|
||||
).fetchone()[0]
|
||||
if per_address >= current_app.config.get("WEBSUB_MAX_PER_HOST", 25):
|
||||
raise SubscriptionError("Too many subscriptions for that callback's server", 429)
|
||||
|
||||
|
||||
def stats(db) -> dict:
|
||||
"""Active subscribers per topic and deliveries being retried (admin)"""
|
||||
by_topic = db.execute(
|
||||
|
||||
Reference in new issue
Block a user