aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/views/endpoint.py
diff options
context:
space:
mode:
Diffstat (limited to 'webmentions_ssg/views/endpoint.py')
-rw-r--r--webmentions_ssg/views/endpoint.py150
1 files changed, 150 insertions, 0 deletions
diff --git a/webmentions_ssg/views/endpoint.py b/webmentions_ssg/views/endpoint.py
new file mode 100644
index 0000000..1c2fe13
--- /dev/null
+++ b/webmentions_ssg/views/endpoint.py
@@ -0,0 +1,150 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Public Webmention endpoint and verification status view."""
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from typing import Any, cast
+
+import sqlalchemy as sa
+import sqlalchemy.exc as sa_exc
+from flask import Response, abort, current_app, render_template, url_for
+from flask.typing import ResponseReturnValue
+from sqlalchemy.engine import CursorResult
+
+from .. import forms
+from ..extensions import CSRF, LIMITER
+from ..extensions import DATABASE as db
+from ..models import ReceivedWebmention, received_url_digest
+from ..tasks.receiver import verify_webmention
+from . import root_page
+
+
+def submit_received(source: str, target: str) -> tuple[uuid.UUID, bool] | None:
+ """Upsert a submission atomically and return (identifier, enqueue flag).
+
+ ``None`` means that the URL fingerprint matches a different source/target.
+ No background task is enqueued until the transaction is committed.
+ """
+ url_digest = received_url_digest(source, target)
+ webmention = db.session.execute(
+ sa.select(ReceivedWebmention).where(ReceivedWebmention.url_digest == url_digest)
+ ).scalar_one_or_none()
+
+ # A SHA-256 collision must never cause an unrelated Webmention to be overwritten.
+ if webmention is not None and (webmention.source, webmention.target) != (
+ source,
+ target,
+ ):
+ return None
+
+ should_verify = False
+
+ if webmention is None:
+ identifier = uuid.uuid7()
+ webmention = ReceivedWebmention(uuid=identifier, source=source, target=target)
+ db.session.add(webmention)
+
+ try:
+ db.session.commit()
+ should_verify = True
+ except sa_exc.IntegrityError:
+ db.session.rollback()
+
+ # Another request may have inserted the same source/target pair
+ # after our SELECT but before our COMMIT.
+ webmention = db.session.execute(
+ sa.select(ReceivedWebmention).where(
+ ReceivedWebmention.url_digest == url_digest
+ )
+ ).scalar_one_or_none()
+ if webmention is None or (webmention.source, webmention.target) != (
+ source,
+ target,
+ ):
+ return None
+
+ else:
+ now = datetime.now(UTC)
+ cutoff = now - timedelta(
+ seconds=current_app.config["ENDPOINT_REVERIFY_COOLDOWN_SECONDS"]
+ )
+
+ # Atomic conditional update: only one concurrent request can reopen an expired verification.
+ result = cast(
+ CursorResult[Any],
+ db.session.execute(
+ sa.update(ReceivedWebmention)
+ .where(
+ ReceivedWebmention.uuid == webmention.uuid,
+ ReceivedWebmention.updated_at <= cutoff,
+ )
+ .values(ReceivedWebmention.verification_reset_values(at=now))
+ .execution_options(synchronize_session=False)
+ ),
+ )
+ should_verify = result.rowcount == 1
+ db.session.commit()
+
+ return webmention.uuid, should_verify
+
+
+@root_page.post("/endpoint")
+@LIMITER.limit(
+ lambda: current_app.config["ENDPOINT_GLOBAL_RATE_LIMIT"],
+ key_func=lambda: "all-clients",
+)
+@LIMITER.limit(lambda: current_app.config["ENDPOINT_RATE_LIMIT"])
+@CSRF.exempt
+def endpoint() -> ResponseReturnValue:
+ """
+ Receive and queue a Webmention for verification.
+
+ Existing Webmentions with the same source and target are reset for
+ reverification. Concurrent insertion of the same Webmention is handled by
+ retrieving and updating the row created by the competing request.
+
+ :return: HTTP 201 response with the Webmention status URL in the
+ ``Location`` header, or validation errors with HTTP 400.
+ """
+ form = forms.EndpointForm(meta={"csrf": False})
+
+ if not form.validate_on_submit():
+ return form.errors, 400
+
+ source = cast(str, form.source.data)
+ target = cast(str, form.target.data)
+
+ result = submit_received(source, target)
+
+ if result is None:
+ return {"error": "Webmention URL fingerprint conflict"}, 409
+
+ identifier, should_verify = result
+
+ if should_verify:
+ verify_webmention(identifier)
+
+ status_url = url_for("root.status", identifier=str(identifier), _external=True)
+
+ return Response(status=201, headers={"Location": status_url})
+
+
+@root_page.route("/status/<uuid:identifier>")
+def status(identifier: uuid.UUID) -> ResponseReturnValue:
+ """
+ Display the verification status of a received Webmention.
+
+ :param identifier: Identifier of the Webmention to display.
+ :return: Rendered Webmention status page.
+ """
+ webmention = db.session.get(ReceivedWebmention, identifier)
+
+ if webmention is None:
+ return abort(404)
+
+ return render_template(
+ "status.html", title="Webmention status", webmention=webmention
+ )