Skip to content

Commit 0fac6f8

Browse files
Apply the private flag to IPv6 hosts in hostname() and url()
hostname() and url() document `private` as "Embedded IP address is public if False, private/local if True", but only passed the flag to ipv4(). Every IPv6 literal therefore passed, whatever the value of the flag: url("http://127.0.0.1/", private=False) # ValidationError url("http://[::1]/", private=False) # True url("http://[::ffff:127.0.0.1]/", private=False) # True url("http://[fd00::1]/", private=False) # True ipv6() gets a `private` parameter and hostname() passes the flag on. The IPv4 behaviour is not touched: _check_private_ip() is unchanged, and the IPv6 check uses the counterparts of the ranges it already treats as private (unspecified, loopback, unique local, link-local, site-local, multicast). An IPv4-mapped address is judged by the IPv4 address it embeds, with the existing function. This is the single pull request asked for when #451, #452 and #453 were closed. See discussion #591. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 22786cc commit 0fac6f8

5 files changed

Lines changed: 157 additions & 5 deletions

File tree

‎src/validators/hostname.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,12 +129,12 @@ def _matches_simple_hostname(host: str):
129129
_matches_simple_hostname(host_seg)
130130
or domain(host_seg, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
131131
or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False, private=private))
132-
or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False))
132+
or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False, private=private))
133133
)
134134

135135
return (
136136
_matches_simple_hostname(value)
137137
or domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
138138
or (False if skip_ipv4_addr else ipv4(value, cidr=False, private=private))
139-
or (False if skip_ipv6_addr else ipv6(value, cidr=False))
139+
or (False if skip_ipv6_addr else ipv6(value, cidr=False, private=private))
140140
)

‎src/validators/ip_address.py‎

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
IPv4Address,
77
IPv4Network,
88
IPv6Address,
9+
IPv6Interface,
910
IPv6Network,
1011
NetmaskValueError,
1112
)
@@ -38,6 +39,33 @@ def _check_private_ip(value: str, is_private: Optional[bool]):
3839
return not is_private
3940

4041

42+
# IPv6 counterparts of the IPv4 ranges that `_check_private_ip` treats as private
43+
_PRIVATE_IPV6_NETWORKS = (
44+
IPv6Network("::/128"), # unspecified
45+
IPv6Network("::1/128"), # loopback
46+
IPv6Network("fc00::/7"), # unique local (private)
47+
IPv6Network("fe80::/10"), # link-local
48+
IPv6Network("fec0::/10"), # site-local (deprecated)
49+
IPv6Network("ff00::/8"), # multicast
50+
)
51+
52+
53+
def _check_private_ipv6(value: str, is_private: Optional[bool]):
54+
if is_private is None:
55+
return True
56+
# an interface accepts a bare address as well as CIDR notation
57+
address = IPv6Interface(value).ip
58+
if address.ipv4_mapped is not None:
59+
# ::ffff:a.b.c.d reaches the IPv4 host a.b.c.d
60+
return _check_private_ip(str(address.ipv4_mapped), is_private)
61+
# compare without the zone identifier
62+
address = IPv6Address(int(address))
63+
if any(address in network for network in _PRIVATE_IPV6_NETWORKS):
64+
return is_private
65+
66+
return not is_private
67+
68+
4169
@validator
4270
def ipv4(
4371
value: str,
@@ -95,7 +123,15 @@ def ipv4(
95123

96124

97125
@validator
98-
def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True):
126+
def ipv6(
127+
value: str,
128+
/,
129+
*,
130+
cidr: bool = True,
131+
strict: bool = False,
132+
private: Optional[bool] = None,
133+
host_bit: bool = True,
134+
):
99135
"""Returns if a given value is a valid IPv6 address.
100136
101137
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
110146
True
111147
>>> ipv6('abc.0.0.1')
112148
ValidationError(func=ipv6, args={'value': 'abc.0.0.1'})
149+
>>> ipv6('::1', private=False)
150+
ValidationError(func=ipv6, args={'value': '::1', 'private': False})
113151
114152
Args:
115153
value:
@@ -118,6 +156,9 @@ def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bo
118156
IP address string may contain CIDR annotation.
119157
strict:
120158
IP address string is strictly in CIDR notation.
159+
private:
160+
IP address is public if `False`, private/local/loopback/multicast if `True`.
161+
An IPv4-mapped address is judged by the IPv4 address it embeds.
121162
host_bit:
122163
If `False` and host bits (along with network bits) _are_ set in the supplied
123164
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
133174
if cidr:
134175
if strict and value.count("/") != 1:
135176
raise ValueError("IPv6 address was expected in CIDR notation")
136-
return IPv6Network(value, strict=not host_bit)
137-
return IPv6Address(value)
177+
return IPv6Network(value, strict=not host_bit) and _check_private_ipv6(value, private)
178+
return IPv6Address(value) and _check_private_ipv6(value, private)
138179
except (ValueError, AddressValueError, NetmaskValueError):
139180
return False

‎tests/test_hostname.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,26 @@ def test_returns_failed_validation_on_invalid_hostname(value: str, rfc_1034: boo
7272
assert isinstance(hostname(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782), ValidationError)
7373

7474

75+
@pytest.mark.parametrize(
76+
("value", "private"),
77+
[
78+
("::1", True),
79+
("[::1]:22", True),
80+
("[fd00::1]:8080", True),
81+
("[fe80::1]:22", True),
82+
("[::ffff:127.0.0.1]:80", True),
83+
("2606:4700:4700::1111", False),
84+
("[2001:4860:4860::8888]:53", False),
85+
("[::ffff:1.1.1.1]:53", False),
86+
],
87+
)
88+
def test_returns_true_on_ipv6_host_that_matches_the_private_flag(value: str, private: bool):
89+
"""Test the private flag applies to IPv6 hosts as it does to IPv4 hosts."""
90+
assert hostname(value, private=private)
91+
assert isinstance(hostname(value, private=not private), ValidationError)
92+
assert hostname(value)
93+
94+
7595
@pytest.mark.parametrize(
7696
"value",
7797
[

‎tests/test_ip_address.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,63 @@ def test_returns_failed_validation_on_invalid_ipv6_cidr_address(
150150
assert isinstance(ipv6(address, cidr=cidr, strict=strict, host_bit=host_bit), ValidationError)
151151

152152

153+
@pytest.mark.parametrize(
154+
"address",
155+
[
156+
"::", # unspecified
157+
"::1", # loopback
158+
"fc00::1", # unique local
159+
"fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
160+
"fe80::1", # link-local
161+
"fe80::1%eth0",
162+
"febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
163+
"fec0::1", # site-local
164+
"ff02::1", # multicast
165+
"fd00::/8",
166+
# IPv4-mapped addresses follow the IPv4 address they embed
167+
"::ffff:127.0.0.1",
168+
"::ffff:10.1.1.1",
169+
"::ffff:169.254.169.254",
170+
"::ffff:7f00:1",
171+
],
172+
)
173+
def test_returns_true_on_valid_private_ipv6_address(address: str):
174+
"""Test returns true on private ipv6 address."""
175+
assert ipv6(address, private=True)
176+
assert isinstance(ipv6(address, private=False), ValidationError)
177+
178+
179+
@pytest.mark.parametrize(
180+
"address",
181+
[
182+
"2001:4860:4860::8888",
183+
"2606:4700:4700::1111",
184+
"2001:4860:4860::8888%eth0",
185+
"2600::/12",
186+
# just outside the unique local and link-local ranges
187+
"fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
188+
"fe00::1",
189+
"fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
190+
"::2",
191+
# IPv4-mapped addresses follow the IPv4 address they embed
192+
"::ffff:1.1.1.1",
193+
"::ffff:192.169.1.1",
194+
],
195+
)
196+
def test_returns_true_on_valid_public_ipv6_address(address: str):
197+
"""Test returns true on public ipv6 address."""
198+
assert ipv6(address, private=False)
199+
assert isinstance(ipv6(address, private=True), ValidationError)
200+
201+
202+
@pytest.mark.parametrize("address", ["::g", "12345::", "::1/129"])
203+
def test_returns_failed_validation_on_invalid_ipv6_address_with_private_flag(address: str):
204+
"""Test the private flag never turns an invalid ipv6 address into a valid one."""
205+
assert isinstance(ipv6(address), ValidationError)
206+
assert isinstance(ipv6(address, private=True), ValidationError)
207+
assert isinstance(ipv6(address, private=False), ValidationError)
208+
209+
153210
@pytest.mark.parametrize(
154211
("address", "private"),
155212
[

‎tests/test_url.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,40 @@ def test_returns_true_on_valid_private_url(value: str, private: Optional[bool]):
123123
assert url(value, private=private)
124124

125125

126+
@pytest.mark.parametrize(
127+
"value",
128+
[
129+
"http://[::1]/",
130+
"http://[::1]:8080/admin",
131+
"http://[::ffff:127.0.0.1]/",
132+
"http://[::ffff:169.254.169.254]/latest/meta-data/",
133+
"http://[fd00::1]/",
134+
"http://[fe80::1]/",
135+
"http://username:password@[fc00::10]:4010/",
136+
],
137+
)
138+
def test_private_flag_applies_to_private_ipv6_hosts(value: str):
139+
"""Test a private IPv6 host is private, like its IPv4 counterpart."""
140+
assert url(value, private=True)
141+
assert isinstance(url(value, private=False), ValidationError)
142+
assert url(value)
143+
144+
145+
@pytest.mark.parametrize(
146+
"value",
147+
[
148+
"http://[2001:4860:4860::8888]/",
149+
"http://[2606:4700:4700::1111]:443/dns-query",
150+
"http://[::ffff:1.1.1.1]/",
151+
],
152+
)
153+
def test_private_flag_applies_to_public_ipv6_hosts(value: str):
154+
"""Test a public IPv6 host is public, like its IPv4 counterpart."""
155+
assert url(value, private=False)
156+
assert isinstance(url(value, private=True), ValidationError)
157+
assert url(value)
158+
159+
126160
@pytest.mark.parametrize(
127161
"value",
128162
[

0 commit comments

Comments
 (0)