Tachyon /Users/simon/Documents/Codex/2026-10-12/i-need-a-python-3-15/.venv/lib/python3.15/site-packages/web_edit/security.py
4
Self Samples
5
Cumulative
3
Lines Hit
0.02%
% of Total
2
Max Self
3
Max Total
Intensity:
Cold Hot
Self Time
Total Time
Show All
Hot Only
Heat
Specialization
Line
Self
Total
Code
1
"""Exact host matching for requests to the unauthenticated file server."""
2
3
import ipaddress
4
import re
5
6
LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
7
UNSPECIFIED_HOSTS = {"0.0.0.0", "::"}
8
HOST_HEADER = re.compile(r"(?:\[([0-9a-fA-F:.]+)\]|([a-zA-Z0-9.-]+))(?::([0-9]{1,5}))?")
9
DNS_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")
10
11
12
def normalize_host(value):
13
"""Accept an IP or exact DNS name, without a scheme, port, or wildcard."""
14
try:
15
1
1
return str(ipaddress.ip_address(value))
16
except ValueError:
17
pass
18
try:
19
name = value.encode("idna").decode("ascii").lower().removesuffix(".")
20
except UnicodeError:
21
name = ""
22
if (
23
not name
24
or len(name) > 253
25
or not all(DNS_LABEL.fullmatch(label) for label in name.split("."))
26
):
27
raise ValueError(
28
"Use an IP address or exact hostname, without a scheme, port, path, or wildcard."
29
)
30
return name
31
32
33
def allowed_hosts_for(host, extra_hosts=()):
34
hosts = LOCAL_HOSTS | {normalize_host(name) for name in extra_hosts}
35
bound_host = normalize_host(host)
36
# Listening on every interface must not mean trusting every Host header.
37
if bound_host not in UNSPECIFIED_HOSTS:
38
hosts.add(bound_host)
39
return frozenset(hosts)
40
41
42
def is_allowed_host(headers, allowed_hosts):
43
values = [value for name, value in headers if name.lower() == b"host"]
44
if len(values) != 1:
45
return False
46
try:
47
1
1
match = HOST_HEADER.fullmatch(values[0].decode("ascii"))
48
if match is None:
49
return False
50
ipv6, hostname, port = match.groups()
51
if port is not None and not 1 <= int(port) <= 65535:
52
return False
53
2
3
host = str(ipaddress.IPv6Address(ipv6)) if ipv6 else normalize_host(hostname)
54
except (ValueError, UnicodeError):
55
return False
56
return host in allowed_hosts