fix: Webmention processing works end to end (v2.6.9)

- Normalise mf2 author values: u-photo with alt text is a dict in mf2py and
  broke the database update for most real senders
- Pass str(response.url) to urljoin during endpoint discovery; the TypeError
  marked every target as having no endpoint. Retry on discovery errors
- Hold a cross-process flock so only one gunicorn process runs the worker
- Keep author URL/photo only if http(s) (XSS via javascript: URLs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
PhilandClaude Opus 5.5 committed 2026-11-03 07:53:19 -07:00
1 parent 3c1e109358
commit 106495d114
6 files changed
+184 -18

No files matched your search

+2 -2
View File
@@ -459,5 +459,5 @@ def create_app(config=None):
# Package version (Semantic Versioning 2.0.0)
# See docs/standards/versioning-strategy.md for details
__version__ = "2.6.8"
__version_info__ = (2, 6, 8)
__version__ = "2.6.9"
__version_info__ = (2, 6, 9)
+32 -7
View File
@@ -182,6 +182,28 @@ def detect_mention_type(parsed_mf2: Dict, target_url: str) -> str:
return 'mention'
def _first_str(props: Dict, name: str) -> Optional[str]:
"""
First value of an mf2 property as a string
mf2py gives u-photo with alt text as {'value': url, 'alt': ...} and nested
microformats as dicts with a 'value'; reduce those to the plain value.
"""
values = props.get(name) or [None]
value = values[0]
if isinstance(value, dict):
value = value.get('value')
return value if isinstance(value, str) and value else None
def _is_http_url(value: Optional[str]) -> bool:
"""True if value is an absolute http or https URL"""
if not value:
return False
parsed = urlparse(value.strip())
return parsed.scheme.lower() in ('http', 'https') and bool(parsed.netloc)
def extract_author(parsed_mf2: Dict, source_url: str) -> Dict[str, Optional[str]]:
"""
Extract author information from h-card.
@@ -212,26 +234,29 @@ def extract_author(parsed_mf2: Dict, source_url: str) -> Dict[str, Optional[str]
if isinstance(author_data, dict):
# h-card object
props = author_data.get('properties', {})
author_name = props.get('name', [None])[0]
author_url = props.get('url', [None])[0]
author_photo = props.get('photo', [None])[0]
author_name = _first_str(props, 'name')
author_url = _first_str(props, 'url')
author_photo = _first_str(props, 'photo')
# If no author in h-entry, find representative h-card
if not author_name:
for item in parsed_mf2.get('items', []):
if 'h-card' in item.get('type', []):
props = item.get('properties', {})
author_name = props.get('name', [None])[0]
author_url = props.get('url', [None])[0]
author_photo = props.get('photo', [None])[0]
author_name = _first_str(props, 'name')
author_url = _first_str(props, 'url')
author_photo = _first_str(props, 'photo')
break
# Fallback to hostname if no author found
if not author_name:
author_name = urlparse(source_url).netloc
if not author_url:
# Only http(s) URLs are rendered as links (blocks javascript: and data:)
if not _is_http_url(author_url):
author_url = source_url
if not _is_http_url(author_photo):
author_photo = None
return {
'author_name': author_name,
+44 -7
View File
@@ -12,6 +12,7 @@ References:
- ADR-063: Webmention Implementation
"""
import fcntl
import logging
import threading
import time
@@ -76,6 +77,7 @@ class WebmentionWorker(threading.Thread):
self.auto_approve = auto_approve
self._stop_event = threading.Event()
self._last_processed = None
self._lock_file = None
# Phase 3: Discovery cache (worker instance variable)
# Per architect's answer to Q4
@@ -94,11 +96,14 @@ class WebmentionWorker(threading.Thread):
try:
logger.info("Webmention worker started")
# Cleanup orphaned items from previous crashes
self._cleanup_orphaned_items()
# Main processing loop
while not self._stop_event.is_set():
# Every gunicorn process starts a worker; only the one holding
# the lock processes queues, so nothing is sent twice
if not self._acquire_lock():
self._stop_event.wait(self.poll_interval)
continue
try:
processed = 0
@@ -124,8 +129,40 @@ class WebmentionWorker(threading.Thread):
except Exception as e:
logger.error(f"Webmention worker thread failed: {e}", exc_info=True)
finally:
self._release_lock()
logger.info("Webmention worker stopped")
def _acquire_lock(self) -> bool:
"""
Take the cross-process worker lock (non-blocking)
On first acquisition, also reset items left mid-send by a previous
holder. The OS releases the lock if this process dies.
Returns:
True if this worker holds the lock
"""
if self._lock_file:
return True
lock_file = open(Path(self.db_path).parent / "webmention-worker.lock", "w")
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
lock_file.close()
return False
self._lock_file = lock_file
logger.info("Webmention worker holds the queue lock")
self._cleanup_orphaned_items()
return True
def _release_lock(self):
"""Release the cross-process worker lock if held"""
if self._lock_file:
self._lock_file.close()
self._lock_file = None
def _cleanup_orphaned_items(self):
"""
Clean up orphaned 'sending' status items on startup
@@ -510,7 +547,7 @@ class WebmentionWorker(threading.Thread):
# 1. Check Link header
link_header = response.headers.get('Link', '')
if link_header:
endpoint = self._parse_link_header(link_header, response.url)
endpoint = self._parse_link_header(link_header, str(response.url))
if endpoint:
self._cache_endpoint(target_url, endpoint, hours=1)
return endpoint
@@ -518,7 +555,7 @@ class WebmentionWorker(threading.Thread):
# 2. Parse HTML for <link> and <a> elements
content_type = response.headers.get('Content-Type', '')
if 'html' in content_type.lower():
endpoint = self._parse_html_for_endpoint(response.text, response.url)
endpoint = self._parse_html_for_endpoint(response.text, str(response.url))
if endpoint:
self._cache_endpoint(target_url, endpoint, hours=1)
return endpoint
@@ -529,9 +566,9 @@ class WebmentionWorker(threading.Thread):
return None
except Exception as e:
# Don't cache; the caller schedules a retry
logger.warning(f"Failed to discover endpoint for {target_url}: {e}")
# Don't cache on error - allow retry
return None
raise
def _parse_link_header(self, link_header: str, base_url: str) -> Optional[str]:
"""