返回 last30days-skill
network_guard.py
根目录 / tests / network_guard.py
1 """Fail offline tests for attempted network access, including caught errors."""
2
3 import errno
4 import importlib
5 import ipaddress
6 import socket
7 import threading
8 import weakref
9 from urllib.parse import urlsplit
10
11 import pytest
12
13
14 def _loopback(host):
15 if host == "localhost":
16 return True
17 try:
18 return ipaddress.ip_address(host).is_loopback
19 except ValueError:
20 return False
21
22
23 @pytest.fixture(autouse=True)
24 def network_guard():
25 attempts = []
26 owned_sockets = weakref.WeakKeyDictionary()
27 ownership_lock = threading.RLock()
28 original_bind = socket.socket.bind
29 original_close = socket.socket.close
30 original_detach = socket.socket.detach
31 original_connect = socket.socket.connect
32 original_connect_ex = socket.socket.connect_ex
33 original_sendto = socket.socket.sendto
34 original_sendmsg = getattr(socket.socket, "sendmsg", None)
35 original_create_connection = socket.create_connection
36 original_getaddrinfo = socket.getaddrinfo
37 original_getnameinfo = socket.getnameinfo
38
39 def deny(operation, address):
40 attempts.append(f"{operation}: {address!r}")
41 raise OSError(errno.ENETUNREACH, "offline test attempted an unowned network destination")
42
43 def endpoint(family, kind, protocol, address):
44 kind = int(kind) & ~(getattr(socket, "SOCK_NONBLOCK", 0) | getattr(socket, "SOCK_CLOEXEC", 0))
45 if not protocol:
46 protocol = {socket.SOCK_STREAM: socket.IPPROTO_TCP, socket.SOCK_DGRAM: socket.IPPROTO_UDP}.get(kind, 0)
47 scope = address[3] if family == socket.AF_INET6 and len(address) > 3 else 0
48 return family, str(ipaddress.ip_address(address[0])), address[1], scope, kind, protocol
49
50 def live_endpoints():
51 with ownership_lock:
52 return {value for sock, value in owned_sockets.items() if sock.fileno() >= 0}
53
54 def destinations(operation, host, port, family=0, kind=0, protocol=0, flags=0):
55 if not _loopback(host):
56 deny(operation, (host, port))
57 owned = live_endpoints()
58 hosts = {entry[1] for entry in owned} if host == "localhost" else {host}
59 answers = []
60 for address in sorted(hosts):
61 try:
62 candidates = original_getaddrinfo(
63 address, port, family, kind, protocol,
64 flags | socket.AI_NUMERICHOST | socket.AI_NUMERICSERV,
65 )
66 except socket.gaierror:
67 continue
68 for item in candidates:
69 if endpoint(item[0], item[1], item[2], item[4]) in owned and item not in answers:
70 answers.append(item)
71 if not answers:
72 deny(operation, (host, port))
73 return answers
74
75 def checked_address(operation, sock, address):
76 if sock.family not in (socket.AF_INET, socket.AF_INET6):
77 return address
78 return destinations(operation, address[0], address[1], sock.family, sock.type, sock.proto)[0][4]
79
80 def bind(sock, address):
81 if sock.family in (socket.AF_INET, socket.AF_INET6):
82 host = address[0]
83 if isinstance(host, bytes):
84 try:
85 host = host.decode("ascii")
86 except UnicodeDecodeError:
87 deny("bind", address)
88 if not isinstance(host, str):
89 raise TypeError("socket host must be str or bytes")
90 if host == "localhost":
91 host = "127.0.0.1" if sock.family == socket.AF_INET else "::1"
92 elif host == "":
93 host = "0.0.0.0" if sock.family == socket.AF_INET else "::"
94 try:
95 numeric = ipaddress.ip_address(host)
96 except ValueError:
97 deny("bind", address)
98 if numeric.version != (4 if sock.family == socket.AF_INET else 6):
99 raise socket.gaierror(socket.EAI_FAMILY, "IP address does not match the socket family")
100 address = (str(numeric), *address[1:])
101 result = original_bind(sock, address)
102 if sock.family in (socket.AF_INET, socket.AF_INET6) and _loopback(address[0]):
103 with ownership_lock:
104 owned_sockets[sock] = endpoint(sock.family, sock.type, sock.proto, sock.getsockname())
105 return result
106
107 def close(sock):
108 with ownership_lock:
109 owned_sockets.pop(sock, None)
110 return original_close(sock)
111
112 def detach(sock):
113 with ownership_lock:
114 owned_sockets.pop(sock, None)
115 return original_detach(sock)
116
117 def connect(sock, address):
118 return original_connect(sock, checked_address("connect", sock, address))
119
120 def connect_ex(sock, address):
121 return original_connect_ex(sock, checked_address("connect_ex", sock, address))
122
123 def sendto(sock, data, *args):
124 address = checked_address("sendto", sock, args[-1])
125 return original_sendto(sock, data, *args[:-1], address)
126
127 def sendmsg(sock, buffers, ancdata=(), flags=0, address=None):
128 if address is None:
129 return original_sendmsg(sock, buffers, ancdata, flags)
130 return original_sendmsg(sock, buffers, ancdata, flags, checked_address("sendmsg", sock, address))
131
132 def create_connection(address, *args, **kwargs):
133 destinations("create_connection", address[0], address[1], kind=socket.SOCK_STREAM)
134 return original_create_connection(address, *args, **kwargs)
135
136 def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
137 return destinations("getaddrinfo", host, port, family, type, proto, flags)
138
139 def local_address(operation, host, ipv4_only=False):
140 if not _loopback(host):
141 deny(operation, host)
142 address = ipaddress.ip_address("127.0.0.1" if host == "localhost" else host)
143 if ipv4_only and address.version != 4:
144 raise socket.gaierror(socket.EAI_FAMILY, "IPv4 lookup requires an IPv4 address")
145 return str(address)
146
147 def gethostbyname(host):
148 return local_address("gethostbyname", host, ipv4_only=True)
149
150 def gethostbyname_ex(host):
151 address = local_address("gethostbyname_ex", host, ipv4_only=True)
152 return "localhost" if host == "localhost" else address, [], [address]
153
154 def gethostbyaddr(host):
155 return "localhost", [], [local_address("gethostbyaddr", host)]
156
157 def getnameinfo(address, flags):
158 required = socket.NI_NUMERICHOST | socket.NI_NUMERICSERV
159 if not _loopback(address[0]) or address[0] == "localhost" or flags & required != required:
160 deny("getnameinfo", address)
161 return original_getnameinfo(address, flags)
162
163 with pytest.MonkeyPatch.context() as patch:
164 patch.setattr(socket.socket, "bind", bind)
165 patch.setattr(socket.socket, "close", close)
166 patch.setattr(socket.socket, "detach", detach)
167 patch.setattr(socket.socket, "connect", connect)
168 patch.setattr(socket.socket, "connect_ex", connect_ex)
169 patch.setattr(socket.socket, "sendto", sendto)
170 if original_sendmsg is not None:
171 patch.setattr(socket.socket, "sendmsg", sendmsg)
172 patch.setattr(socket, "create_connection", create_connection)
173 patch.setattr(socket, "getaddrinfo", getaddrinfo)
174 patch.setattr(socket, "gethostbyname", gethostbyname)
175 patch.setattr(socket, "gethostbyname_ex", gethostbyname_ex)
176 patch.setattr(socket, "gethostbyaddr", gethostbyaddr)
177 patch.setattr(socket, "getnameinfo", getnameinfo)
178 try:
179 bounded_get = importlib.import_module("lib.bounded_get")
180 except ModuleNotFoundError as error:
181 if error.name not in ("lib", "lib.bounded_get"):
182 raise
183 else:
184 original_get = bounded_get.get
185
186 def worker_get(req, *args, **kwargs):
187 target = urlsplit(req.full_url)
188 address = (target.hostname, target.port if target.port is not None else (443 if target.scheme == "https" else 80))
189 if target.hostname == "localhost":
190 # Isolated workers resolve the hostname outside the parent socket patches.
191 deny("bounded_get", address)
192 destinations("bounded_get", *address, kind=socket.SOCK_STREAM)
193 return original_get(req, *args, **kwargs)
194
195 patch.setattr(bounded_get, "get", worker_get)
196 yield
197 if attempts:
198 pytest.fail("Unexpected network attempts:\n" + "\n".join(attempts))
199
199 lines PYTHON