aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/forms/validators.py
diff options
context:
space:
mode:
Diffstat (limited to 'webmentions_ssg/forms/validators.py')
-rw-r--r--webmentions_ssg/forms/validators.py27
1 files changed, 26 insertions, 1 deletions
diff --git a/webmentions_ssg/forms/validators.py b/webmentions_ssg/forms/validators.py
index dd0ee9b..e8f33eb 100644
--- a/webmentions_ssg/forms/validators.py
+++ b/webmentions_ssg/forms/validators.py
@@ -4,6 +4,7 @@
"""Provide validators for URL safety and form field constraints."""
+import ipaddress
from urllib.parse import urlsplit
from flask import current_app
@@ -85,7 +86,10 @@ class AllowedHostname:
:param field: Field containing the URL to validate.
:raises ValidationError: If the URL hostname is not configured as allowed.
"""
- hostname = urlsplit(field.data).hostname
+ 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."))
@@ -125,3 +129,24 @@ class PublicURL:
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."))