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

"""Provide validators for URL safety and form field constraints."""

import ipaddress
from urllib.parse import urlsplit

from flask import current_app
from wtforms import Field, ValidationError
from wtforms.form import BaseForm

from ..url_security import AddressResolutionError, is_public_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 address.is_global:
            raise ValidationError(field.gettext("URL must use a public address."))