# SPDX-FileCopyrightText: 2026 Dennis Fink # # SPDX-License-Identifier: BSD-3-Clause """Webmention forms and URL validation.""" import ipaddress import re import unicodedata from urllib.parse import urlsplit import httpx from flask import current_app from flask_wtf import FlaskForm from wtforms import Field, PasswordField, StringField, SubmitField, ValidationError from wtforms.form import BaseForm from wtforms.validators import URL, InputRequired, Regexp, StopValidation from .net import is_public_address 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 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 or "").rstrip(".") 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 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.")) 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", ), PublicIPLiteral(), ], ) target = StringField( "target", validators=[ InputRequired(), URLMaxBytes(), HTTPXURL(), URL(), Regexp( "^https?://.*", flags=re.IGNORECASE, message="target must begin with http or https", ), AllowedHostname(), ], ) def validate_source(self, field: Field) -> None: """Reject a source URL that equals the target URL.""" if field.data == self.target.data: raise ValidationError(field.gettext("Field must not be equal to target.")) class AdminActionForm(FlaskForm): """Form for confirming an administrative action.""" submit = SubmitField("Confirm")