v0.166.0
  1import ipaddress
  2import math
  3import re
  4from collections.abc import Callable
  5from pathlib import Path
  6from typing import TYPE_CHECKING, Any, ClassVar, cast
  7from urllib.parse import urlsplit, urlunsplit
  8
  9from plain.exceptions import ValidationError
 10from plain.utils.deconstruct import deconstructible
 11from plain.utils.encoding import punycode
 12from plain.utils.ipv6 import is_valid_ipv6_address
 13from plain.utils.regex_helper import _lazy_re_compile
 14from plain.utils.text import pluralize_lazy
 15
 16if TYPE_CHECKING:
 17    from plain.utils.functional import SimpleLazyObject
 18
 19# These values, if given to validate(), will trigger the self.required check.
 20EMPTY_VALUES = (None, "", [], (), {})
 21
 22
 23@deconstructible
 24class RegexValidator:
 25    regex: str | re.Pattern[str] | SimpleLazyObject = ""
 26    message = "Enter a valid value."
 27    code = "invalid"
 28    inverse_match = False
 29    flags = 0
 30
 31    def __init__(
 32        self,
 33        regex: str | re.Pattern[str] | None = None,
 34        message: str | None = None,
 35        code: str | None = None,
 36        inverse_match: bool | None = None,
 37        flags: int | None = None,
 38    ) -> None:
 39        # Only compile regex if explicitly provided or if class default needs compilation
 40        if regex is not None:
 41            regex_to_compile: str | re.Pattern[str] = regex
 42        elif isinstance(self.regex, str | re.Pattern):
 43            # Class-level regex is a string or pattern that needs compilation
 44            regex_to_compile = self.regex
 45        else:
 46            # Class-level regex is already compiled (e.g., in URL Validator subclass)
 47            # Don't recompile it
 48            regex_to_compile = None
 49
 50        if message is not None:
 51            self.message = message
 52        if code is not None:
 53            self.code = code
 54        if inverse_match is not None:
 55            self.inverse_match = inverse_match
 56        if flags is not None:
 57            self.flags = flags
 58
 59        # Only compile if we have a regex to compile
 60        if regex_to_compile is not None:
 61            if self.flags and not isinstance(regex_to_compile, str):
 62                raise TypeError(
 63                    "If the flags are set, regex must be a regular expression string."
 64                )
 65            self.regex = _lazy_re_compile(regex_to_compile, self.flags)
 66
 67    def __call__(self, value: Any) -> None:
 68        """
 69        Validate that the input contains (or does *not* contain, if
 70        inverse_match is True) a match for the regular expression.
 71        """
 72        # self.regex is always a SimpleLazyObject with search() after __init__
 73        regex_matches = cast(re.Pattern[str], self.regex).search(str(value))
 74        invalid_input = regex_matches if self.inverse_match else not regex_matches
 75        if invalid_input:
 76            raise ValidationError(self.message, code=self.code, params={"value": value})
 77
 78    def __eq__(self, other: object) -> bool:
 79        if not isinstance(other, RegexValidator):
 80            return NotImplemented
 81        self_regex = cast(re.Pattern[str], self.regex)
 82        other_regex = cast(re.Pattern[str], other.regex)
 83        return (
 84            self_regex.pattern == other_regex.pattern
 85            and self_regex.flags == other_regex.flags
 86            and (self.message == other.message)
 87            and (self.code == other.code)
 88            and (self.inverse_match == other.inverse_match)
 89        )
 90
 91
 92@deconstructible
 93class URLValidator(RegexValidator):
 94    ul = "\u00a1-\uffff"  # Unicode letters range (must not be a raw string).
 95
 96    # IP patterns
 97    ipv4_re = (
 98        r"(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)"
 99        r"(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}"
100    )
101    ipv6_re = r"\[[0-9a-f:.]+\]"  # (simple regex, validated later)
102
103    # Host patterns
104    hostname_re = (
105        r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?"
106    )
107    # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
108    domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?<!-))*"
109    tld_re = (
110        r"\."  # dot
111        r"(?!-)"  # can't start with a dash
112        r"(?:[a-z" + ul + "-]{2,63}"  # domain label
113        r"|xn--[a-z0-9]{1,59})"  # or punycode label
114        r"(?<!-)"  # can't end with a dash
115        r"\.?"  # may have a trailing dot
116    )
117    host_re = "(" + hostname_re + domain_re + tld_re + "|localhost)"
118
119    regex = _lazy_re_compile(
120        r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
121        r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication
122        r"(?:" + ipv4_re + "|" + ipv6_re + "|" + host_re + ")"
123        r"(?::[0-9]{1,5})?"  # port
124        r"(?:[/?#][^\s]*)?"  # resource path
125        r"\Z",
126        re.IGNORECASE,
127    )
128    message = "Enter a valid URL."
129    schemes: tuple[str, ...] = ("http", "https", "ftp", "ftps")
130    unsafe_chars = frozenset("\t\r\n")
131
132    def __init__(self, schemes: tuple[str, ...] | None = None, **kwargs: Any) -> None:
133        super().__init__(**kwargs)
134        if schemes is not None:
135            self.schemes = schemes
136
137    def __call__(self, value: Any) -> None:
138        if not isinstance(value, str):
139            raise ValidationError(self.message, code=self.code, params={"value": value})
140        if self.unsafe_chars.intersection(value):
141            raise ValidationError(self.message, code=self.code, params={"value": value})
142        # Check if the scheme is valid.
143        scheme = value.split("://")[0].lower()
144        if scheme not in self.schemes:
145            raise ValidationError(self.message, code=self.code, params={"value": value})
146
147        # Then check full URL
148        try:
149            splitted_url = urlsplit(value)
150        except ValueError:
151            raise ValidationError(self.message, code=self.code, params={"value": value})
152        try:
153            super().__call__(value)
154        except ValidationError as e:
155            # Trivial case failed. Try for possible IDN domain
156            if value:
157                scheme, netloc, path, query, fragment = splitted_url
158                try:
159                    netloc = punycode(netloc)  # IDN -> ACE
160                except UnicodeError:  # invalid domain part
161                    raise e
162                url = urlunsplit((scheme, netloc, path, query, fragment))
163                super().__call__(url)
164            else:
165                raise
166        else:
167            # Now verify IPv6 in the netloc part
168            host_match = re.search(r"^\[(.+)\](?::[0-9]{1,5})?$", splitted_url.netloc)
169            if host_match:
170                potential_ip = host_match[1]
171                try:
172                    validate_ipv6_address(potential_ip)
173                except ValidationError:
174                    raise ValidationError(
175                        self.message, code=self.code, params={"value": value}
176                    )
177
178        # The maximum length of a full host name is 253 characters per RFC 1034
179        # section 3.1. It's defined to be 255 bytes or less, but this includes
180        # one byte for the length of the name and one byte for the trailing dot
181        # that's used to indicate absolute names in DNS.
182        if splitted_url.hostname is None or len(splitted_url.hostname) > 253:
183            raise ValidationError(self.message, code=self.code, params={"value": value})
184
185
186@deconstructible
187class EmailValidator:
188    message = "Enter a valid email address."
189    code = "invalid"
190    user_regex = _lazy_re_compile(
191        # dot-atom
192        r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z"
193        # quoted-string
194        r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])'
195        r'*"\Z)',
196        re.IGNORECASE,
197    )
198    domain_regex = _lazy_re_compile(
199        # max length for domain name labels is 63 characters per RFC 1034
200        r"((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\Z",
201        re.IGNORECASE,
202    )
203    literal_regex = _lazy_re_compile(
204        # literal form, ipv4 or ipv6 address (SMTP 4.1.3)
205        r"\[([A-F0-9:.]+)\]\Z",
206        re.IGNORECASE,
207    )
208    domain_allowlist: tuple[str, ...] = ("localhost",)
209
210    def __init__(
211        self,
212        message: str | None = None,
213        code: str | None = None,
214        allowlist: tuple[str, ...] | None = None,
215    ) -> None:
216        if message is not None:
217            self.message = message
218        if code is not None:
219            self.code = code
220        if allowlist is not None:
221            self.domain_allowlist = allowlist
222
223    def __call__(self, value: Any) -> None:
224        if not value or "@" not in value:
225            raise ValidationError(self.message, code=self.code, params={"value": value})
226
227        user_part, domain_part = value.rsplit("@", 1)
228
229        if not self.user_regex.match(user_part):
230            raise ValidationError(self.message, code=self.code, params={"value": value})
231
232        if domain_part not in self.domain_allowlist and not self.validate_domain_part(
233            domain_part
234        ):
235            # Try for possible IDN domain-part
236            try:
237                domain_part = punycode(domain_part)
238            except UnicodeError:
239                pass
240            else:
241                if self.validate_domain_part(domain_part):
242                    return
243            raise ValidationError(self.message, code=self.code, params={"value": value})
244        return
245
246    def validate_domain_part(self, domain_part: str) -> bool:
247        if self.domain_regex.match(domain_part):
248            return True
249
250        literal_match = self.literal_regex.match(domain_part)
251        if literal_match:
252            ip_address = literal_match[1]
253            try:
254                validate_ipv46_address(ip_address)
255                return True
256            except ValidationError:
257                pass
258        return False
259
260    def __eq__(self, other: object) -> bool:
261        return (
262            isinstance(other, EmailValidator)
263            and (self.domain_allowlist == other.domain_allowlist)
264            and (self.message == other.message)
265            and (self.code == other.code)
266        )
267
268
269validate_email = EmailValidator()
270
271
272def validate_ipv4_address(value: str, /) -> None:
273    try:
274        ipaddress.IPv4Address(value)
275    except ValueError:
276        raise ValidationError(
277            "Enter a valid IPv4 address.", code="invalid", params={"value": value}
278        )
279
280
281def validate_ipv6_address(value: str, /) -> None:
282    if not is_valid_ipv6_address(value):
283        raise ValidationError(
284            "Enter a valid IPv6 address.", code="invalid", params={"value": value}
285        )
286
287
288def validate_ipv46_address(value: str, /) -> None:
289    try:
290        validate_ipv4_address(value)
291    except ValidationError:
292        try:
293            validate_ipv6_address(value)
294        except ValidationError:
295            raise ValidationError(
296                "Enter a valid IPv4 or IPv6 address.",
297                code="invalid",
298                params={"value": value},
299            )
300
301
302ip_address_validator_map: dict[str, tuple[tuple[Callable[[str], None], ...], str]] = {
303    "both": ((validate_ipv46_address,), "Enter a valid IPv4 or IPv6 address."),
304    "ipv4": ((validate_ipv4_address,), "Enter a valid IPv4 address."),
305    "ipv6": ((validate_ipv6_address,), "Enter a valid IPv6 address."),
306}
307
308
309def ip_address_validators(
310    protocol: str, unpack_ipv4: bool
311) -> tuple[tuple[Callable[[str], None], ...], str]:
312    """
313    Depending on the given parameters, return the appropriate validators for
314    the GenericIPAddressField.
315    """
316    if protocol != "both" and unpack_ipv4:
317        raise ValueError(
318            "You can only use `unpack_ipv4` if `protocol` is set to 'both'"
319        )
320    try:
321        return ip_address_validator_map[protocol.lower()]
322    except KeyError:
323        raise ValueError(
324            f"The protocol '{protocol}' is unknown. Supported: {list(ip_address_validator_map)}"
325        )
326
327
328def int_list_validator(
329    sep: str = ",",
330    message: str | None = None,
331    code: str = "invalid",
332    allow_negative: bool = False,
333) -> RegexValidator:
334    regexp = _lazy_re_compile(
335        r"^{neg}\d+(?:{sep}{neg}\d+)*\Z".format(
336            neg="(-)?" if allow_negative else "",
337            sep=re.escape(sep),
338        )
339    )
340    return RegexValidator(regexp, message=message, code=code)  # ty: ignore[invalid-argument-type]
341
342
343validate_comma_separated_integer_list = int_list_validator(
344    message="Enter only digits separated by commas.",
345)
346
347
348@deconstructible
349class BaseValidator:
350    message = "Ensure this value is %(limit_value)s (it is %(show_value)s)."
351    code = "limit_value"
352
353    def __init__(self, limit_value: Any, message: str | None = None) -> None:
354        self.limit_value = limit_value
355        if message:
356            self.message = message
357
358    def __call__(self, value: Any) -> None:
359        cleaned = self.clean(value)
360        limit_value = (
361            self.limit_value() if callable(self.limit_value) else self.limit_value
362        )
363        params = {"limit_value": limit_value, "show_value": cleaned, "value": value}
364        if self.compare(cleaned, limit_value):
365            raise ValidationError(self.message, code=self.code, params=params)
366
367    def __eq__(self, other: object) -> bool:
368        if not isinstance(other, self.__class__):
369            return NotImplemented
370        return (
371            self.limit_value == other.limit_value
372            and self.message == other.message
373            and self.code == other.code
374        )
375
376    def compare(self, a: Any, b: Any) -> bool:
377        return a is not b
378
379    def clean(self, x: Any) -> Any:
380        return x
381
382
383@deconstructible
384class MaxValueValidator(BaseValidator):
385    message = "Ensure this value is less than or equal to %(limit_value)s."
386    code = "max_value"
387
388    def compare(self, a: Any, b: Any) -> bool:
389        return a > b
390
391
392@deconstructible
393class MinValueValidator(BaseValidator):
394    message = "Ensure this value is greater than or equal to %(limit_value)s."
395    code = "min_value"
396
397    def compare(self, a: Any, b: Any) -> bool:
398        return a < b
399
400
401@deconstructible
402class StepValueValidator(BaseValidator):
403    message = "Ensure this value is a multiple of step size %(limit_value)s."
404    code = "step_size"
405
406    def compare(self, a: Any, b: Any) -> bool:
407        return not math.isclose(math.remainder(a, b), 0, abs_tol=1e-9)
408
409
410@deconstructible
411class MinLengthValidator(BaseValidator):
412    message = pluralize_lazy(
413        "Ensure this value has at least %(limit_value)d character (it has "
414        "%(show_value)d).",
415        "Ensure this value has at least %(limit_value)d characters (it has "
416        "%(show_value)d).",
417        "limit_value",
418    )
419    code = "min_length"
420
421    def compare(self, a: Any, b: Any) -> bool:
422        return a < b
423
424    def clean(self, x: Any) -> int:
425        return len(x)
426
427
428@deconstructible
429class MaxLengthValidator(BaseValidator):
430    message = pluralize_lazy(
431        "Ensure this value has at most %(limit_value)d character (it has "
432        "%(show_value)d).",
433        "Ensure this value has at most %(limit_value)d characters (it has "
434        "%(show_value)d).",
435        "limit_value",
436    )
437    code = "max_length"
438
439    def compare(self, a: Any, b: Any) -> bool:
440        return a > b
441
442    def clean(self, x: Any) -> int:
443        return len(x)
444
445
446@deconstructible
447class DecimalValidator:
448    """
449    Validate that the input does not exceed the maximum number of digits
450    expected, otherwise raise ValidationError.
451    """
452
453    messages: ClassVar = {
454        "invalid": "Enter a number.",
455        "max_digits": pluralize_lazy(
456            "Ensure that there are no more than %(max)s digit in total.",
457            "Ensure that there are no more than %(max)s digits in total.",
458            "max",
459        ),
460        "max_decimal_places": pluralize_lazy(
461            "Ensure that there are no more than %(max)s decimal place.",
462            "Ensure that there are no more than %(max)s decimal places.",
463            "max",
464        ),
465        "max_whole_digits": pluralize_lazy(
466            "Ensure that there are no more than %(max)s digit before the decimal "
467            "point.",
468            "Ensure that there are no more than %(max)s digits before the decimal "
469            "point.",
470            "max",
471        ),
472    }
473
474    def __init__(self, max_digits: int | None, decimal_places: int | None) -> None:
475        self.max_digits = max_digits
476        self.decimal_places = decimal_places
477
478    def __call__(self, value: Any) -> None:
479        digit_tuple, exponent = value.as_tuple()[1:]
480        if exponent in {"F", "n", "N"}:
481            raise ValidationError(
482                self.messages["invalid"], code="invalid", params={"value": value}
483            )
484        if exponent >= 0:
485            digits = len(digit_tuple)
486            if digit_tuple != (0,):
487                # A positive exponent adds that many trailing zeros.
488                digits += exponent
489            decimals = 0
490        else:
491            # If the absolute value of the negative exponent is larger than the
492            # number of digits, then it's the same as the number of digits,
493            # because it'll consume all of the digits in digit_tuple and then
494            # add abs(exponent) - len(digit_tuple) leading zeros after the
495            # decimal point.
496            if abs(exponent) > len(digit_tuple):
497                digits = decimals = abs(exponent)
498            else:
499                digits = len(digit_tuple)
500                decimals = abs(exponent)
501        whole_digits = digits - decimals
502
503        if self.max_digits is not None and digits > self.max_digits:
504            raise ValidationError(
505                self.messages["max_digits"],
506                code="max_digits",
507                params={"max": self.max_digits, "value": value},
508            )
509        if self.decimal_places is not None and decimals > self.decimal_places:
510            raise ValidationError(
511                self.messages["max_decimal_places"],
512                code="max_decimal_places",
513                params={"max": self.decimal_places, "value": value},
514            )
515        if (
516            self.max_digits is not None
517            and self.decimal_places is not None
518            and whole_digits > (self.max_digits - self.decimal_places)
519        ):
520            raise ValidationError(
521                self.messages["max_whole_digits"],
522                code="max_whole_digits",
523                params={"max": (self.max_digits - self.decimal_places), "value": value},
524            )
525
526    def __eq__(self, other: object) -> bool:
527        return (
528            isinstance(other, self.__class__)
529            and self.max_digits == other.max_digits
530            and self.decimal_places == other.decimal_places
531        )
532
533
534@deconstructible
535class FileExtensionValidator:
536    message = 'File extension "%(extension)s" is not allowed. Allowed extensions are: %(allowed_extensions)s.'
537    code = "invalid_extension"
538
539    def __init__(
540        self,
541        allowed_extensions: list[str] | None = None,
542        message: str | None = None,
543        code: str | None = None,
544    ) -> None:
545        if allowed_extensions is not None:
546            allowed_extensions = [
547                allowed_extension.lower() for allowed_extension in allowed_extensions
548            ]
549        self.allowed_extensions = allowed_extensions
550        if message is not None:
551            self.message = message
552        if code is not None:
553            self.code = code
554
555    def __call__(self, value: Any) -> None:
556        extension = Path(value.name).suffix[1:].lower()
557        if (
558            self.allowed_extensions is not None
559            and extension not in self.allowed_extensions
560        ):
561            raise ValidationError(
562                self.message,
563                code=self.code,
564                params={
565                    "extension": extension,
566                    "allowed_extensions": ", ".join(self.allowed_extensions),
567                    "value": value,
568                },
569            )
570
571    def __eq__(self, other: object) -> bool:
572        return (
573            isinstance(other, self.__class__)
574            and self.allowed_extensions == other.allowed_extensions
575            and self.message == other.message
576            and self.code == other.code
577        )
578
579
580def get_available_image_extensions() -> list[str]:
581    try:
582        from PIL import Image  # ty: ignore[unresolved-import]
583    except ImportError:
584        return []
585    else:
586        Image.init()
587        return [ext.lower()[1:] for ext in Image.EXTENSION]
588
589
590def validate_image_file_extension(value: Any) -> None:
591    return FileExtensionValidator(allowed_extensions=get_available_image_extensions())(
592        value
593    )
594
595
596@deconstructible
597class ProhibitNullCharactersValidator:
598    """Validate that the string doesn't contain the null character."""
599
600    message = "Null characters are not allowed."
601    code = "null_characters_not_allowed"
602
603    def __init__(self, message: str | None = None, code: str | None = None) -> None:
604        if message is not None:
605            self.message = message
606        if code is not None:
607            self.code = code
608
609    def __call__(self, value: Any) -> None:
610        if "\x00" in str(value):
611            raise ValidationError(self.message, code=self.code, params={"value": value})
612
613    def __eq__(self, other: object) -> bool:
614        return (
615            isinstance(other, self.__class__)
616            and self.message == other.message
617            and self.code == other.code
618        )