aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/tasks/receiver.py
blob: acd66a1948a5bd7c2471c28989af8c285142f9c1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Fetch and verify incoming Webmentions against their source pages."""

import uuid
from datetime import UTC, datetime, timedelta
from urllib.parse import urljoin

import httpx
import rfc3987
import sqlalchemy as sa
from bs4 import BeautifulSoup
from flask import current_app

from .. import APP_NAME, VERSION
from .. import DATABASE as db
from .. import HUEY as huey
from ..models import ReceivedWebmention
from ..public_transport import PublicHTTPTransport
from ..url_security import AddressResolutionError, UnsafeAddressError


RECOVERY_EXHAUSTED_REASON = "Verification recovery limit reached"


class VerificationError(Exception):
    """The source permanently failed ReceivedWebmention verification."""


class SourceGoneError(VerificationError):
    """The source explicitly reports that it has been removed."""


class TemporaryFetchError(Exception):
    """Fetching the source may succeed when retried later."""


IRI_PATTERN = rfc3987.get_compiled_pattern("IRI")
TRAILING_IRI_PUNCTUATION = ".,;:!?"


HTML_URL_ATTRIBUTES = {
    "href": {"a", "area", "link"},
    "src": {
        "audio",
        "embed",
        "iframe",
        "img",
        'input[type="image" i]',
        "script",
        "audio source",
        "video source",
        "track",
        "video",
    },
    "cite": {"blockquote", "del", "ins", "q"},
}


def html_mentions_target(body: bytes, source_url: str, target_url: str) -> bool:
    """
    Check whether an HTML document mentions the target URL.

    URL references are resolved against the document's ``base`` element when
    present, or against the source URL otherwise.

    :param body: HTML document body.
    :param source_url: URL from which the document was retrieved.
    :param target_url: Exact URL to look for.
    :return: Whether a supported HTML URL attribute references the target URL.
    """

    document = BeautifulSoup(body, "html.parser")
    base_url = source_url

    if (base_element := document.select_one("base[href]")) is not None and isinstance(
        base_href := base_element.get("href"), str
    ):
        base_url = urljoin(source_url, base_href.strip())

    for attribute, selectors in HTML_URL_ATTRIBUTES.items():
        selector = ", ".join(
            [f"{selector_string}[{attribute}]" for selector_string in selectors]
        )

        for element in document.select(selector):
            if not isinstance(reference := element.get(attribute), str):
                continue

            if urljoin(base_url, reference.strip()) == target_url:
                return True

    return False


def text_mentions_target(body: str, target_url: str) -> bool:
    """
    Check whether plain text contains the target IRI, ignoring trailing prose
    punctuation but not extra URL path or query characters.

    :param body: Plain-text document body.
    :param target_url: Exact IRI to look for.
    :return: Whether the target IRI occurs in the document.
    """
    for match in IRI_PATTERN.finditer(body):
        candidate = match.group()

        # A URL in prose can be followed by punctuation that the IRI pattern
        # consumes as part of its match. Only remove trailing punctuation,
        # leaving longer URLs (e.g. ``target/more``) unmatched.
        if not candidate.startswith(target_url):
            continue

        while candidate != target_url:
            if candidate[-1] in TRAILING_IRI_PUNCTUATION:
                candidate = candidate[:-1]
            elif candidate[-1] == ")" and candidate.count(")") > candidate.count("("):
                # Keep balanced parentheses that belong to the URL itself.
                candidate = candidate[:-1]
            else:
                break

        if candidate == target_url:
            return True

    return False


def fetch_source(source_url: str) -> tuple[httpx.Response, bytes]:
    """
    Fetch a webmention source document.

    The request follows redirects while enforcing the configured timeout,
    redirect limit, and maximum response size.

    :param source_url: URL of the source document.
    :return: HTTP response and response body.
    :raises SourceGoneError: If the source returns HTTP 410.
    :raises TemporaryFetchError: If the source returns a temporary HTTP error.
    :raises VerificationError: If the source returns another unsuccessful HTTP
        status or exceeds the configured maximum response size.
    """

    try:
        return _fetch_source(source_url)
    except UnsafeAddressError as exc:
        raise VerificationError("Source resolves to a non-public address") from exc
    except AddressResolutionError as exc:
        raise TemporaryFetchError("Source hostname could not be resolved") from exc


def _fetch_source(source_url: str) -> tuple[httpx.Response, bytes]:
    with (
        httpx.Client(
            headers={
                "Accept": "text/html, application/xhtml+xml;q=0.9, text/plain;q=0.8",
                "User-Agent": f"{APP_NAME}/{VERSION} ReceivedWebmention",
            },
            timeout=httpx.Timeout(current_app.config.get("REQUEST_TIMEOUT", 5.0)),
            follow_redirects=True,
            max_redirects=current_app.config.get("MAX_REDIRECTS", 20),
            trust_env=False,
            transport=PublicHTTPTransport(
                current_app.config.get("REQUEST_TOTAL_TIMEOUT", 30.0)
            ),
        ) as client,
        client.stream("GET", source_url) as response,
    ):
        match response.status_code:
            case 200:
                pass
            case 410:
                raise SourceGoneError("Source returned HTTP 410")
            case status:
                if status in {408, 425, 429} or 500 <= status <= 599:
                    raise TemporaryFetchError(f"Source returned HTTP {status}")
                else:
                    raise VerificationError(f"Source returned HTTP {status}")

        max_source_bytes = current_app.config.get("MAX_SOURCE_BYTES", 1_000_000)

        if (content_length := response.headers.get("Content-Length")) is not None:
            try:
                if int(content_length) > max_source_bytes:
                    raise VerificationError("Source document is too large")
            except ValueError:
                pass

        body = bytearray()
        for chunk in response.iter_bytes(chunk_size=64 * 1024):
            body.extend(chunk)

            if len(body) > max_source_bytes:
                raise VerificationError("Source document is too large")

        return response, bytes(body)


def source_mentions_target(source_url: str, target_url: str) -> bool:
    """
    Fetch a source and check whether it mentions the target URL.

    HTML and XHTML sources are inspected for supported URL attributes, while
    plain-text sources are searched for the exact target IRI.

    :param source_url: URL of the source document.
    :param target_url: Exact target URL to look for.
    :return: Whether the source mentions the target URL.
    :raises VerificationError: If the source has an unsupported or missing
        content type.
    :raises SourceGoneError: If the source explicitly reports that it is gone.
    :raises TemporaryFetchError: If fetching the source fails temporarily.
    """

    response, body = fetch_source(source_url)

    media_type = (
        response.headers.get("Content-Type", "").partition(";")[0].strip().lower()
    )

    match media_type:
        case "text/html" | "application/xhtml+xml":
            return html_mentions_target(body, str(response.url), target_url)
        case "text/plain":
            try:
                decoded_body = body.decode(
                    response.encoding or "utf-8", errors="replace"
                )
            except LookupError:
                decoded_body = body.decode("utf-8", errors="replace")
            return text_mentions_target(decoded_body, target_url)
        case _:
            raise VerificationError(
                f"Unsupported source content type: {media_type or 'missing'}"
            )


@huey.task(retries=2, retry_delay=50)
def verify_webmention(webmention_uuid: uuid.UUID) -> None:
    """
    Verify a received webmention and persist the result.

    The transition into ``verifying`` is an atomic claim. Its ``updated_at``
    timestamp acts as a lease version: if a reaper has reclaimed the row while
    the fetch was in progress, the old worker cannot overwrite the new result.
    Temporary fetch failures are persisted and re-raised for Huey's retries.

    :param webmention_uuid: Identifier of the received webmention to verify.
    :raises TemporaryFetchError: If fetching the source fails temporarily.
    :raises httpx.RequestError: If an HTTP request error occurs while fetching
        the source.
    """
    webmention = db.session.get(ReceivedWebmention, webmention_uuid)

    if webmention is None:
        current_app.logger.warning(
            "Cannot verify unknown ReceivedWebmention %s", webmention_uuid
        )
        return

    # Failed tasks may be retried by Huey. Completed and already-running tasks
    # should not start another concurrent verification.
    if webmention.status not in {"received", "failed"}:
        return
    # A reaper-exhausted row must not be revived by a late Huey retry.
    if (
        webmention.status == "failed"
        and webmention.failure_reason == RECOVERY_EXHAUSTED_REASON
    ):
        return

    previous_status = webmention.status
    previous_updated_at = webmention.updated_at
    source, target = webmention.source, webmention.target
    started_at = datetime.now(UTC)

    claimed = db.session.execute(
        sa.update(ReceivedWebmention)
        .where(
            ReceivedWebmention.uuid == webmention_uuid,
            ReceivedWebmention.status == previous_status,
            ReceivedWebmention.updated_at == previous_updated_at,
        )
        .values(status="verifying", failure_reason=None, updated_at=started_at)
    )
    if claimed.rowcount != 1:
        db.session.rollback()
        return
    db.session.commit()

    def finish(status: str, failure_reason: str | None) -> None:
        # A timeout or a newer verification may have superseded this attempt.
        # Do not let a late worker overwrite its state.
        db.session.execute(
            sa.update(ReceivedWebmention)
            .where(
                ReceivedWebmention.uuid == webmention_uuid,
                ReceivedWebmention.status == "verifying",
                ReceivedWebmention.updated_at == started_at,
            )
            .values(
                status=status,
                failure_reason=failure_reason,
                updated_at=datetime.now(UTC),
            )
        )
        db.session.commit()

    try:
        mentions_target = source_mentions_target(source, target)
    except SourceGoneError as exc:
        finish("deleted", str(exc))
    except VerificationError as exc:
        finish("failed", str(exc))
    except (TemporaryFetchError, httpx.RequestError) as exc:
        finish("failed", str(exc) or "Source could not be fetched")
        raise
    except Exception as exc:
        # InvalidURL is not a RequestError; other unexpected source errors must
        # also leave the row in a terminal state, without an endless retry loop.
        current_app.logger.exception(
            "Unexpected error verifying ReceivedWebmention %s", webmention_uuid
        )
        finish("failed", str(exc) or type(exc).__name__)
    else:
        if mentions_target:
            finish("verified", None)
        else:
            finish("deleted", "Source does not mention target")


def recover_stale_webmentions() -> int:
    """
    Requeue verification attempts that were abandoned or lost from the queue.

    Recover both stale ``verifying`` rows (workers that died) and stale
    ``received`` rows (tasks that were never enqueued or were lost). Conditional
    updates prevent overlapping reapers from enqueueing the same row. Each
    reclaimed row is committed *before* enqueueing, so the worker can claim it.
    A crash between commit and enqueue is recovered on a later sweep.
    Persist a recovery count so repeatedly lost or crashing tasks eventually
    terminate rather than being requeued forever.

    :return: Number of webmentions requeued.
    """
    now = datetime.now(UTC)
    cutoff = now - timedelta(seconds=current_app.config["VERIFICATION_TIMEOUT_SECONDS"])
    stale = db.session.execute(
        sa.select(
            ReceivedWebmention.uuid,
            ReceivedWebmention.status,
            ReceivedWebmention.updated_at,
            ReceivedWebmention.recovery_attempts,
        ).where(
            ReceivedWebmention.status.in_(("verifying", "received")),
            ReceivedWebmention.updated_at <= cutoff,
        )
    ).all()

    recovered = 0
    exhausted = 0
    max_recoveries = current_app.config["VERIFICATION_MAX_RECOVERIES"]
    for identifier, status, updated_at, recovery_attempts in stale:
        at_limit = recovery_attempts >= max_recoveries
        changed = db.session.execute(
            sa.update(ReceivedWebmention)
            .where(
                ReceivedWebmention.uuid == identifier,
                ReceivedWebmention.status == status,
                ReceivedWebmention.updated_at == updated_at,
                ReceivedWebmention.recovery_attempts == recovery_attempts,
            )
            .values(
                status="failed" if at_limit else "received",
                failure_reason=RECOVERY_EXHAUSTED_REASON if at_limit else None,
                updated_at=now,
                recovery_attempts=(
                    recovery_attempts if at_limit else recovery_attempts + 1
                ),
            )
        )
        if changed.rowcount != 1:
            db.session.rollback()
            continue

        db.session.commit()
        if at_limit:
            exhausted += 1
            continue
        verify_webmention(identifier)
        recovered += 1

    if exhausted:
        current_app.logger.warning(
            "Failed %d stale webmentions after maximum verification recoveries",
            exhausted,
        )

    if recovered:
        current_app.logger.warning(
            "Requeued %d stale received webmention verifications", recovered
        )

    return recovered