network-validators 0.1.0__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.
- network_validators/__init__.py +147 -0
- network_validators/_addr.py +255 -0
- network_validators/_codes.py +60 -0
- network_validators/_core.py +81 -0
- network_validators/domain.py +137 -0
- network_validators/ip.py +64 -0
- network_validators/ip_range.py +48 -0
- network_validators/mac.py +37 -0
- network_validators/port.py +71 -0
- network_validators/py.typed +0 -0
- network_validators/relations.py +84 -0
- network_validators/subnet.py +72 -0
- network_validators-0.1.0.dist-info/METADATA +108 -0
- network_validators-0.1.0.dist-info/RECORD +16 -0
- network_validators-0.1.0.dist-info/WHEEL +4 -0
- network_validators-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,147 @@
|
|
|
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 ._codes import ERROR_CODES, ErrorCode
|
|
13
|
+
from ._core import ValidationResult
|
|
14
|
+
from .domain import validate_fqdn, validate_host, validate_hostname
|
|
15
|
+
from .ip import validate_ip_address, validate_private_ip_address
|
|
16
|
+
from .ip_range import validate_ip_range
|
|
17
|
+
from .mac import validate_mac_address
|
|
18
|
+
from .port import validate_port, validate_port_list, validate_port_range
|
|
19
|
+
from .relations import (
|
|
20
|
+
validate_ip_in_subnets,
|
|
21
|
+
validate_ip_not_in_subnets,
|
|
22
|
+
validate_ip_range_not_overlapping,
|
|
23
|
+
validate_subnet_in_subnets,
|
|
24
|
+
validate_subnet_not_overlapping,
|
|
25
|
+
)
|
|
26
|
+
from .subnet import validate_netmask, validate_private_subnet, validate_subnet
|
|
27
|
+
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
SPEC_VERSION = "0.1.0"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def is_ip_address(value: Any, **options: Any) -> bool:
|
|
33
|
+
return validate_ip_address(value, **options).valid
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def is_private_ip_address(value: Any, **options: Any) -> bool:
|
|
37
|
+
return validate_private_ip_address(value, **options).valid
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def is_netmask(value: Any) -> bool:
|
|
41
|
+
return validate_netmask(value).valid
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def is_subnet(value: Any, **options: Any) -> bool:
|
|
45
|
+
return validate_subnet(value, **options).valid
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def is_private_subnet(value: Any, **options: Any) -> bool:
|
|
49
|
+
return validate_private_subnet(value, **options).valid
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_ip_range(value: Any, **options: Any) -> bool:
|
|
53
|
+
return validate_ip_range(value, **options).valid
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def is_ip_in_subnets(value: Any, **options: Any) -> bool:
|
|
57
|
+
return validate_ip_in_subnets(value, **options).valid
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def is_ip_not_in_subnets(value: Any, **options: Any) -> bool:
|
|
61
|
+
return validate_ip_not_in_subnets(value, **options).valid
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def is_subnet_in_subnets(value: Any, **options: Any) -> bool:
|
|
65
|
+
return validate_subnet_in_subnets(value, **options).valid
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_subnet_not_overlapping(value: Any, **options: Any) -> bool:
|
|
69
|
+
return validate_subnet_not_overlapping(value, **options).valid
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def is_ip_range_not_overlapping(value: Any, **options: Any) -> bool:
|
|
73
|
+
return validate_ip_range_not_overlapping(value, **options).valid
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_hostname(value: Any, **options: Any) -> bool:
|
|
77
|
+
return validate_hostname(value, **options).valid
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def is_fqdn(value: Any, **options: Any) -> bool:
|
|
81
|
+
return validate_fqdn(value, **options).valid
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def is_host(value: Any, **options: Any) -> bool:
|
|
85
|
+
return validate_host(value, **options).valid
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def is_port(value: Any, **options: Any) -> bool:
|
|
89
|
+
return validate_port(value, **options).valid
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def is_port_range(value: Any, **options: Any) -> bool:
|
|
93
|
+
return validate_port_range(value, **options).valid
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def is_port_list(value: Any, **options: Any) -> bool:
|
|
97
|
+
return validate_port_list(value, **options).valid
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def is_mac_address(value: Any, **options: Any) -> bool:
|
|
101
|
+
return validate_mac_address(value, **options).valid
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# Listed explicitly: type checkers can't read a computed __all__, and under
|
|
105
|
+
# mypy --strict they would treat every validator as not exported.
|
|
106
|
+
__all__ = [
|
|
107
|
+
"ERROR_CODES",
|
|
108
|
+
"ErrorCode",
|
|
109
|
+
"SPEC_VERSION",
|
|
110
|
+
"ValidationResult",
|
|
111
|
+
"is_fqdn",
|
|
112
|
+
"is_host",
|
|
113
|
+
"is_hostname",
|
|
114
|
+
"is_ip_address",
|
|
115
|
+
"is_ip_in_subnets",
|
|
116
|
+
"is_ip_not_in_subnets",
|
|
117
|
+
"is_ip_range",
|
|
118
|
+
"is_ip_range_not_overlapping",
|
|
119
|
+
"is_mac_address",
|
|
120
|
+
"is_netmask",
|
|
121
|
+
"is_port",
|
|
122
|
+
"is_port_list",
|
|
123
|
+
"is_port_range",
|
|
124
|
+
"is_private_ip_address",
|
|
125
|
+
"is_private_subnet",
|
|
126
|
+
"is_subnet",
|
|
127
|
+
"is_subnet_in_subnets",
|
|
128
|
+
"is_subnet_not_overlapping",
|
|
129
|
+
"validate_fqdn",
|
|
130
|
+
"validate_host",
|
|
131
|
+
"validate_hostname",
|
|
132
|
+
"validate_ip_address",
|
|
133
|
+
"validate_ip_in_subnets",
|
|
134
|
+
"validate_ip_not_in_subnets",
|
|
135
|
+
"validate_ip_range",
|
|
136
|
+
"validate_ip_range_not_overlapping",
|
|
137
|
+
"validate_mac_address",
|
|
138
|
+
"validate_netmask",
|
|
139
|
+
"validate_port",
|
|
140
|
+
"validate_port_list",
|
|
141
|
+
"validate_port_range",
|
|
142
|
+
"validate_private_ip_address",
|
|
143
|
+
"validate_private_subnet",
|
|
144
|
+
"validate_subnet",
|
|
145
|
+
"validate_subnet_in_subnets",
|
|
146
|
+
"validate_subnet_not_overlapping",
|
|
147
|
+
]
|
|
@@ -0,0 +1,255 @@
|
|
|
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, Dict, List, Literal, Optional, Sequence
|
|
9
|
+
|
|
10
|
+
from ._codes import ErrorCode
|
|
11
|
+
from ._core import Invalid, is_ascii_digits
|
|
12
|
+
|
|
13
|
+
_HEX = frozenset("0123456789abcdefABCDEF")
|
|
14
|
+
_ZONE_CHARS = frozenset(string.ascii_letters + string.digits + "._~-")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AddressError(Exception):
|
|
18
|
+
"""kind is 'invalid' or 'leading_zero'."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, kind: Literal["invalid", "leading_zero"] = "invalid") -> None:
|
|
21
|
+
super().__init__(kind)
|
|
22
|
+
self.kind = kind
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Address:
|
|
27
|
+
version: int
|
|
28
|
+
value: int
|
|
29
|
+
zone: Optional[str] = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Network:
|
|
34
|
+
version: int
|
|
35
|
+
address: int # as written, host bits included
|
|
36
|
+
prefix: int
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def bits(self) -> int:
|
|
40
|
+
return 32 if self.version == 4 else 128
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def mask(self) -> int:
|
|
44
|
+
return ((1 << self.prefix) - 1) << (self.bits - self.prefix)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def first(self) -> int:
|
|
48
|
+
return self.address & self.mask
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def last(self) -> int:
|
|
52
|
+
return self.first | (~self.mask & ((1 << self.bits) - 1))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# --- parsing -----------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_ipv4(s: str) -> int:
|
|
59
|
+
parts = s.split(".")
|
|
60
|
+
if len(parts) != 4:
|
|
61
|
+
raise AddressError()
|
|
62
|
+
value = 0
|
|
63
|
+
leading_zero = False
|
|
64
|
+
for part in parts:
|
|
65
|
+
if not (1 <= len(part) <= 3) or not is_ascii_digits(part):
|
|
66
|
+
raise AddressError()
|
|
67
|
+
n = int(part)
|
|
68
|
+
if n > 255:
|
|
69
|
+
raise AddressError()
|
|
70
|
+
if len(part) > 1 and part[0] == "0":
|
|
71
|
+
leading_zero = True
|
|
72
|
+
value = (value << 8) | n
|
|
73
|
+
if leading_zero:
|
|
74
|
+
raise AddressError("leading_zero")
|
|
75
|
+
return value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def parse_ipv6(s: str) -> Address:
|
|
79
|
+
zone: Optional[str] = None
|
|
80
|
+
if "%" in s:
|
|
81
|
+
s, zone = s.split("%", 1)
|
|
82
|
+
if zone == "" or any(c not in _ZONE_CHARS for c in zone):
|
|
83
|
+
raise AddressError()
|
|
84
|
+
|
|
85
|
+
if "." in s:
|
|
86
|
+
idx = s.rfind(":")
|
|
87
|
+
if idx == -1:
|
|
88
|
+
raise AddressError()
|
|
89
|
+
try:
|
|
90
|
+
v4 = parse_ipv4(s[idx + 1 :])
|
|
91
|
+
except AddressError:
|
|
92
|
+
raise AddressError() from None
|
|
93
|
+
s = f"{s[: idx + 1]}{v4 >> 16:x}:{v4 & 0xFFFF:x}"
|
|
94
|
+
|
|
95
|
+
if s.count("::") > 1:
|
|
96
|
+
raise AddressError()
|
|
97
|
+
if "::" in s:
|
|
98
|
+
head, tail = s.split("::", 1)
|
|
99
|
+
h = head.split(":") if head else []
|
|
100
|
+
t = tail.split(":") if tail else []
|
|
101
|
+
if len(h) + len(t) > 7:
|
|
102
|
+
raise AddressError()
|
|
103
|
+
groups = h + ["0"] * (8 - len(h) - len(t)) + t
|
|
104
|
+
else:
|
|
105
|
+
groups = s.split(":")
|
|
106
|
+
if len(groups) != 8:
|
|
107
|
+
raise AddressError()
|
|
108
|
+
|
|
109
|
+
value = 0
|
|
110
|
+
for g in groups:
|
|
111
|
+
if not (1 <= len(g) <= 4) or any(c not in _HEX for c in g):
|
|
112
|
+
raise AddressError()
|
|
113
|
+
value = (value << 16) | int(g, 16)
|
|
114
|
+
return Address(6, value, zone)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def parse_ip(s: str) -> Address:
|
|
118
|
+
"""SPEC §2.3. Raises AddressError."""
|
|
119
|
+
if ":" in s:
|
|
120
|
+
return parse_ipv6(s)
|
|
121
|
+
return Address(4, parse_ipv4(s))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def netmask_prefix(s: str) -> int:
|
|
125
|
+
"""Prefix length of a dotted IPv4 netmask. Raises AddressError or ValueError (not contiguous)."""
|
|
126
|
+
value = parse_ipv4(s)
|
|
127
|
+
inverted = ~value & 0xFFFFFFFF
|
|
128
|
+
if inverted & (inverted + 1):
|
|
129
|
+
raise ValueError("netmask not contiguous")
|
|
130
|
+
return 32 - inverted.bit_length()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# --- formatting (SPEC §2.4) ----------------------------------------------------
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def format_address(version: int, value: int) -> str:
|
|
137
|
+
if version == 4:
|
|
138
|
+
return ".".join(str((value >> shift) & 0xFF) for shift in (24, 16, 8, 0))
|
|
139
|
+
groups = [(value >> (16 * (7 - i))) & 0xFFFF for i in range(8)]
|
|
140
|
+
best_start, best_len = -1, 0
|
|
141
|
+
i = 0
|
|
142
|
+
while i < 8:
|
|
143
|
+
if groups[i] == 0:
|
|
144
|
+
j = i
|
|
145
|
+
while j < 8 and groups[j] == 0:
|
|
146
|
+
j += 1
|
|
147
|
+
if j - i > best_len:
|
|
148
|
+
best_start, best_len = i, j - i
|
|
149
|
+
i = j
|
|
150
|
+
else:
|
|
151
|
+
i += 1
|
|
152
|
+
hexes = [f"{g:x}" for g in groups]
|
|
153
|
+
if best_len < 2:
|
|
154
|
+
return ":".join(hexes)
|
|
155
|
+
head = ":".join(hexes[:best_start])
|
|
156
|
+
tail = ":".join(hexes[best_start + best_len :])
|
|
157
|
+
return f"{head}::{tail}"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def format_network(net: Network) -> str:
|
|
161
|
+
return f"{format_address(net.version, net.first)}/{net.prefix}"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# --- subnets (SPEC §4.2) -------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
_WRONG_VERSION: Dict[str, ErrorCode] = {"ip": "ip.wrong_version", "subnet": "subnet.wrong_version", "range": "range.wrong_version"}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def check_version_matches(prefix: Literal["ip", "subnet", "range"], version: Any, actual: int) -> None:
|
|
171
|
+
if version != "any" and actual != version:
|
|
172
|
+
raise Invalid(_WRONG_VERSION[prefix], {"version": actual})
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def parse_subnet(
|
|
176
|
+
value: str,
|
|
177
|
+
*,
|
|
178
|
+
version: Any = "any",
|
|
179
|
+
allow_netmask: bool = True,
|
|
180
|
+
allow_host_bits: bool = True,
|
|
181
|
+
) -> Network:
|
|
182
|
+
"""Checks 1-7 of SPEC §4.2 on a value that already passed the common checks."""
|
|
183
|
+
if "/" in value:
|
|
184
|
+
left, _, right = value.partition("/")
|
|
185
|
+
if "/" in right:
|
|
186
|
+
raise Invalid("subnet.invalid")
|
|
187
|
+
elif value.count(" ") == 1:
|
|
188
|
+
left, _, right = value.partition(" ")
|
|
189
|
+
if "." not in right:
|
|
190
|
+
raise Invalid("subnet.invalid")
|
|
191
|
+
else:
|
|
192
|
+
raise Invalid("subnet.invalid")
|
|
193
|
+
if left == "" or right == "":
|
|
194
|
+
raise Invalid("subnet.invalid")
|
|
195
|
+
|
|
196
|
+
try:
|
|
197
|
+
addr = parse_ip(left)
|
|
198
|
+
except AddressError:
|
|
199
|
+
raise Invalid("subnet.invalid_address") from None
|
|
200
|
+
if addr.zone is not None:
|
|
201
|
+
raise Invalid("subnet.invalid_address")
|
|
202
|
+
check_version_matches("subnet", version, addr.version)
|
|
203
|
+
|
|
204
|
+
if "." in right:
|
|
205
|
+
if not allow_netmask:
|
|
206
|
+
raise Invalid("subnet.netmask_not_allowed")
|
|
207
|
+
if addr.version == 6:
|
|
208
|
+
raise Invalid("subnet.invalid_netmask")
|
|
209
|
+
try:
|
|
210
|
+
prefix = netmask_prefix(right)
|
|
211
|
+
except (AddressError, ValueError):
|
|
212
|
+
raise Invalid("subnet.invalid_netmask") from None
|
|
213
|
+
else:
|
|
214
|
+
max_prefix = 32 if addr.version == 4 else 128
|
|
215
|
+
if (
|
|
216
|
+
not is_ascii_digits(right)
|
|
217
|
+
or len(right) > 3
|
|
218
|
+
or (len(right) > 1 and right[0] == "0")
|
|
219
|
+
or int(right) > max_prefix
|
|
220
|
+
):
|
|
221
|
+
raise Invalid("subnet.invalid_prefix")
|
|
222
|
+
prefix = int(right)
|
|
223
|
+
|
|
224
|
+
net = Network(addr.version, addr.value, prefix)
|
|
225
|
+
if not allow_host_bits and net.address != net.first:
|
|
226
|
+
raise Invalid("subnet.host_bits_set", {"network": format_network(net)})
|
|
227
|
+
return net
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def parse_subnet_list(name: str, entries: Any) -> List[Network]:
|
|
231
|
+
"""SPEC §2.6. Raises TypeError/ValueError for bad configuration."""
|
|
232
|
+
if isinstance(entries, (str, bytes)) or not isinstance(entries, Sequence):
|
|
233
|
+
raise TypeError(f"{name} must be a list of subnet strings")
|
|
234
|
+
nets = []
|
|
235
|
+
for entry in entries:
|
|
236
|
+
if not isinstance(entry, str) or entry == "":
|
|
237
|
+
raise ValueError(f"{name}: invalid subnet {entry!r}")
|
|
238
|
+
try:
|
|
239
|
+
nets.append(parse_subnet(entry))
|
|
240
|
+
except Invalid as e:
|
|
241
|
+
raise ValueError(f"{name}: invalid subnet {entry!r} ({e.code})") from None
|
|
242
|
+
return nets
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
PRIVATE_NETWORKS = parse_subnet_list(
|
|
246
|
+
"PRIVATE_NETWORKS", ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def in_network(version: int, value: int, net: Network) -> bool:
|
|
251
|
+
return version == net.version and net.first <= value <= net.last
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def is_private(addr: Address) -> bool:
|
|
255
|
+
return any(in_network(addr.version, addr.value, n) for n in PRIVATE_NETWORKS)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Every error code a validator can return, from spec/codes.json. Generated by scripts/gen_codes.py; do not edit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal, get_args
|
|
6
|
+
|
|
7
|
+
ErrorCode = Literal[
|
|
8
|
+
"not_string", # Value is not a string.
|
|
9
|
+
"empty", # Value is an empty string.
|
|
10
|
+
"whitespace", # Value starts or ends with whitespace.
|
|
11
|
+
"ip.invalid", # Not a valid IP address.
|
|
12
|
+
"ip.leading_zero", # IPv4 address has a leading zero in an octet.
|
|
13
|
+
"ip.wrong_version", # IP address is not of the required version.
|
|
14
|
+
"ip.zone_id_not_allowed", # IPv6 zone ID is not allowed.
|
|
15
|
+
"ip.unspecified", # The unspecified address (0.0.0.0 or ::) is not allowed.
|
|
16
|
+
"ip.private", # Private IP addresses are not allowed.
|
|
17
|
+
"ip.not_private", # IP address must be private.
|
|
18
|
+
"ip.not_in_subnets", # IP address is not in any of the allowed subnets.
|
|
19
|
+
"ip.in_subnet", # IP address is in a forbidden subnet.
|
|
20
|
+
"netmask.invalid", # Not a valid IPv4 netmask.
|
|
21
|
+
"netmask.not_contiguous", # Netmask bits are not contiguous.
|
|
22
|
+
"subnet.invalid", # Not a valid subnet.
|
|
23
|
+
"subnet.invalid_address", # Subnet address is not a valid IP address.
|
|
24
|
+
"subnet.wrong_version", # Subnet is not of the required IP version.
|
|
25
|
+
"subnet.netmask_not_allowed", # Netmask notation is not allowed; use a prefix length.
|
|
26
|
+
"subnet.invalid_netmask", # Subnet netmask is not valid.
|
|
27
|
+
"subnet.invalid_prefix", # Subnet prefix length is not valid.
|
|
28
|
+
"subnet.host_bits_set", # Subnet address has host bits set.
|
|
29
|
+
"subnet.not_private", # Subnet must be private.
|
|
30
|
+
"subnet.not_in_subnets", # Subnet is not inside any of the allowed subnets.
|
|
31
|
+
"subnet.overlaps", # Subnet overlaps a forbidden subnet.
|
|
32
|
+
"range.invalid", # Not a valid IP range.
|
|
33
|
+
"range.invalid_address", # IP range contains an invalid address.
|
|
34
|
+
"range.mixed_versions", # IP range start and end are different IP versions.
|
|
35
|
+
"range.wrong_version", # IP range is not of the required IP version.
|
|
36
|
+
"range.descending", # IP range start is greater than its end.
|
|
37
|
+
"range.overlaps", # IP range overlaps a forbidden subnet.
|
|
38
|
+
"domain.trailing_dot_not_allowed", # Trailing dot is not allowed.
|
|
39
|
+
"domain.too_long", # Domain name is longer than 253 characters.
|
|
40
|
+
"domain.empty_label", # Domain name has an empty label.
|
|
41
|
+
"domain.invalid_wildcard", # Wildcard is only allowed as the entire leftmost label.
|
|
42
|
+
"domain.wildcard_not_allowed", # Wildcard domain names are not allowed.
|
|
43
|
+
"domain.label_too_long", # Domain label is longer than 63 characters.
|
|
44
|
+
"domain.invalid_character", # Domain name contains an invalid character.
|
|
45
|
+
"domain.hyphen_position", # Domain label starts or ends with a hyphen.
|
|
46
|
+
"domain.single_label", # Fully qualified domain name requires at least two labels.
|
|
47
|
+
"domain.numeric_tld", # Top-level label must not be all digits.
|
|
48
|
+
"port.invalid", # Port must be a number.
|
|
49
|
+
"port.leading_zero", # Port has a leading zero.
|
|
50
|
+
"port.out_of_range", # Port is out of range.
|
|
51
|
+
"port_range.invalid", # Not a valid port range.
|
|
52
|
+
"port_range.descending", # Port range start is greater than its end.
|
|
53
|
+
"port_list.empty_item", # Port list contains an empty item.
|
|
54
|
+
"port_list.range_not_allowed", # Port ranges are not allowed in this list.
|
|
55
|
+
"port_list.invalid_item", # Port list contains an invalid item.
|
|
56
|
+
"mac.invalid", # Not a valid MAC address.
|
|
57
|
+
"mac.format_not_allowed", # MAC address format is not allowed.
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
ERROR_CODES: tuple[ErrorCode, ...] = get_args(ErrorCode)
|
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
from ._codes import ErrorCode
|
|
9
|
+
|
|
10
|
+
Version = Union[Literal[4], Literal[6], Literal["any"]]
|
|
11
|
+
|
|
12
|
+
ASCII_DIGITS = frozenset("0123456789")
|
|
13
|
+
_ASCII_WHITESPACE = frozenset(" \t\n\r\x0b\x0c")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class ValidationResult:
|
|
18
|
+
"""Outcome of a validation. Truthy when valid.
|
|
19
|
+
|
|
20
|
+
``code`` is None exactly when the result is valid. Type checkers can't narrow it from
|
|
21
|
+
``if not result``, so test ``if result.code is not None`` to get it typed as :data:`ErrorCode`.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
valid: bool
|
|
25
|
+
code: Optional[ErrorCode] = None
|
|
26
|
+
details: Dict[str, Any] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
def __bool__(self) -> bool:
|
|
29
|
+
return self.valid
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Invalid(Exception):
|
|
33
|
+
"""Internal signal for a validation failure; converted to a ValidationResult."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, code: ErrorCode, details: Optional[Dict[str, Any]] = None) -> None:
|
|
36
|
+
super().__init__(code)
|
|
37
|
+
self.code = code
|
|
38
|
+
self.details = details or {}
|
|
39
|
+
|
|
40
|
+
def result(self) -> ValidationResult:
|
|
41
|
+
return ValidationResult(False, self.code, dict(self.details))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def run(check: Callable[[], Any]) -> ValidationResult:
|
|
45
|
+
"""Run a check that raises Invalid on failure and return the result."""
|
|
46
|
+
try:
|
|
47
|
+
check()
|
|
48
|
+
except Invalid as e:
|
|
49
|
+
return e.result()
|
|
50
|
+
return ValidationResult(True)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def check_common(value: Any) -> str:
|
|
54
|
+
"""SPEC §1.4. Returns the value typed as str."""
|
|
55
|
+
if not isinstance(value, str):
|
|
56
|
+
raise Invalid("not_string")
|
|
57
|
+
if value == "":
|
|
58
|
+
raise Invalid("empty")
|
|
59
|
+
if value[0] in _ASCII_WHITESPACE or value[-1] in _ASCII_WHITESPACE:
|
|
60
|
+
raise Invalid("whitespace")
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def is_ascii_digits(s: str) -> bool:
|
|
65
|
+
return s != "" and all(c in ASCII_DIGITS for c in s)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# --- option checks (configuration errors, SPEC §1.3) -------------------------
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def check_version(version: Any) -> None:
|
|
72
|
+
if version == "any" and isinstance(version, str):
|
|
73
|
+
return
|
|
74
|
+
if type(version) is int and version in (4, 6):
|
|
75
|
+
return
|
|
76
|
+
raise ValueError(f"version must be 4, 6 or 'any', got {version!r}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_bool(name: str, value: Any) -> None:
|
|
80
|
+
if not isinstance(value, bool):
|
|
81
|
+
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)
|
network_validators/ip.py
ADDED
|
@@ -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("ip.leading_zero" if e.kind == "leading_zero" else "ip.invalid") 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, List, Sequence, Tuple
|
|
6
|
+
|
|
7
|
+
from ._addr import Network, 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[Tuple[str, Network]]:
|
|
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,108 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: network-validators
|
|
3
|
+
Version: 0.1.0
|
|
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. Before 1.0, a minor version (0.2, 0.3, …) may include breaking changes. Every change is 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 network-validators
|
|
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
|
+
from network_validators import ErrorCode, validate_subnet
|
|
65
|
+
|
|
66
|
+
MESSAGES: dict[ErrorCode, str] = {
|
|
67
|
+
"empty": "This field is required.",
|
|
68
|
+
"subnet.host_bits_set": "Did you mean {network}?",
|
|
69
|
+
"port.out_of_range": "Port must be between {min} and {max}.",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
r = validate_subnet(value, allow_host_bits=False)
|
|
73
|
+
if r.code is not None: # same as `if not r`, and type checkers then see code as an ErrorCode
|
|
74
|
+
message = MESSAGES.get(r.code, "Invalid value.").format(**r.details)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`ErrorCode` is a `Literal` type of every code, so a type checker flags a misspelled code in your map. `ERROR_CODES` lists them at runtime, for example to check that a message catalog covers them all.
|
|
78
|
+
|
|
79
|
+
Empty strings fail with code `empty`. If a field is optional, skip validation when it's empty.
|
|
80
|
+
|
|
81
|
+
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.
|
|
82
|
+
|
|
83
|
+
## Validators
|
|
84
|
+
|
|
85
|
+
| Function | Accepts | Options |
|
|
86
|
+
|---|---|---|
|
|
87
|
+
| `validate_ip_address` | `192.0.2.1`, `2001:db8::1` | `version`, `allow_zone_id`, `allow_unspecified`, `allow_private` |
|
|
88
|
+
| `validate_private_ip_address` | `10.0.0.1`, `fd00::1` | `version`, `allow_zone_id`, `additional_ranges` |
|
|
89
|
+
| `validate_netmask` | `255.255.255.0` | |
|
|
90
|
+
| `validate_subnet` | `10.0.0.0/8`, `10.0.0.0 255.0.0.0`, `2001:db8::/32` | `version`, `allow_netmask`, `allow_host_bits` |
|
|
91
|
+
| `validate_private_subnet` | `192.168.1.0/24` | as `validate_subnet`, plus `additional_ranges` |
|
|
92
|
+
| `validate_ip_range` | `10.0.0.1-10.0.0.50` | `version`, `allow_single` |
|
|
93
|
+
| `validate_ip_in_subnets` / `validate_ip_not_in_subnets` | an IP address | `subnets` (required), `version` |
|
|
94
|
+
| `validate_subnet_in_subnets` / `validate_subnet_not_overlapping` | a subnet | `subnets` (required), `version` |
|
|
95
|
+
| `validate_ip_range_not_overlapping` | an IP range | `subnets` (required), `version` |
|
|
96
|
+
| `validate_hostname` / `validate_fqdn` | `server1` / `www.example.com` | `allow_wildcard`, `allow_underscore`, `allow_trailing_dot` |
|
|
97
|
+
| `validate_host` | a hostname, FQDN or IP address | IP and name options, plus `allow_single_label` |
|
|
98
|
+
| `validate_port` / `validate_port_range` | `443` / `8000-8080` | `allow_zero` |
|
|
99
|
+
| `validate_port_list` | `80, 443, 8000-8080` | `allow_zero`, `allow_ranges` |
|
|
100
|
+
| `validate_mac_address` | `00:1a:2b:3c:4d:5e`, `001a.2b3c.4d5e` | `formats` |
|
|
101
|
+
|
|
102
|
+
`version` is `4`, `6` or `"any"` (the default).
|
|
103
|
+
|
|
104
|
+
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).
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
network_validators/__init__.py,sha256=O0h74UsYGZfXydC3HT4J-SVp-sVBX8LyplYtR-ZJGHw,4297
|
|
2
|
+
network_validators/_addr.py,sha256=Sjtfzv1-lgeCG3zUX_dYzDAhTvGMZZjwPykioaK-1Rk,7773
|
|
3
|
+
network_validators/_codes.py,sha256=_vWaKvZtDeMHcH9MvXGZfOCmV6ud_PYWkjHaowCIf1E,3547
|
|
4
|
+
network_validators/_core.py,sha256=rAKqLKZN2KyNMK5lsbrHafHvXsOm5Bdr8yBpHni9kX4,2452
|
|
5
|
+
network_validators/domain.py,sha256=hXhioHRXzngvbjSMOkwl-85zB43W7U0k08ZckgRtPxE,4361
|
|
6
|
+
network_validators/ip.py,sha256=oQB5m0mm6FWA58uG1XtPgNHKPeZw4Swsqh7R-ao_XiE,2286
|
|
7
|
+
network_validators/ip_range.py,sha256=o9ou0lw5ZzCy3VD1L2QDkOKW0ZHkXU8WwXvlvZcZf-s,1846
|
|
8
|
+
network_validators/mac.py,sha256=ERxwLU0Tc9bX8AHDfLq_fHvnIC6M9JirmhZdLmerEYs,1360
|
|
9
|
+
network_validators/port.py,sha256=MRsdr0ds20qjiZ83fAiaBIKEQarq5LYv0nzB2RY1zLs,2756
|
|
10
|
+
network_validators/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
network_validators/relations.py,sha256=dxrakwOgU3x5vfC9V2Aq0cqqMDnYIa1V7XotCw5j2KA,3203
|
|
12
|
+
network_validators/subnet.py,sha256=kfMzdvlGQM2i8i7ovA2tV-vgbFZGaJmV_jNJoP5nbtA,2289
|
|
13
|
+
network_validators-0.1.0.dist-info/METADATA,sha256=hJmDUCOgs_MOBKbGpgosjlqf1Yzlevc0ZuHEhkUiSMA,5236
|
|
14
|
+
network_validators-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
15
|
+
network_validators-0.1.0.dist-info/licenses/LICENSE,sha256=MpxeIrnEXVK8DLQGfs9iqW7ap7RPCdHsttEtXW5rbSY,1067
|
|
16
|
+
network_validators-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|