From eb4da0b58c2e0b851eb7c4fe378b531de7f06512 Mon Sep 17 00:00:00 2001 From: Jo2234 <64789670+Jo2234@users.noreply.github.com> Date: Sun, 1 Mar 2026 15:56:17 +0800 Subject: [PATCH] fix: reject hostnames exceeding 253 characters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per RFC 1123, a hostname must not exceed 253 characters. The existing validator only checked individual label length (≤63 chars via regex) but never validated the total hostname length. This allowed hostnames with multiple short labels separated by dots to pass validation even when the total length exceeded 253 characters. The fix adds an early length check after stripping port and IPv6 brackets, before proceeding with label/domain/IP validation. Fixes #413 --- src/validators/hostname.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/validators/hostname.py b/src/validators/hostname.py index bdf6bdb..2015a13 100644 --- a/src/validators/hostname.py +++ b/src/validators/hostname.py @@ -113,6 +113,20 @@ def hostname( if not value: return False + # Determine the host part (strip port if present) for length validation + host_part = value + if may_have_port: + if (seg := _port_validator(value)): + host_part = seg + + # Strip IPv6 brackets for length check + host_part = host_part.lstrip("[").rstrip("]") + + # RFC 1123: total hostname length must not exceed 253 characters + # (excluding optional trailing dot) + if len(host_part.rstrip(".")) > 253: + return False + if may_have_port and (host_seg := _port_validator(value)): return ( (_simple_hostname_regex().match(host_seg) if maybe_simple else False)