Skip to content

Commit 1c20656

Browse files
committed
Reject non-string inputs in IP address validators
1 parent 22786cc commit 1c20656

2 files changed

Lines changed: 29 additions & 2 deletions

File tree

‎src/validators/ip_address.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,8 @@ def ipv4(
8282
(Literal[True]): If `value` is a valid IPv4 address.
8383
(ValidationError): If `value` is an invalid IPv4 address.
8484
"""
85-
if not value:
85+
# Validate untyped callers too, even though the public annotation is str.
86+
if not isinstance(value, str) or not value: # pyright: ignore[reportUnnecessaryIsInstance]
8687
return False
8788
try:
8889
if cidr:
@@ -127,7 +128,8 @@ def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bo
127128
(Literal[True]): If `value` is a valid IPv6 address.
128129
(ValidationError): If `value` is an invalid IPv6 address.
129130
"""
130-
if not value:
131+
# Validate untyped callers too, even though the public annotation is str.
132+
if not isinstance(value, str) or not value: # pyright: ignore[reportUnnecessaryIsInstance]
131133
return False
132134
try:
133135
if cidr:

‎tests/test_ip_address.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,37 @@
11
"""Test IP Address."""
22

3+
# standard
4+
from typing import Any, Optional
5+
36
# external
47
import pytest
58

69
# local
710
from validators import ValidationError, ipv4, ipv6
811

912

13+
@pytest.mark.parametrize("address", [True, 3232235777, b"\x7f\x00\x00\x01", ("10.0.0.0", 8)])
14+
@pytest.mark.parametrize("cidr", [True, False])
15+
@pytest.mark.parametrize("private", [None, True, False])
16+
def test_rejects_non_string_ipv4_address(address: Any, cidr: bool, private: Optional[bool]):
17+
"""Reject non-string inputs even when ipaddress accepts their representation."""
18+
assert isinstance(ipv4(address, cidr=cidr, private=private), ValidationError)
19+
20+
21+
@pytest.mark.parametrize("address", [True, 1, bytes(16), ("::", 0)])
22+
@pytest.mark.parametrize("cidr", [True, False])
23+
@pytest.mark.parametrize("strict", [True, False])
24+
def test_rejects_non_string_ipv6_address(address: Any, cidr: bool, strict: bool):
25+
"""Reject non-string addresses and avoid errors from CIDR string operations."""
26+
assert isinstance(ipv6(address, cidr=cidr, strict=strict), ValidationError)
27+
28+
29+
@pytest.mark.parametrize("address", [True, 3232235777, b"\x7f\x00\x00\x01", ("10.0.0.0", 8)])
30+
def test_rejects_non_string_strict_ipv4_address(address: Any):
31+
"""Strict CIDR validation must reject non-string input without an AttributeError."""
32+
assert isinstance(ipv4(address, strict=True), ValidationError)
33+
34+
1035
@pytest.mark.parametrize(
1136
("address",),
1237
[

0 commit comments

Comments
 (0)