aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/forms.py
blob: c8ad0bae89071f0f45fa5e5d17139cad172a240a (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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Webmention forms and URL validation."""

import ipaddress

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 InputRequired, StopValidation

from .net import is_public_address, normalized_hostname
from .validation import is_control_character


class MaxURLBytes:
    """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 StrictHTTPURL:
    """Require an HTTP(S) URL that httpx can parse without rewriting whitespace.

    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 is_control_character(character)
            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."))

        if parsed.scheme not in ("http", "https"):
            raise StopValidation(
                field.gettext(f"{field.name} must begin with http or https")
            )


class AllowedTargetHostname:
    """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.
        """
        hostname = normalized_hostname(field.data)
        if (
            hostname is not None
            and hostname in current_app.config["ALLOWED_TARGET_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:
        hostname = normalized_hostname(field.data)
        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 WebmentionSubmissionForm(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(), MaxURLBytes(), StrictHTTPURL(), PublicIPLiteral()],
    )
    target = StringField(
        "target",
        validators=[
            InputRequired(),
            MaxURLBytes(),
            StrictHTTPURL(),
            AllowedTargetHostname(),
        ],
    )

    def validate_source(self, field: Field) -> None:
        """Reject a source URL that equals the target URL.

        :param field: Source URL field being validated.
        :raises ValidationError: If the source URL equals the target URL.
        """
        if field.data == self.target.data:
            raise ValidationError(field.gettext("Field must not be equal to target."))


class ConfirmActionForm(FlaskForm):
    """Form for confirming an administrative action."""

    submit = SubmitField("Confirm")