diff options
| author | Dennis Fink | 2026-10-29 19:49:44 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-10-29 19:49:44 +0100 |
| commit | 9a1e863079b64883beadaba7b283621f1b3cf70a (patch) | |
| tree | 3737edbe481460b13dad9e12eaeb3ed5208dda1b /webmentions_ssg | |
| parent | 38f5a47ed79fac6b5cdb525e50168beb67c4a0b3 (diff) | |
| download | webmentions-ssg-9a1e863079b64883beadaba7b283621f1b3cf70a.tar.gz webmentions-ssg-9a1e863079b64883beadaba7b283621f1b3cf70a.zip | |
fix(receiver): rate limit Webmention submissions
Protect the public endpoint from abusive request floods and repeated
duplicate submissions that would otherwise trigger unnecessary
verification work.
Add per-client and global limits, require shared limiter storage in
production, and only reverify existing Webmentions after a configurable
cooldown.
Diffstat (limited to 'webmentions_ssg')
| -rw-r--r-- | webmentions_ssg/__init__.py | 13 | ||||
| -rw-r--r-- | webmentions_ssg/config.py | 7 | ||||
| -rw-r--r-- | webmentions_ssg/views.py | 53 |
3 files changed, 56 insertions, 17 deletions
diff --git a/webmentions_ssg/__init__.py b/webmentions_ssg/__init__.py index 61add02..c4ad4f6 100644 --- a/webmentions_ssg/__init__.py +++ b/webmentions_ssg/__init__.py @@ -12,6 +12,8 @@ from pathlib import Path import coloredlogs from flask import Flask from flask_bootstrap import Bootstrap5 +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address from flask_mail import Mail from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy @@ -37,6 +39,7 @@ DATABASE = SQLAlchemy(model_class=Base) MIGRATE = Migrate() HUEY = Huey() MAIL = Mail() +LIMITER = Limiter(key_func=get_remote_address) def create_app(config_class: type[DefaultConfig] | None = None) -> Flask: @@ -73,6 +76,15 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask: app.config.from_prefixed_env(prefix="FLASK") app.config.from_prefixed_env(prefix="WEBMENTIONS_SSG") + if ( + not app.testing + and not app.debug + and app.config["RATELIMIT_STORAGE_URI"] == "memory://" + ): + raise RuntimeError( + "Configure RATELIMIT_STORAGE_URI with shared storage before running in production." + ) + default_logging_formatter = logging.Formatter(app.config["LOG_FORMAT"]) log_file_handler = logging.handlers.RotatingFileHandler( @@ -110,6 +122,7 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask: command="migrate", ) CSRF.init_app(app) + LIMITER.init_app(app) MAIL.init_app(app) from .auth import AUTH diff --git a/webmentions_ssg/config.py b/webmentions_ssg/config.py index 6cadbab..aea201b 100644 --- a/webmentions_ssg/config.py +++ b/webmentions_ssg/config.py @@ -34,6 +34,13 @@ class DefaultConfig: MAIL_PASSWORD = None MAIL_DEFAULT_SENDER = None + RATELIMIT_STORAGE_URI = "memory://" + RATELIMIT_HEADERS_ENABLED = True + + ENDPOINT_RATE_LIMIT = "10/minute;100/hour" + ENDPOINT_GLOBAL_RATE_LIMIT = "1000/hour" + ENDPOINT_REVERIFY_COOLDOWN_SECONDS = 600 + class DevelopmentConfig(DefaultConfig): DEBUG = True diff --git a/webmentions_ssg/views.py b/webmentions_ssg/views.py index cef81fc..bb1f38a 100644 --- a/webmentions_ssg/views.py +++ b/webmentions_ssg/views.py @@ -5,7 +5,8 @@ """Provide routes for authentication and Webmention administration.""" import uuid -from typing import cast +from datetime import UTC, datetime, timedelta +from typing import Any, cast import sqlalchemy as sa import sqlalchemy.exc as sa_exc @@ -13,6 +14,7 @@ from flask import ( Blueprint, Response, abort, + current_app, flash, redirect, render_template, @@ -21,9 +23,10 @@ from flask import ( ) from flask.typing import ResponseReturnValue from flask_login import current_user, login_required, login_user, logout_user +from sqlalchemy.engine import CursorResult from sqlalchemy.orm import selectinload -from . import CSRF, forms +from . import CSRF, LIMITER, forms from . import DATABASE as db from .models import ReceivedWebmention, SentWebmention, Source, User from .tasks.receiver import verify_webmention @@ -292,6 +295,11 @@ def resend_sent_webmention( @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: """ @@ -318,8 +326,8 @@ def endpoint() -> ResponseReturnValue: ) ).scalar_one_or_none() - # Only notify about new webmentions, not resubmissions of existing ones. - send_notification = webmention is None + should_verify = False + send_notification = False if webmention is None: identifier = uuid.uuid7() @@ -330,9 +338,10 @@ def endpoint() -> ResponseReturnValue: try: db.session.commit() + should_verify = True + send_notification = True except sa_exc.IntegrityError: db.session.rollback() - send_notification = False # Another request may have inserted the same source/target pair # after our SELECT but before our COMMIT. @@ -343,22 +352,32 @@ def endpoint() -> ResponseReturnValue: ) ).scalar_one() - identifier = webmention.uuid - webmention.status = "received" - webmention.failure_reason = None - - db.session.commit() - else: - identifier = webmention.uuid - - # Re-sent webmention: re-verify the existing row. - webmention.status = "received" - webmention.failure_reason = None + 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(status="received", failure_reason=None, updated_at=now) + .execution_options(synchronize_session=False) + ), + ) + should_verify = result.rowcount == 1 db.session.commit() - verify_webmention(webmention.uuid, send_notification=send_notification) + identifier = webmention.uuid + + if should_verify: + verify_webmention(identifier, send_notification=send_notification) status_url = url_for("root.status", identifier=str(identifier), _external=True) |
