diff --git a/src/validators/hostname.py b/src/validators/hostname.py index e34ab7e4..17bd1c0a 100644 --- a/src/validators/hostname.py +++ b/src/validators/hostname.py @@ -129,12 +129,12 @@ def _matches_simple_hostname(host: str): _matches_simple_hostname(host_seg) or domain(host_seg, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782) or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False, private=private)) - or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False)) + or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False, private=private)) ) return ( _matches_simple_hostname(value) or domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782) or (False if skip_ipv4_addr else ipv4(value, cidr=False, private=private)) - or (False if skip_ipv6_addr else ipv6(value, cidr=False)) + or (False if skip_ipv6_addr else ipv6(value, cidr=False, private=private)) ) diff --git a/src/validators/ip_address.py b/src/validators/ip_address.py index 94a42c62..f8d08d25 100644 --- a/src/validators/ip_address.py +++ b/src/validators/ip_address.py @@ -6,6 +6,7 @@ IPv4Address, IPv4Network, IPv6Address, + IPv6Interface, IPv6Network, NetmaskValueError, ) @@ -38,6 +39,33 @@ def _check_private_ip(value: str, is_private: Optional[bool]): return not is_private +# IPv6 counterparts of the IPv4 ranges that `_check_private_ip` treats as private +_PRIVATE_IPV6_NETWORKS = ( + IPv6Network("::/128"), # unspecified + IPv6Network("::1/128"), # loopback + IPv6Network("fc00::/7"), # unique local (private) + IPv6Network("fe80::/10"), # link-local + IPv6Network("fec0::/10"), # site-local (deprecated) + IPv6Network("ff00::/8"), # multicast +) + + +def _check_private_ipv6(value: str, is_private: Optional[bool]): + if is_private is None: + return True + # an interface accepts a bare address as well as CIDR notation + address = IPv6Interface(value).ip + if address.ipv4_mapped is not None: + # ::ffff:a.b.c.d reaches the IPv4 host a.b.c.d + return _check_private_ip(str(address.ipv4_mapped), is_private) + # compare without the zone identifier + address = IPv6Address(int(address)) + if any(address in network for network in _PRIVATE_IPV6_NETWORKS): + return is_private + + return not is_private + + @validator def ipv4( value: str, @@ -95,7 +123,15 @@ def ipv4( @validator -def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True): +def ipv6( + value: str, + /, + *, + cidr: bool = True, + strict: bool = False, + private: Optional[bool] = None, + host_bit: bool = True, +): """Returns if a given value is a valid IPv6 address. Including IPv4-mapped IPv6 addresses. The initial version of ipv6 validator @@ -110,6 +146,8 @@ def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bo True >>> ipv6('abc.0.0.1') ValidationError(func=ipv6, args={'value': 'abc.0.0.1'}) + >>> ipv6('::1', private=False) + ValidationError(func=ipv6, args={'value': '::1', 'private': False}) Args: value: @@ -118,6 +156,9 @@ def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bo IP address string may contain CIDR annotation. strict: IP address string is strictly in CIDR notation. + private: + IP address is public if `False`, private/local/loopback/multicast if `True`. + An IPv4-mapped address is judged by the IPv4 address it embeds. host_bit: If `False` and host bits (along with network bits) _are_ set in the supplied address, this function raises a validation error. ref [IPv6Network][2]. @@ -133,7 +174,7 @@ def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bo if cidr: if strict and value.count("/") != 1: raise ValueError("IPv6 address was expected in CIDR notation") - return IPv6Network(value, strict=not host_bit) - return IPv6Address(value) + return IPv6Network(value, strict=not host_bit) and _check_private_ipv6(value, private) + return IPv6Address(value) and _check_private_ipv6(value, private) except (ValueError, AddressValueError, NetmaskValueError): return False diff --git a/tests/test_hostname.py b/tests/test_hostname.py index 83f00212..92cf63d7 100644 --- a/tests/test_hostname.py +++ b/tests/test_hostname.py @@ -72,6 +72,26 @@ def test_returns_failed_validation_on_invalid_hostname(value: str, rfc_1034: boo assert isinstance(hostname(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782), ValidationError) +@pytest.mark.parametrize( + ("value", "private"), + [ + ("::1", True), + ("[::1]:22", True), + ("[fd00::1]:8080", True), + ("[fe80::1]:22", True), + ("[::ffff:127.0.0.1]:80", True), + ("2606:4700:4700::1111", False), + ("[2001:4860:4860::8888]:53", False), + ("[::ffff:1.1.1.1]:53", False), + ], +) +def test_returns_true_on_ipv6_host_that_matches_the_private_flag(value: str, private: bool): + """Test the private flag applies to IPv6 hosts as it does to IPv4 hosts.""" + assert hostname(value, private=private) + assert isinstance(hostname(value, private=not private), ValidationError) + assert hostname(value) + + @pytest.mark.parametrize( "value", [ diff --git a/tests/test_ip_address.py b/tests/test_ip_address.py index ed6fd7d4..a46a7e43 100644 --- a/tests/test_ip_address.py +++ b/tests/test_ip_address.py @@ -150,6 +150,63 @@ def test_returns_failed_validation_on_invalid_ipv6_cidr_address( assert isinstance(ipv6(address, cidr=cidr, strict=strict, host_bit=host_bit), ValidationError) +@pytest.mark.parametrize( + "address", + [ + "::", # unspecified + "::1", # loopback + "fc00::1", # unique local + "fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + "fe80::1", # link-local + "fe80::1%eth0", + "febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + "fec0::1", # site-local + "ff02::1", # multicast + "fd00::/8", + # IPv4-mapped addresses follow the IPv4 address they embed + "::ffff:127.0.0.1", + "::ffff:10.1.1.1", + "::ffff:169.254.169.254", + "::ffff:7f00:1", + ], +) +def test_returns_true_on_valid_private_ipv6_address(address: str): + """Test returns true on private ipv6 address.""" + assert ipv6(address, private=True) + assert isinstance(ipv6(address, private=False), ValidationError) + + +@pytest.mark.parametrize( + "address", + [ + "2001:4860:4860::8888", + "2606:4700:4700::1111", + "2001:4860:4860::8888%eth0", + "2600::/12", + # just outside the unique local and link-local ranges + "fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + "fe00::1", + "fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + "::2", + # IPv4-mapped addresses follow the IPv4 address they embed + "::ffff:1.1.1.1", + "::ffff:192.169.1.1", + ], +) +def test_returns_true_on_valid_public_ipv6_address(address: str): + """Test returns true on public ipv6 address.""" + assert ipv6(address, private=False) + assert isinstance(ipv6(address, private=True), ValidationError) + + +@pytest.mark.parametrize("address", ["::g", "12345::", "::1/129"]) +def test_returns_failed_validation_on_invalid_ipv6_address_with_private_flag(address: str): + """Test the private flag never turns an invalid ipv6 address into a valid one.""" + assert isinstance(ipv6(address), ValidationError) + assert isinstance(ipv6(address, private=True), ValidationError) + assert isinstance(ipv6(address, private=False), ValidationError) + + @pytest.mark.parametrize( ("address", "private"), [ diff --git a/tests/test_url.py b/tests/test_url.py index d48a03ec..6cd0d88f 100644 --- a/tests/test_url.py +++ b/tests/test_url.py @@ -123,6 +123,40 @@ def test_returns_true_on_valid_private_url(value: str, private: Optional[bool]): assert url(value, private=private) +@pytest.mark.parametrize( + "value", + [ + "http://[::1]/", + "http://[::1]:8080/admin", + "http://[::ffff:127.0.0.1]/", + "http://[::ffff:169.254.169.254]/latest/meta-data/", + "http://[fd00::1]/", + "http://[fe80::1]/", + "http://username:password@[fc00::10]:4010/", + ], +) +def test_private_flag_applies_to_private_ipv6_hosts(value: str): + """Test a private IPv6 host is private, like its IPv4 counterpart.""" + assert url(value, private=True) + assert isinstance(url(value, private=False), ValidationError) + assert url(value) + + +@pytest.mark.parametrize( + "value", + [ + "http://[2001:4860:4860::8888]/", + "http://[2606:4700:4700::1111]:443/dns-query", + "http://[::ffff:1.1.1.1]/", + ], +) +def test_private_flag_applies_to_public_ipv6_hosts(value: str): + """Test a public IPv6 host is public, like its IPv4 counterpart.""" + assert url(value, private=False) + assert isinstance(url(value, private=True), ValidationError) + assert url(value) + + @pytest.mark.parametrize( "value", [