network-validators 0.1.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,107 @@
1
+ """Validators for network-related input: IP addresses, subnets, ranges, hostnames, ports and MAC addresses.
2
+
3
+ Every ``validate_*`` function returns a :class:`ValidationResult` with a stable error ``code``;
4
+ every ``is_*`` function returns a plain ``bool``. Behavior is defined by the shared specification
5
+ (spec/SPEC.md) and matches the TypeScript package.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from ._core import ValidationResult
13
+ from .domain import validate_fqdn, validate_host, validate_hostname
14
+ from .ip import validate_ip_address, validate_private_ip_address
15
+ from .ip_range import validate_ip_range
16
+ from .mac import validate_mac_address
17
+ from .port import validate_port, validate_port_list, validate_port_range
18
+ from .relations import (
19
+ validate_ip_in_subnets,
20
+ validate_ip_not_in_subnets,
21
+ validate_ip_range_not_overlapping,
22
+ validate_subnet_in_subnets,
23
+ validate_subnet_not_overlapping,
24
+ )
25
+ from .subnet import validate_netmask, validate_private_subnet, validate_subnet
26
+
27
+ __version__ = "0.1.0rc1"
28
+ SPEC_VERSION = "0.1.0"
29
+
30
+
31
+ def is_ip_address(value: Any, **options: Any) -> bool:
32
+ return validate_ip_address(value, **options).valid
33
+
34
+
35
+ def is_private_ip_address(value: Any, **options: Any) -> bool:
36
+ return validate_private_ip_address(value, **options).valid
37
+
38
+
39
+ def is_netmask(value: Any) -> bool:
40
+ return validate_netmask(value).valid
41
+
42
+
43
+ def is_subnet(value: Any, **options: Any) -> bool:
44
+ return validate_subnet(value, **options).valid
45
+
46
+
47
+ def is_private_subnet(value: Any, **options: Any) -> bool:
48
+ return validate_private_subnet(value, **options).valid
49
+
50
+
51
+ def is_ip_range(value: Any, **options: Any) -> bool:
52
+ return validate_ip_range(value, **options).valid
53
+
54
+
55
+ def is_ip_in_subnets(value: Any, **options: Any) -> bool:
56
+ return validate_ip_in_subnets(value, **options).valid
57
+
58
+
59
+ def is_ip_not_in_subnets(value: Any, **options: Any) -> bool:
60
+ return validate_ip_not_in_subnets(value, **options).valid
61
+
62
+
63
+ def is_subnet_in_subnets(value: Any, **options: Any) -> bool:
64
+ return validate_subnet_in_subnets(value, **options).valid
65
+
66
+
67
+ def is_subnet_not_overlapping(value: Any, **options: Any) -> bool:
68
+ return validate_subnet_not_overlapping(value, **options).valid
69
+
70
+
71
+ def is_ip_range_not_overlapping(value: Any, **options: Any) -> bool:
72
+ return validate_ip_range_not_overlapping(value, **options).valid
73
+
74
+
75
+ def is_hostname(value: Any, **options: Any) -> bool:
76
+ return validate_hostname(value, **options).valid
77
+
78
+
79
+ def is_fqdn(value: Any, **options: Any) -> bool:
80
+ return validate_fqdn(value, **options).valid
81
+
82
+
83
+ def is_host(value: Any, **options: Any) -> bool:
84
+ return validate_host(value, **options).valid
85
+
86
+
87
+ def is_port(value: Any, **options: Any) -> bool:
88
+ return validate_port(value, **options).valid
89
+
90
+
91
+ def is_port_range(value: Any, **options: Any) -> bool:
92
+ return validate_port_range(value, **options).valid
93
+
94
+
95
+ def is_port_list(value: Any, **options: Any) -> bool:
96
+ return validate_port_list(value, **options).valid
97
+
98
+
99
+ def is_mac_address(value: Any, **options: Any) -> bool:
100
+ return validate_mac_address(value, **options).valid
101
+
102
+
103
+ __all__ = [
104
+ "SPEC_VERSION",
105
+ "ValidationResult",
106
+ *[name for name in dict(globals()) if name.startswith(("validate_", "is_"))],
107
+ ]
@@ -0,0 +1,251 @@
1
+ """Address and subnet parsing (SPEC §2, §4.2). No dependency on the stdlib ipaddress module,
2
+ so behavior matches the TypeScript implementation exactly."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import string
7
+ from dataclasses import dataclass
8
+ from typing import Any, List, Optional, Sequence
9
+
10
+ from ._core import Invalid, is_ascii_digits
11
+
12
+ _HEX = frozenset("0123456789abcdefABCDEF")
13
+ _ZONE_CHARS = frozenset(string.ascii_letters + string.digits + "._~-")
14
+
15
+
16
+ class AddressError(Exception):
17
+ """kind is 'invalid' or 'leading_zero'."""
18
+
19
+ def __init__(self, kind: str = "invalid") -> None:
20
+ super().__init__(kind)
21
+ self.kind = kind
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Address:
26
+ version: int
27
+ value: int
28
+ zone: Optional[str] = None
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Network:
33
+ version: int
34
+ address: int # as written, host bits included
35
+ prefix: int
36
+
37
+ @property
38
+ def bits(self) -> int:
39
+ return 32 if self.version == 4 else 128
40
+
41
+ @property
42
+ def mask(self) -> int:
43
+ return ((1 << self.prefix) - 1) << (self.bits - self.prefix)
44
+
45
+ @property
46
+ def first(self) -> int:
47
+ return self.address & self.mask
48
+
49
+ @property
50
+ def last(self) -> int:
51
+ return self.first | (~self.mask & ((1 << self.bits) - 1))
52
+
53
+
54
+ # --- parsing -----------------------------------------------------------------
55
+
56
+
57
+ def parse_ipv4(s: str) -> int:
58
+ parts = s.split(".")
59
+ if len(parts) != 4:
60
+ raise AddressError()
61
+ value = 0
62
+ leading_zero = False
63
+ for part in parts:
64
+ if not (1 <= len(part) <= 3) or not is_ascii_digits(part):
65
+ raise AddressError()
66
+ n = int(part)
67
+ if n > 255:
68
+ raise AddressError()
69
+ if len(part) > 1 and part[0] == "0":
70
+ leading_zero = True
71
+ value = (value << 8) | n
72
+ if leading_zero:
73
+ raise AddressError("leading_zero")
74
+ return value
75
+
76
+
77
+ def parse_ipv6(s: str) -> Address:
78
+ zone: Optional[str] = None
79
+ if "%" in s:
80
+ s, zone = s.split("%", 1)
81
+ if zone == "" or any(c not in _ZONE_CHARS for c in zone):
82
+ raise AddressError()
83
+
84
+ if "." in s:
85
+ idx = s.rfind(":")
86
+ if idx == -1:
87
+ raise AddressError()
88
+ try:
89
+ v4 = parse_ipv4(s[idx + 1 :])
90
+ except AddressError:
91
+ raise AddressError() from None
92
+ s = f"{s[: idx + 1]}{v4 >> 16:x}:{v4 & 0xFFFF:x}"
93
+
94
+ if s.count("::") > 1:
95
+ raise AddressError()
96
+ if "::" in s:
97
+ head, tail = s.split("::", 1)
98
+ h = head.split(":") if head else []
99
+ t = tail.split(":") if tail else []
100
+ if len(h) + len(t) > 7:
101
+ raise AddressError()
102
+ groups = h + ["0"] * (8 - len(h) - len(t)) + t
103
+ else:
104
+ groups = s.split(":")
105
+ if len(groups) != 8:
106
+ raise AddressError()
107
+
108
+ value = 0
109
+ for g in groups:
110
+ if not (1 <= len(g) <= 4) or any(c not in _HEX for c in g):
111
+ raise AddressError()
112
+ value = (value << 16) | int(g, 16)
113
+ return Address(6, value, zone)
114
+
115
+
116
+ def parse_ip(s: str) -> Address:
117
+ """SPEC §2.3. Raises AddressError."""
118
+ if ":" in s:
119
+ return parse_ipv6(s)
120
+ return Address(4, parse_ipv4(s))
121
+
122
+
123
+ def netmask_prefix(s: str) -> int:
124
+ """Prefix length of a dotted IPv4 netmask. Raises AddressError or ValueError (not contiguous)."""
125
+ value = parse_ipv4(s)
126
+ inverted = ~value & 0xFFFFFFFF
127
+ if inverted & (inverted + 1):
128
+ raise ValueError("netmask not contiguous")
129
+ return 32 - inverted.bit_length()
130
+
131
+
132
+ # --- formatting (SPEC §2.4) ----------------------------------------------------
133
+
134
+
135
+ def format_address(version: int, value: int) -> str:
136
+ if version == 4:
137
+ return ".".join(str((value >> shift) & 0xFF) for shift in (24, 16, 8, 0))
138
+ groups = [(value >> (16 * (7 - i))) & 0xFFFF for i in range(8)]
139
+ best_start, best_len = -1, 0
140
+ i = 0
141
+ while i < 8:
142
+ if groups[i] == 0:
143
+ j = i
144
+ while j < 8 and groups[j] == 0:
145
+ j += 1
146
+ if j - i > best_len:
147
+ best_start, best_len = i, j - i
148
+ i = j
149
+ else:
150
+ i += 1
151
+ hexes = [f"{g:x}" for g in groups]
152
+ if best_len < 2:
153
+ return ":".join(hexes)
154
+ head = ":".join(hexes[:best_start])
155
+ tail = ":".join(hexes[best_start + best_len :])
156
+ return f"{head}::{tail}"
157
+
158
+
159
+ def format_network(net: Network) -> str:
160
+ return f"{format_address(net.version, net.first)}/{net.prefix}"
161
+
162
+
163
+ # --- subnets (SPEC §4.2) -------------------------------------------------------
164
+
165
+
166
+ def check_version_matches(prefix: str, version: Any, actual: int) -> None:
167
+ if version != "any" and actual != version:
168
+ raise Invalid(f"{prefix}.wrong_version", {"version": actual})
169
+
170
+
171
+ def parse_subnet(
172
+ value: str,
173
+ *,
174
+ version: Any = "any",
175
+ allow_netmask: bool = True,
176
+ allow_host_bits: bool = True,
177
+ ) -> Network:
178
+ """Checks 1-7 of SPEC §4.2 on a value that already passed the common checks."""
179
+ if "/" in value:
180
+ left, _, right = value.partition("/")
181
+ if "/" in right:
182
+ raise Invalid("subnet.invalid")
183
+ elif value.count(" ") == 1:
184
+ left, _, right = value.partition(" ")
185
+ if "." not in right:
186
+ raise Invalid("subnet.invalid")
187
+ else:
188
+ raise Invalid("subnet.invalid")
189
+ if left == "" or right == "":
190
+ raise Invalid("subnet.invalid")
191
+
192
+ try:
193
+ addr = parse_ip(left)
194
+ except AddressError:
195
+ raise Invalid("subnet.invalid_address") from None
196
+ if addr.zone is not None:
197
+ raise Invalid("subnet.invalid_address")
198
+ check_version_matches("subnet", version, addr.version)
199
+
200
+ if "." in right:
201
+ if not allow_netmask:
202
+ raise Invalid("subnet.netmask_not_allowed")
203
+ if addr.version == 6:
204
+ raise Invalid("subnet.invalid_netmask")
205
+ try:
206
+ prefix = netmask_prefix(right)
207
+ except (AddressError, ValueError):
208
+ raise Invalid("subnet.invalid_netmask") from None
209
+ else:
210
+ max_prefix = 32 if addr.version == 4 else 128
211
+ if (
212
+ not is_ascii_digits(right)
213
+ or len(right) > 3
214
+ or (len(right) > 1 and right[0] == "0")
215
+ or int(right) > max_prefix
216
+ ):
217
+ raise Invalid("subnet.invalid_prefix")
218
+ prefix = int(right)
219
+
220
+ net = Network(addr.version, addr.value, prefix)
221
+ if not allow_host_bits and net.address != net.first:
222
+ raise Invalid("subnet.host_bits_set", {"network": format_network(net)})
223
+ return net
224
+
225
+
226
+ def parse_subnet_list(name: str, entries: Any) -> List[Network]:
227
+ """SPEC §2.6. Raises TypeError/ValueError for bad configuration."""
228
+ if isinstance(entries, (str, bytes)) or not isinstance(entries, Sequence):
229
+ raise TypeError(f"{name} must be a list of subnet strings")
230
+ nets = []
231
+ for entry in entries:
232
+ if not isinstance(entry, str) or entry == "":
233
+ raise ValueError(f"{name}: invalid subnet {entry!r}")
234
+ try:
235
+ nets.append(parse_subnet(entry))
236
+ except Invalid as e:
237
+ raise ValueError(f"{name}: invalid subnet {entry!r} ({e.code})") from None
238
+ return nets
239
+
240
+
241
+ PRIVATE_NETWORKS = parse_subnet_list(
242
+ "PRIVATE_NETWORKS", ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]
243
+ )
244
+
245
+
246
+ def in_network(version: int, value: int, net: Network) -> bool:
247
+ return version == net.version and net.first <= value <= net.last
248
+
249
+
250
+ def is_private(addr: Address) -> bool:
251
+ return any(in_network(addr.version, addr.value, n) for n in PRIVATE_NETWORKS)
@@ -0,0 +1,75 @@
1
+ """Result type, common checks and option checks shared by all validators (SPEC §1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Callable, Dict, Literal, Optional, Union
7
+
8
+ Version = Union[Literal[4], Literal[6], Literal["any"]]
9
+
10
+ ASCII_DIGITS = frozenset("0123456789")
11
+ _ASCII_WHITESPACE = frozenset(" \t\n\r\x0b\x0c")
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ValidationResult:
16
+ """Outcome of a validation. Truthy when valid."""
17
+
18
+ valid: bool
19
+ code: Optional[str] = None
20
+ details: Dict[str, Any] = field(default_factory=dict)
21
+
22
+ def __bool__(self) -> bool:
23
+ return self.valid
24
+
25
+
26
+ class Invalid(Exception):
27
+ """Internal signal for a validation failure; converted to a ValidationResult."""
28
+
29
+ def __init__(self, code: str, details: Optional[Dict[str, Any]] = None) -> None:
30
+ super().__init__(code)
31
+ self.code = code
32
+ self.details = details or {}
33
+
34
+ def result(self) -> ValidationResult:
35
+ return ValidationResult(False, self.code, dict(self.details))
36
+
37
+
38
+ def run(check: Callable[[], Any]) -> ValidationResult:
39
+ """Run a check that raises Invalid on failure and return the result."""
40
+ try:
41
+ check()
42
+ except Invalid as e:
43
+ return e.result()
44
+ return ValidationResult(True)
45
+
46
+
47
+ def check_common(value: Any) -> str:
48
+ """SPEC §1.4. Returns the value typed as str."""
49
+ if not isinstance(value, str):
50
+ raise Invalid("not_string")
51
+ if value == "":
52
+ raise Invalid("empty")
53
+ if value[0] in _ASCII_WHITESPACE or value[-1] in _ASCII_WHITESPACE:
54
+ raise Invalid("whitespace")
55
+ return value
56
+
57
+
58
+ def is_ascii_digits(s: str) -> bool:
59
+ return s != "" and all(c in ASCII_DIGITS for c in s)
60
+
61
+
62
+ # --- option checks (configuration errors, SPEC §1.3) -------------------------
63
+
64
+
65
+ def check_version(version: Any) -> None:
66
+ if version == "any" and isinstance(version, str):
67
+ return
68
+ if type(version) is int and version in (4, 6):
69
+ return
70
+ raise ValueError(f"version must be 4, 6 or 'any', got {version!r}")
71
+
72
+
73
+ def check_bool(name: str, value: Any) -> None:
74
+ if not isinstance(value, bool):
75
+ raise TypeError(f"{name} must be a bool, got {value!r}")
@@ -0,0 +1,137 @@
1
+ """Hostname, FQDN and host validators (SPEC §7)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import string
6
+ from typing import Any
7
+
8
+ from ._core import ASCII_DIGITS, Invalid, ValidationResult, Version, check_bool, check_common, check_version, run, is_ascii_digits
9
+ from .ip import validate_ip_address
10
+
11
+ _LDH = frozenset(string.ascii_letters + string.digits + "-")
12
+ _LDH_UNDERSCORE = _LDH | {"_"}
13
+ _IP_CHARS = ASCII_DIGITS | {"."}
14
+
15
+
16
+ def _check_name(
17
+ value: str,
18
+ *,
19
+ require_two_labels: bool,
20
+ allow_wildcard: bool,
21
+ allow_underscore: bool,
22
+ allow_trailing_dot: bool,
23
+ ) -> None:
24
+ name = value
25
+ if name.endswith("."):
26
+ if not allow_trailing_dot:
27
+ raise Invalid("domain.trailing_dot_not_allowed")
28
+ name = name[:-1]
29
+ if len(name) > 253:
30
+ raise Invalid("domain.too_long")
31
+
32
+ allowed = _LDH_UNDERSCORE if allow_underscore else _LDH
33
+ labels = name.split(".")
34
+ for i, label in enumerate(labels):
35
+ if label == "":
36
+ raise Invalid("domain.empty_label")
37
+ if "*" in label:
38
+ if i == 0 and label == "*":
39
+ if not allow_wildcard:
40
+ raise Invalid("domain.wildcard_not_allowed")
41
+ continue
42
+ raise Invalid("domain.invalid_wildcard")
43
+ if len(label) > 63:
44
+ raise Invalid("domain.label_too_long")
45
+ for c in label:
46
+ if c not in allowed:
47
+ raise Invalid("domain.invalid_character", {"character": c})
48
+ if label[0] == "-" or label[-1] == "-":
49
+ raise Invalid("domain.hyphen_position")
50
+
51
+ real = labels[1:] if labels[0] == "*" else labels
52
+ if not real:
53
+ raise Invalid("domain.invalid_wildcard")
54
+ if require_two_labels and len(real) < 2:
55
+ raise Invalid("domain.single_label")
56
+ if is_ascii_digits(real[-1]):
57
+ raise Invalid("domain.numeric_tld")
58
+
59
+
60
+ def _validate_name(value: Any, require_two_labels: bool, **opts: bool) -> ValidationResult:
61
+ for name, v in opts.items():
62
+ check_bool(name, v)
63
+ return run(lambda: _check_name(check_common(value), require_two_labels=require_two_labels, **opts))
64
+
65
+
66
+ def validate_hostname(
67
+ value: Any,
68
+ *,
69
+ allow_wildcard: bool = False,
70
+ allow_underscore: bool = False,
71
+ allow_trailing_dot: bool = True,
72
+ ) -> ValidationResult:
73
+ """Validate a hostname (RFC 1123); a single label such as ``server1`` is allowed."""
74
+ return _validate_name(
75
+ value,
76
+ False,
77
+ allow_wildcard=allow_wildcard,
78
+ allow_underscore=allow_underscore,
79
+ allow_trailing_dot=allow_trailing_dot,
80
+ )
81
+
82
+
83
+ def validate_fqdn(
84
+ value: Any,
85
+ *,
86
+ allow_wildcard: bool = False,
87
+ allow_underscore: bool = False,
88
+ allow_trailing_dot: bool = True,
89
+ ) -> ValidationResult:
90
+ """Validate a fully qualified domain name with at least two labels, e.g. ``www.example.com``."""
91
+ return _validate_name(
92
+ value,
93
+ True,
94
+ allow_wildcard=allow_wildcard,
95
+ allow_underscore=allow_underscore,
96
+ allow_trailing_dot=allow_trailing_dot,
97
+ )
98
+
99
+
100
+ def validate_host(
101
+ value: Any,
102
+ *,
103
+ version: Version = "any",
104
+ allow_zone_id: bool = False,
105
+ allow_unspecified: bool = True,
106
+ allow_private: bool = True,
107
+ allow_single_label: bool = True,
108
+ allow_wildcard: bool = False,
109
+ allow_underscore: bool = False,
110
+ allow_trailing_dot: bool = True,
111
+ ) -> ValidationResult:
112
+ """Validate a hostname/FQDN or an IP address, as typed into a "server" field."""
113
+ check_version(version)
114
+ check_bool("allow_single_label", allow_single_label)
115
+ ip_opts = dict(
116
+ version=version,
117
+ allow_zone_id=allow_zone_id,
118
+ allow_unspecified=allow_unspecified,
119
+ allow_private=allow_private,
120
+ )
121
+ name_opts = dict(
122
+ allow_wildcard=allow_wildcard,
123
+ allow_underscore=allow_underscore,
124
+ allow_trailing_dot=allow_trailing_dot,
125
+ )
126
+ for name, v in {**ip_opts, **name_opts}.items():
127
+ if name != "version":
128
+ check_bool(name, v)
129
+
130
+ common = run(lambda: check_common(value))
131
+ if not common.valid:
132
+ return common
133
+ if ":" in value or all(c in _IP_CHARS for c in value):
134
+ return validate_ip_address(value, **ip_opts) # type: ignore[arg-type]
135
+ if allow_single_label:
136
+ return validate_hostname(value, **name_opts)
137
+ return validate_fqdn(value, **name_opts)
@@ -0,0 +1,64 @@
1
+ """IP address validators (SPEC §3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Sequence
6
+
7
+ from ._addr import Address, AddressError, check_version_matches, in_network, is_private, parse_ip, parse_subnet_list
8
+ from ._core import Invalid, ValidationResult, Version, check_bool, check_common, check_version, run
9
+
10
+
11
+ def check_ip(value: str, version: Any, allow_zone_id: bool) -> Address:
12
+ """Checks 1-4 of SPEC §3.1 on a value that already passed the common checks."""
13
+ try:
14
+ addr = parse_ip(value)
15
+ except AddressError as e:
16
+ raise Invalid(f"ip.{e.kind}") from None
17
+ check_version_matches("ip", version, addr.version)
18
+ if addr.zone is not None and not allow_zone_id:
19
+ raise Invalid("ip.zone_id_not_allowed")
20
+ return addr
21
+
22
+
23
+ def validate_ip_address(
24
+ value: Any,
25
+ *,
26
+ version: Version = "any",
27
+ allow_zone_id: bool = False,
28
+ allow_unspecified: bool = True,
29
+ allow_private: bool = True,
30
+ ) -> ValidationResult:
31
+ """Validate an IPv4 or IPv6 address, e.g. ``192.0.2.1`` or ``2001:db8::1``."""
32
+ check_version(version)
33
+ check_bool("allow_zone_id", allow_zone_id)
34
+ check_bool("allow_unspecified", allow_unspecified)
35
+ check_bool("allow_private", allow_private)
36
+
37
+ def check() -> None:
38
+ addr = check_ip(check_common(value), version, allow_zone_id)
39
+ if not allow_unspecified and addr.value == 0:
40
+ raise Invalid("ip.unspecified")
41
+ if not allow_private and is_private(addr):
42
+ raise Invalid("ip.private")
43
+
44
+ return run(check)
45
+
46
+
47
+ def validate_private_ip_address(
48
+ value: Any,
49
+ *,
50
+ version: Version = "any",
51
+ allow_zone_id: bool = False,
52
+ additional_ranges: Sequence[str] = (),
53
+ ) -> ValidationResult:
54
+ """Validate that an address is private (RFC 1918 / RFC 4193) or in ``additional_ranges``."""
55
+ check_version(version)
56
+ check_bool("allow_zone_id", allow_zone_id)
57
+ extra = parse_subnet_list("additional_ranges", additional_ranges)
58
+
59
+ def check() -> None:
60
+ addr = check_ip(check_common(value), version, allow_zone_id)
61
+ if not is_private(addr) and not any(in_network(addr.version, addr.value, n) for n in extra):
62
+ raise Invalid("ip.not_private")
63
+
64
+ return run(check)
@@ -0,0 +1,48 @@
1
+ """IP range validator (SPEC §5)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Tuple
6
+
7
+ from ._addr import Address, AddressError, check_version_matches, parse_ip
8
+ from ._core import Invalid, ValidationResult, Version, check_bool, check_common, check_version, run
9
+
10
+
11
+ def _range_address(s: str, position: str) -> Address:
12
+ try:
13
+ addr = parse_ip(s)
14
+ except AddressError:
15
+ raise Invalid("range.invalid_address", {"position": position}) from None
16
+ if addr.zone is not None:
17
+ raise Invalid("range.invalid_address", {"position": position})
18
+ return addr
19
+
20
+
21
+ def parse_range(value: str, *, version: Any = "any", allow_single: bool = False) -> Tuple[Address, Address]:
22
+ """Checks 1-6 of SPEC §5.1 on a value that already passed the common checks."""
23
+ dashes = value.count("-")
24
+ if dashes > 1 or (dashes == 0 and not allow_single):
25
+ raise Invalid("range.invalid")
26
+ if dashes == 0:
27
+ start_s = end_s = value
28
+ else:
29
+ start_s, _, end_s = value.partition("-")
30
+ start_s, end_s = start_s.strip(" "), end_s.strip(" ")
31
+ if start_s == "" or end_s == "":
32
+ raise Invalid("range.invalid")
33
+
34
+ start = _range_address(start_s, "start")
35
+ end = _range_address(end_s, "end")
36
+ if start.version != end.version:
37
+ raise Invalid("range.mixed_versions")
38
+ check_version_matches("range", version, start.version)
39
+ if start.value > end.value:
40
+ raise Invalid("range.descending")
41
+ return start, end
42
+
43
+
44
+ def validate_ip_range(value: Any, *, version: Version = "any", allow_single: bool = False) -> ValidationResult:
45
+ """Validate an IP range such as ``10.0.0.1-10.0.0.50``."""
46
+ check_version(version)
47
+ check_bool("allow_single", allow_single)
48
+ return run(lambda: parse_range(check_common(value), version=version, allow_single=allow_single))
@@ -0,0 +1,37 @@
1
+ """MAC address validator (SPEC §9)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Sequence
7
+
8
+ from ._core import Invalid, ValidationResult, check_common, run
9
+
10
+ _H = "[0-9A-Fa-f]"
11
+ MAC_FORMATS = {
12
+ "colon": re.compile(f"{_H}{{2}}(?::{_H}{{2}}){{5}}"),
13
+ "hyphen": re.compile(f"{_H}{{2}}(?:-{_H}{{2}}){{5}}"),
14
+ "dot": re.compile(f"{_H}{{4}}(?:\\.{_H}{{4}}){{2}}"),
15
+ "bare": re.compile(f"{_H}{{12}}"),
16
+ }
17
+ DEFAULT_MAC_FORMATS = ("colon", "hyphen", "dot")
18
+
19
+
20
+ def validate_mac_address(value: Any, *, formats: Sequence[str] = DEFAULT_MAC_FORMATS) -> ValidationResult:
21
+ """Validate a MAC address such as ``00:1a:2b:3c:4d:5e``. ``formats`` limits the accepted notations."""
22
+ if isinstance(formats, (str, bytes)) or not isinstance(formats, Sequence) or len(formats) == 0:
23
+ raise TypeError("formats must be a non-empty list")
24
+ for f in formats:
25
+ if f not in MAC_FORMATS:
26
+ raise ValueError(f"unknown MAC format {f!r}; expected one of {sorted(MAC_FORMATS)}")
27
+
28
+ def check() -> None:
29
+ s = check_common(value)
30
+ for name, pattern in MAC_FORMATS.items():
31
+ if pattern.fullmatch(s):
32
+ if name not in formats:
33
+ raise Invalid("mac.format_not_allowed", {"format": name})
34
+ return
35
+ raise Invalid("mac.invalid")
36
+
37
+ return run(check)
@@ -0,0 +1,71 @@
1
+ """Port validators (SPEC §8)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+ from ._core import Invalid, ValidationResult, check_bool, check_common, is_ascii_digits, run
8
+
9
+ PORT_MAX = 65535
10
+
11
+
12
+ def _check_port(s: str, allow_zero: bool, position: Optional[str] = None) -> int:
13
+ extra: Dict[str, Any] = {"position": position} if position else {}
14
+ if not is_ascii_digits(s):
15
+ raise Invalid("port.invalid", extra)
16
+ if len(s) > 1 and s[0] == "0":
17
+ raise Invalid("port.leading_zero", extra)
18
+ minimum = 0 if allow_zero else 1
19
+ n = int(s) if len(s) <= 5 else PORT_MAX + 1
20
+ if not (minimum <= n <= PORT_MAX):
21
+ raise Invalid("port.out_of_range", {"min": minimum, "max": PORT_MAX, **extra})
22
+ return n
23
+
24
+
25
+ def _check_port_range(s: str, allow_zero: bool) -> None:
26
+ if s.count("-") != 1:
27
+ raise Invalid("port_range.invalid")
28
+ low_s, _, high_s = s.partition("-")
29
+ low_s, high_s = low_s.strip(" "), high_s.strip(" ")
30
+ if low_s == "" or high_s == "":
31
+ raise Invalid("port_range.invalid")
32
+ low = _check_port(low_s, allow_zero, "start")
33
+ high = _check_port(high_s, allow_zero, "end")
34
+ if low > high:
35
+ raise Invalid("port_range.descending")
36
+
37
+
38
+ def validate_port(value: Any, *, allow_zero: bool = False) -> ValidationResult:
39
+ """Validate a TCP/UDP port number such as ``443``."""
40
+ check_bool("allow_zero", allow_zero)
41
+ return run(lambda: _check_port(check_common(value), allow_zero))
42
+
43
+
44
+ def validate_port_range(value: Any, *, allow_zero: bool = False) -> ValidationResult:
45
+ """Validate a port range such as ``8000-8080``."""
46
+ check_bool("allow_zero", allow_zero)
47
+ return run(lambda: _check_port_range(check_common(value), allow_zero))
48
+
49
+
50
+ def validate_port_list(value: Any, *, allow_zero: bool = False, allow_ranges: bool = True) -> ValidationResult:
51
+ """Validate a comma-separated list of ports and ranges such as ``80, 443, 8000-8080``."""
52
+ check_bool("allow_zero", allow_zero)
53
+ check_bool("allow_ranges", allow_ranges)
54
+
55
+ def check() -> None:
56
+ for index, raw in enumerate(check_common(value).split(",")):
57
+ item = raw.strip(" ")
58
+ if item == "":
59
+ raise Invalid("port_list.empty_item", {"index": index})
60
+ is_range = "-" in item
61
+ if is_range and not allow_ranges:
62
+ raise Invalid("port_list.range_not_allowed", {"index": index})
63
+ try:
64
+ if is_range:
65
+ _check_port_range(item, allow_zero)
66
+ else:
67
+ _check_port(item, allow_zero)
68
+ except Invalid as e:
69
+ raise Invalid("port_list.invalid_item", {"index": index, "reason": e.code}) from None
70
+
71
+ return run(check)
File without changes
@@ -0,0 +1,84 @@
1
+ """Validators that compare a value against a list of subnets (SPEC §6)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Sequence
6
+
7
+ from ._addr import in_network, parse_subnet, parse_subnet_list
8
+ from ._core import Invalid, ValidationResult, Version, check_common, check_version, run
9
+ from .ip import check_ip
10
+ from .ip_range import parse_range
11
+
12
+
13
+ def _entries(subnets: Sequence[str]) -> list:
14
+ return list(zip(subnets, parse_subnet_list("subnets", subnets)))
15
+
16
+
17
+ def validate_ip_in_subnets(value: Any, *, subnets: Sequence[str], version: Version = "any") -> ValidationResult:
18
+ """Validate that an address is inside at least one of ``subnets``."""
19
+ check_version(version)
20
+ entries = _entries(subnets)
21
+
22
+ def check() -> None:
23
+ addr = check_ip(check_common(value), version, False)
24
+ if not any(in_network(addr.version, addr.value, net) for _, net in entries):
25
+ raise Invalid("ip.not_in_subnets")
26
+
27
+ return run(check)
28
+
29
+
30
+ def validate_ip_not_in_subnets(value: Any, *, subnets: Sequence[str], version: Version = "any") -> ValidationResult:
31
+ """Validate that an address is in none of ``subnets``."""
32
+ check_version(version)
33
+ entries = _entries(subnets)
34
+
35
+ def check() -> None:
36
+ addr = check_ip(check_common(value), version, False)
37
+ for text, net in entries:
38
+ if in_network(addr.version, addr.value, net):
39
+ raise Invalid("ip.in_subnet", {"subnet": text})
40
+
41
+ return run(check)
42
+
43
+
44
+ def validate_subnet_in_subnets(value: Any, *, subnets: Sequence[str], version: Version = "any") -> ValidationResult:
45
+ """Validate that a subnet lies entirely inside one of ``subnets``."""
46
+ check_version(version)
47
+ entries = _entries(subnets)
48
+
49
+ def check() -> None:
50
+ net = parse_subnet(check_common(value), version=version)
51
+ if not any(
52
+ e.version == net.version and e.first <= net.first and net.last <= e.last for _, e in entries
53
+ ):
54
+ raise Invalid("subnet.not_in_subnets")
55
+
56
+ return run(check)
57
+
58
+
59
+ def validate_subnet_not_overlapping(value: Any, *, subnets: Sequence[str], version: Version = "any") -> ValidationResult:
60
+ """Validate that a subnet shares no address with any of ``subnets``."""
61
+ check_version(version)
62
+ entries = _entries(subnets)
63
+
64
+ def check() -> None:
65
+ net = parse_subnet(check_common(value), version=version)
66
+ for text, e in entries:
67
+ if e.version == net.version and net.first <= e.last and e.first <= net.last:
68
+ raise Invalid("subnet.overlaps", {"subnet": text})
69
+
70
+ return run(check)
71
+
72
+
73
+ def validate_ip_range_not_overlapping(value: Any, *, subnets: Sequence[str], version: Version = "any") -> ValidationResult:
74
+ """Validate that an IP range shares no address with any of ``subnets``."""
75
+ check_version(version)
76
+ entries = _entries(subnets)
77
+
78
+ def check() -> None:
79
+ start, end = parse_range(check_common(value), version=version)
80
+ for text, e in entries:
81
+ if e.version == start.version and start.value <= e.last and e.first <= end.value:
82
+ raise Invalid("range.overlaps", {"subnet": text})
83
+
84
+ return run(check)
@@ -0,0 +1,72 @@
1
+ """Netmask and subnet validators (SPEC §4)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Sequence
6
+
7
+ from ._addr import PRIVATE_NETWORKS, AddressError, netmask_prefix, parse_subnet, parse_subnet_list
8
+ from ._core import Invalid, ValidationResult, Version, check_bool, check_common, check_version, run
9
+
10
+
11
+ def validate_netmask(value: Any) -> ValidationResult:
12
+ """Validate a dotted IPv4 netmask such as ``255.255.255.0``."""
13
+
14
+ def check() -> None:
15
+ try:
16
+ netmask_prefix(check_common(value))
17
+ except AddressError:
18
+ raise Invalid("netmask.invalid") from None
19
+ except ValueError:
20
+ raise Invalid("netmask.not_contiguous") from None
21
+
22
+ return run(check)
23
+
24
+
25
+ def validate_subnet(
26
+ value: Any,
27
+ *,
28
+ version: Version = "any",
29
+ allow_netmask: bool = True,
30
+ allow_host_bits: bool = True,
31
+ ) -> ValidationResult:
32
+ """Validate a subnet: ``10.0.0.0/8``, ``10.0.0.0/255.0.0.0``, ``10.0.0.0 255.0.0.0`` or ``2001:db8::/32``."""
33
+ check_version(version)
34
+ check_bool("allow_netmask", allow_netmask)
35
+ check_bool("allow_host_bits", allow_host_bits)
36
+ return run(
37
+ lambda: parse_subnet(
38
+ check_common(value),
39
+ version=version,
40
+ allow_netmask=allow_netmask,
41
+ allow_host_bits=allow_host_bits,
42
+ )
43
+ )
44
+
45
+
46
+ def validate_private_subnet(
47
+ value: Any,
48
+ *,
49
+ version: Version = "any",
50
+ allow_netmask: bool = True,
51
+ allow_host_bits: bool = True,
52
+ additional_ranges: Sequence[str] = (),
53
+ ) -> ValidationResult:
54
+ """Validate that a whole subnet lies inside one private range or one of ``additional_ranges``."""
55
+ check_version(version)
56
+ check_bool("allow_netmask", allow_netmask)
57
+ check_bool("allow_host_bits", allow_host_bits)
58
+ allowed = PRIVATE_NETWORKS + parse_subnet_list("additional_ranges", additional_ranges)
59
+
60
+ def check() -> None:
61
+ net = parse_subnet(
62
+ check_common(value),
63
+ version=version,
64
+ allow_netmask=allow_netmask,
65
+ allow_host_bits=allow_host_bits,
66
+ )
67
+ if not any(
68
+ r.version == net.version and r.first <= net.first and net.last <= r.last for r in allowed
69
+ ):
70
+ raise Invalid("subnet.not_private")
71
+
72
+ return run(check)
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.5
2
+ Name: network-validators
3
+ Version: 0.1.0rc1
4
+ Summary: Validators for IP addresses, subnets, ranges, hostnames, ports and MAC addresses, with stable error codes.
5
+ Project-URL: Homepage, https://github.com/icmp-type0/network-validators-py
6
+ Project-URL: Specification, https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md
7
+ Project-URL: Issues, https://github.com/icmp-type0/network-validators-py/issues
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: cidr,fqdn,hostname,ip,ipv4,ipv6,mac,port,subnet,validation
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: System :: Networking
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest>=8; extra == 'test'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # network-validators
28
+
29
+ Validators for network-related input: IP addresses, subnets, IP ranges, hostnames, ports and MAC addresses. Each check returns a stable error code, not a message, so you write the messages your users see.
30
+
31
+ - No dependencies. Python 3.11+.
32
+ - Strict about common traps: IPv4 leading zeros (CVE-2021-29921), non-ASCII digits, surrounding whitespace, IPv6 zone IDs.
33
+ - Behaves the same as the [TypeScript package](https://www.npmjs.com/package/network-validators). Both follow one [specification](https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md) and run the same test cases.
34
+
35
+ > Status: 0.1.0 release candidate. Changes are listed in the [changelog](https://github.com/icmp-type0/network-validators-py/blob/main/CHANGELOG.md).
36
+
37
+ ## Install
38
+
39
+ ```sh
40
+ pip install --pre network-validators # --pre while 0.1.0 is a release candidate
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ Every validator has two forms: `validate_*` returns a result, and `is_*` returns a `bool`.
46
+
47
+ ```python
48
+ from network_validators import is_host, validate_subnet
49
+
50
+ r = validate_subnet("10.0.0.5/24", allow_host_bits=False)
51
+ r.valid # False
52
+ r.code # "subnet.host_bits_set"
53
+ r.details # {"network": "10.0.0.0/24"}
54
+
55
+ if r: # a result is truthy only when valid
56
+ ...
57
+
58
+ is_host("example.com") # True
59
+ ```
60
+
61
+ Map codes to your own messages:
62
+
63
+ ```python
64
+ MESSAGES = {
65
+ "empty": "This field is required.",
66
+ "subnet.host_bits_set": "Did you mean {network}?",
67
+ "port.out_of_range": "Port must be between {min} and {max}.",
68
+ }
69
+
70
+ r = validate_subnet(value, allow_host_bits=False)
71
+ if not r:
72
+ message = MESSAGES.get(r.code, "Invalid value.").format(**r.details)
73
+ ```
74
+
75
+ Empty strings fail with code `empty`. If a field is optional, skip validation when it's empty.
76
+
77
+ Invalid options, such as `version=5`, an unknown option name or a bad entry in `subnets`, raise `TypeError` or `ValueError` instead of returning a result.
78
+
79
+ ## Validators
80
+
81
+ | Function | Accepts | Options |
82
+ |---|---|---|
83
+ | `validate_ip_address` | `192.0.2.1`, `2001:db8::1` | `version`, `allow_zone_id`, `allow_unspecified`, `allow_private` |
84
+ | `validate_private_ip_address` | `10.0.0.1`, `fd00::1` | `version`, `allow_zone_id`, `additional_ranges` |
85
+ | `validate_netmask` | `255.255.255.0` | |
86
+ | `validate_subnet` | `10.0.0.0/8`, `10.0.0.0 255.0.0.0`, `2001:db8::/32` | `version`, `allow_netmask`, `allow_host_bits` |
87
+ | `validate_private_subnet` | `192.168.1.0/24` | as `validate_subnet`, plus `additional_ranges` |
88
+ | `validate_ip_range` | `10.0.0.1-10.0.0.50` | `version`, `allow_single` |
89
+ | `validate_ip_in_subnets` / `validate_ip_not_in_subnets` | an IP address | `subnets` (required), `version` |
90
+ | `validate_subnet_in_subnets` / `validate_subnet_not_overlapping` | a subnet | `subnets` (required), `version` |
91
+ | `validate_ip_range_not_overlapping` | an IP range | `subnets` (required), `version` |
92
+ | `validate_hostname` / `validate_fqdn` | `server1` / `www.example.com` | `allow_wildcard`, `allow_underscore`, `allow_trailing_dot` |
93
+ | `validate_host` | a hostname, FQDN or IP address | IP and name options, plus `allow_single_label` |
94
+ | `validate_port` / `validate_port_range` | `443` / `8000-8080` | `allow_zero` |
95
+ | `validate_port_list` | `80, 443, 8000-8080` | `allow_zero`, `allow_ranges` |
96
+ | `validate_mac_address` | `00:1a:2b:3c:4d:5e`, `001a.2b3c.4d5e` | `formats` |
97
+
98
+ `version` is `4`, `6` or `"any"` (the default).
99
+
100
+ The [specification](https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md) gives each validator's exact rules and the order of its checks. All error codes are listed in [codes.json](https://github.com/icmp-type0/network-validators-py/blob/main/spec/codes.json).
101
+
102
+ ## License
103
+
104
+ MIT
@@ -0,0 +1,15 @@
1
+ network_validators/__init__.py,sha256=kqxf4K3S68nxuFwr8HoXyQSz3AkWmWLYMvGfZWzvJU8,3245
2
+ network_validators/_addr.py,sha256=L92s5I4w39OFMcRIVNvBXG_fe8FaZfs4oYYKOjEjFrY,7537
3
+ network_validators/_core.py,sha256=zK2GOaMDtPWB2tFfOGGXqNW2AUyQmzyzdS2GIbfNtws,2213
4
+ network_validators/domain.py,sha256=hXhioHRXzngvbjSMOkwl-85zB43W7U0k08ZckgRtPxE,4361
5
+ network_validators/ip.py,sha256=etIiUMVyEMnOXMI8xPtg0g8wYYqqdlPj4W7inGUW9dc,2237
6
+ network_validators/ip_range.py,sha256=o9ou0lw5ZzCy3VD1L2QDkOKW0ZHkXU8WwXvlvZcZf-s,1846
7
+ network_validators/mac.py,sha256=ERxwLU0Tc9bX8AHDfLq_fHvnIC6M9JirmhZdLmerEYs,1360
8
+ network_validators/port.py,sha256=MRsdr0ds20qjiZ83fAiaBIKEQarq5LYv0nzB2RY1zLs,2756
9
+ network_validators/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ network_validators/relations.py,sha256=5qyGyaffipI3Kf9hvUZchqXzgBBwg_Ho8ap4A-XQExU,3160
11
+ network_validators/subnet.py,sha256=kfMzdvlGQM2i8i7ovA2tV-vgbFZGaJmV_jNJoP5nbtA,2289
12
+ network_validators-0.1.0rc1.dist-info/METADATA,sha256=_dx2P6B8GFWbM8TJF8oooJqj9iasAfLrlplPoCqAiCM,4866
13
+ network_validators-0.1.0rc1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ network_validators-0.1.0rc1.dist-info/licenses/LICENSE,sha256=MpxeIrnEXVK8DLQGfs9iqW7ap7RPCdHsttEtXW5rbSY,1067
15
+ network_validators-0.1.0rc1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 icmp-type0
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.