From 4bd1d9e348918b2e55db47a1ac3489d035cf55e2 Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Thu, 12 Nov 2026 19:57:08 +0100 Subject: refactor(core): split modules by responsibility Break up monolithic views, task helpers, networking, CLI, and application extension setup so each module owns a focused concern. Reorganize the test suite around the new boundaries while preserving existing Webmention behavior and coverage. --- webmentions_ssg/forms/__init__.py | 78 -------------- webmentions_ssg/forms/validators.py | 208 ------------------------------------ 2 files changed, 286 deletions(-) delete mode 100644 webmentions_ssg/forms/__init__.py delete mode 100644 webmentions_ssg/forms/validators.py (limited to 'webmentions_ssg/forms') diff --git a/webmentions_ssg/forms/__init__.py b/webmentions_ssg/forms/__init__.py deleted file mode 100644 index 589cbd9..0000000 --- a/webmentions_ssg/forms/__init__.py +++ /dev/null @@ -1,78 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Dennis Fink -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Define forms for login, Webmention submission, and administration.""" - -import re - -from flask_wtf import FlaskForm -from wtforms import PasswordField, StringField, SubmitField -from wtforms.validators import URL, InputRequired, Regexp - -from .validators import ( - AllowedHostname, - HTTPXURL, - NotEqualTo, - PublicIPLiteral, - URLMaxBytes, -) - - -class LoginForm(FlaskForm): - """ - Form for authenticating a user. - """ - - username = StringField("Username", validators=[InputRequired()]) - password = PasswordField("Password", validators=[InputRequired()]) - submit = SubmitField("Sign In") - - -class EndpointForm(FlaskForm): - """ - Form for receiving a Webmention. - - The source must be a public HTTP or HTTPS URL distinct from the target. - The target must be an HTTP or HTTPS URL using an allowed hostname. - """ - - source = StringField( - "source", - validators=[ - InputRequired(), - URLMaxBytes(), - HTTPXURL(), - URL(), - Regexp( - "^https?://.*", - flags=re.IGNORECASE, - message="source must begin with http or https", - ), - NotEqualTo("target"), - PublicIPLiteral(), - ], - ) - target = StringField( - "target", - validators=[ - InputRequired(), - URLMaxBytes(), - HTTPXURL(), - URL(), - Regexp( - "^https?://.*", - flags=re.IGNORECASE, - message="target must begin with http or https", - ), - AllowedHostname(), - ], - ) - - -class AdminActionForm(FlaskForm): - """ - Form for confirming an administrative action. - """ - - submit = SubmitField("Confirm") diff --git a/webmentions_ssg/forms/validators.py b/webmentions_ssg/forms/validators.py deleted file mode 100644 index 384c7a1..0000000 --- a/webmentions_ssg/forms/validators.py +++ /dev/null @@ -1,208 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Dennis Fink -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Provide validators for URL safety and form field constraints.""" - -import ipaddress -import unicodedata -from urllib.parse import urlsplit - -import httpx -from flask import current_app -from wtforms import Field, ValidationError -from wtforms.validators import StopValidation -from wtforms.form import BaseForm - -from ..url_security import AddressResolutionError, is_public_address, is_public_url - - -class URLMaxBytes: - """Check the UTF-8 byte length of a submitted URL using the current config.""" - - def __init__( - self, config_key: str = "MAX_WEBMENTION_URL_BYTES", message: str | None = None - ) -> None: - self.config_key = config_key - self.message = message - - def __call__(self, form: BaseForm, field: Field) -> None: - if field.data is None: - return - - max_bytes = current_app.config[self.config_key] - - try: - length = len(field.data.encode("utf-8")) - except UnicodeEncodeError as exc: - raise ValidationError(field.gettext("URL must be valid UTF-8.")) from exc - - if length > max_bytes: - raise ValidationError( - self.message or field.gettext(f"URL must not exceed {max_bytes} bytes.") - ) - - -class HTTPXURL: - """Reject URLs that cannot be fetched by httpx or contain whitespace/controls. - - httpx automatically percent-encodes some whitespace. Reject it instead of - silently changing the submitted URL (which may be used in exact URL matches). - """ - - def __call__(self, form: BaseForm, field: Field) -> None: - value = field.data - if not isinstance(value, str): - raise StopValidation(field.gettext("Invalid URL.")) - - if any( - character.isspace() or unicodedata.category(character) == "Cc" - for character in value - ): - raise StopValidation(field.gettext("Invalid URL.")) - - try: - parsed = httpx.URL(value) - except (httpx.InvalidURL, ValueError, UnicodeError) as exc: - raise StopValidation(field.gettext("Invalid URL.")) from exc - - if not parsed.host: - raise StopValidation(field.gettext("Invalid URL.")) - - -class NotEqualTo: - """ - Validate that a field does not equal another field. - - :param fieldname: Name of the field to compare against. - :param message: Optional validation error message. - """ - - def __init__(self, fieldname: str, message: str | None = None) -> None: - """ - Initialize the validator. - - :param fieldname: Name of the field to compare against. - :param message: Optional validation error message. - """ - self.fieldname = fieldname - self.message = message - - def __call__(self, form: BaseForm, field: Field) -> None: - """ - Validate that two fields do not contain equal values. - - :param form: Form containing the fields to compare. - :param field: Field being validated. - :raises ValidationError: If the comparison field does not exist or both - fields contain equal values. - """ - try: - other = form[self.fieldname] - except KeyError as exc: - raise ValidationError( - field.gettext("Invalid field name '%s'.") % self.fieldname - ) from exc - - if field.data != other.data: - return - - d = { - "other_label": hasattr(other, "label") - and other.label.text - or self.fieldname, - "other_name": self.fieldname, - } - message = self.message or field.gettext( - "Field must not be equal to %(other_name)s." - ) - raise ValidationError(message % d) - - -class AllowedHostname: - """ - Validate that a URL uses an allowed hostname. - - :param message: Optional validation error message. - """ - - def __init__(self, message: str | None = None) -> None: - """ - Initialize the validator. - - :param message: Optional validation error message. - """ - self.message = message - - def __call__(self, form: BaseForm, field: Field) -> None: - """ - Validate that a URL uses an allowed hostname. - - :param form: Form containing the field. - :param field: Field containing the URL to validate. - :raises ValidationError: If the URL hostname is not configured as allowed. - """ - try: - hostname = urlsplit(field.data).hostname - except ValueError, TypeError: - hostname = None - if hostname is not None and hostname in current_app.config["ALLOWED_HOSTNAMES"]: - return - raise ValidationError(self.message or field.gettext("Invalid input.")) - - -class PublicURL: - """ - Validate that a URL resolves exclusively to public IP addresses. - - :param message: Optional validation error message. - """ - - def __init__(self, message: str | None = None) -> None: - """ - Initialize the validator. - - :param message: Optional validation error message. - """ - self.message = message - - def __call__(self, form: BaseForm, field: Field) -> None: - """ - Validate that a URL resolves exclusively to public IP addresses. - - :param form: Form containing the field. - :param field: Field containing the URL to validate. - :raises ValidationError: If the URL cannot be resolved, has no hostname, or - resolves to a non-public address. - """ - message = self.message - - if message is None: - message = field.gettext("URL must resolve to a public address.") - - try: - if not is_public_url(field.data): - raise ValidationError(message) - except (AddressResolutionError, ValueError) as exc: - raise ValidationError(message) from exc - - -class PublicIPLiteral: - """Reject non-public IP literals without performing DNS in the web worker.""" - - def __call__(self, form: BaseForm, field: Field) -> None: - try: - hostname = urlsplit(field.data).hostname - except (ValueError, TypeError) as exc: - raise ValidationError(field.gettext("Invalid input.")) from exc - - if hostname is None: - raise ValidationError(field.gettext("Invalid input.")) - - try: - address = ipaddress.ip_address(hostname) - except ValueError: - return # Named hosts are resolved only during the background fetch. - - if not is_public_address(address): - raise ValidationError(field.gettext("URL must use a public address.")) -- cgit v1.3.1