Elffuss BraidHub

utopia-ia/elffuss-claw public

main · 40.8 KiBRawPermalink
1#!/usr/bin/env python3
2"""Pruebas del proxy endurecido (/proxy?url=…) de server/serve.py.
3
4Sin red: el DNS (serve._getaddrinfo) y la conexión TCP (serve._dial) se
5sustituyen, e «internet» es un servidor HTTP local al que el dialer desvía las
6direcciones públicas de la prueba. Cualquier otra dirección a la que el proxy
7intentara conectar queda apuntada en el dialer y se rechaza, así que cada
8vector rechazado comprueba también que NO hubo conexión.
9
10 python3 tests/test_proxy.py
11 python3 -m unittest discover -s tests -p 'test_*.py'
12"""
13import gzip
14import http.client
15import http.server
16import importlib.util
17import ipaddress
18import json
19import os
20import socket
21import socketserver
22import ssl
23import sys
24import tempfile
25import threading
26import time
27import tracemalloc
28import types
29import unittest
30import urllib.parse
31import zlib
32from pathlib import Path
33from unittest import mock
34
35sys.dont_write_bytecode = True # que la prueba no deje __pycache__ junto a serve.py
36SERVE_PY = Path(__file__).resolve().parent.parent / 'server' / 'serve.py'
37_spec = importlib.util.spec_from_file_location('elffuss_serve', SERVE_PY)
38serve = importlib.util.module_from_spec(_spec)
39_spec.loader.exec_module(serve)
40REAL_SELF_ADDRESSES = serve._self_addresses # las pruebas lo sustituyen; esta copia es la de verdad
41
42PUBLIC_V4 = '93.184.215.14'
43PUBLIC_V4_B = '93.184.215.15'
44PUBLIC_V6 = '2606:4700:4700::1111'
45# Una respuesta de doble pila como la de un CDN: primero cuatro AAAA.
46DUAL_V6 = ('2a04:4e42::223', '2a04:4e42:200::223', '2a04:4e42:400::223', '2a04:4e42:600::223')
47MANY_V4 = tuple('93.184.216.%d' % i for i in range(1, 11))
48NON_PUBLIC_V4 = ('127.0.0.1', '127.255.255.254', '0.0.0.0', '10.0.0.1', '172.16.0.1', '172.31.255.255',
49 '192.168.0.1', '169.254.169.254', '100.64.0.1', '100.100.100.200', '224.0.0.1',
50 '239.255.255.250', '240.0.0.1', '255.255.255.255', '192.0.0.170', '192.0.2.1',
51 '198.18.0.1', '198.51.100.1', '203.0.113.1', '192.88.99.1')
52NON_PUBLIC_V6 = ('::1', '::', '::ffff:127.0.0.1', '::ffff:7f00:1', '::ffff:169.254.169.254', '::ffff:8.8.8.8',
53 '::127.0.0.1', '::ffff:0:7f00:1', 'fe80::1', 'fc00::1', 'fd00:ec2::254', 'ff02::1',
54 '64:ff9b::7f00:1', '64:ff9b::a9fe:a9fe', '2002:7f00:1::1', '2001::1',
55 '2001:0:4136:e378:8000:63bf:3fff:fdd2', '2001:db8::1', '100::1', '3fff::1')
56
57
58class Upstream:
59 """El «internet» de las pruebas: responde según la ruta y apunta cada
60 petición con sus cabeceras."""
61
62 def __init__(self):
63 self.requests = []
64 self.routes = {}
65 upstream = self
66
67 class H(http.server.BaseHTTPRequestHandler):
68 protocol_version = 'HTTP/1.1'
69
70 def do_GET(self):
71 upstream.requests.append({'path': self.path,
72 'headers': {k.lower(): v for k, v in self.headers.items()}})
73 route = upstream.routes.get(urllib.parse.urlsplit(self.path).path)
74 if route is None:
75 route = (404, {'Content-Type': 'text/plain'}, b'no existe')
76 if callable(route):
77 return route(self)
78 status, headers, body = route
79 self.send_response(status)
80 for k, v in headers.items():
81 self.send_header(k, v)
82 if 'Content-Length' not in headers:
83 self.send_header('Content-Length', str(len(body)))
84 self.send_header('Connection', 'close')
85 self.end_headers()
86 self.wfile.write(body)
87
88 def log_message(self, *args):
89 pass
90
91 self.httpd = http.server.ThreadingHTTPServer(('127.0.0.1', 0), H)
92 self.addr = self.httpd.server_address[:2]
93 threading.Thread(target=self.httpd.serve_forever, kwargs={'poll_interval': 0.05}, daemon=True).start()
94
95 def close(self):
96 self.httpd.shutdown()
97 self.httpd.server_close()
98
99
100class FakeDNS:
101 """Sustituye a getaddrinfo: nombre → lista de IP (o función que la da)."""
102
103 def __init__(self, table):
104 self.table = table
105 self.calls = []
106
107 def __call__(self, host, port, *args):
108 self.calls.append(host)
109 answer = self.table.get(host)
110 if callable(answer):
111 answer = answer()
112 if not answer:
113 raise socket.gaierror(socket.EAI_NONAME, 'Name or service not known')
114 out = []
115 for ip in answer:
116 if ':' in ip:
117 out.append((socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', (ip, port, 0, 0)))
118 else:
119 out.append((socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', (ip, port)))
120 return out
121
122
123class Dialer:
124 """Sustituye a la conexión TCP: las IP públicas de la prueba van al
125 servidor local; cualquier otra se apunta y se rechaza."""
126
127 def __init__(self, routes):
128 self.routes = routes
129 self.calls = []
130
131 def __call__(self, family, sockaddr, timeout):
132 self.calls.append((sockaddr[0], sockaddr[1]))
133 dest = self.routes.get(sockaddr[0])
134 if dest is None:
135 raise ConnectionRefusedError('dirección no prevista en la prueba')
136 return socket.create_connection(dest, timeout=timeout)
137
138
139class _PlainAsTLS(socket.socket):
140 def do_handshake(self):
141 pass
142
143
144class FakeTLSContext:
145 """Contexto TLS de mentira: apunta el server_hostname (SNI y nombre que se
146 verifica) y deja la conexión en claro hacia el servidor local."""
147 verify_mode = ssl.CERT_REQUIRED
148 check_hostname = True
149 post_handshake_auth = None
150
151 def __init__(self):
152 self.server_hostnames = []
153
154 def wrap_socket(self, sock, server_hostname=None, do_handshake_on_connect=True):
155 self.server_hostnames.append(server_hostname)
156 return _PlainAsTLS(sock.family, sock.type, sock.proto, fileno=sock.detach())
157
158
159def _flip(first, then):
160 """Respuesta DNS que cambia tras la primera consulta (DNS rebinding)."""
161 answers = [first]
162
163 def answer():
164 out = answers[0]
165 answers[0] = then
166 return out
167 return answer
168
169
170class ProxyCase(unittest.TestCase):
171 def setUp(self):
172 self.upstream = Upstream()
173 self.addCleanup(self.upstream.close)
174 self.upstream.routes['/ok'] = (200, {'Content-Type': 'text/html; charset=utf-8'}, b'<p>hola</p>')
175 self.dns = FakeDNS({
176 'example.com': [PUBLIC_V4],
177 'www.example.com': [PUBLIC_V4],
178 'other.example.org': [PUBLIC_V4_B],
179 'xn--bcher-kva.example.com': [PUBLIC_V4],
180 'internal.example.com': ['10.0.0.7'],
181 'meta.example.com': ['169.254.169.254'],
182 'loop.example.com': ['127.0.0.1'],
183 'zero.example.com': ['0.0.0.0'],
184 'cgnat.example.com': ['100.100.100.200'],
185 'mcast.example.com': ['224.0.0.251'],
186 'bcast.example.com': ['255.255.255.255'],
187 'v6loop.example.com': ['::1'],
188 'mapped.example.com': ['::ffff:10.0.0.1'],
189 'ula.example.com': ['fd00:ec2::254'],
190 'linklocal6.example.com': ['fe80::1'],
191 'nat64.example.com': ['64:ff9b::a9fe:a9fe'],
192 'mixed.example.com': [PUBLIC_V4, '192.168.1.10'],
193 'rebind.example.com': _flip([PUBLIC_V4], ['127.0.0.1']),
194 'flip.example.com': _flip([PUBLIC_V4], ['127.0.0.1']),
195 'dual.example.com': list(DUAL_V6) + [PUBLIC_V4, PUBLIC_V4_B],
196 'many.example.com': list(MANY_V4),
197 'late.example.com': list(MANY_V4[:4]) + [PUBLIC_V4],
198 })
199 self.dialer = Dialer({PUBLIC_V4: self.upstream.addr, PUBLIC_V4_B: self.upstream.addr,
200 PUBLIC_V6: self.upstream.addr})
201 self.tls = FakeTLSContext()
202 self.own = frozenset() # las direcciones de «esta máquina» en la prueba
203 self.logs = []
204 logs = self.logs
205 for name, value in (('_getaddrinfo', self.dns), ('_dial', self.dialer),
206 ('_tls_context', lambda: self.tls),
207 ('_self_addresses', lambda: self.own),
208 ('PROXY_RATE', serve._RateLimiter(60, 10_000)),
209 ('PROXY_GLOBAL_RATE', serve._RateLimiter(60, 10_000)),
210 ('PROXY_SLOTS', threading.BoundedSemaphore(8))):
211 patcher = mock.patch.object(serve, name, value)
212 patcher.start()
213 self.addCleanup(patcher.stop)
214 patcher = mock.patch.object(serve.Handler, 'log_message', lambda h, fmt, *a: logs.append(fmt % a))
215 patcher.start()
216 self.addCleanup(patcher.stop)
217 self.server = socketserver.ThreadingTCPServer(('127.0.0.1', 0), serve.Handler)
218 self.server.daemon_threads = True
219 self.port = self.server.server_address[1]
220 threading.Thread(target=self.server.serve_forever, kwargs={'poll_interval': 0.05}, daemon=True).start()
221 self.addCleanup(self.server.server_close)
222 self.addCleanup(self.server.shutdown)
223
224 def get(self, url=None, headers=None, path=None):
225 if path is None:
226 path = '/proxy?url=' + urllib.parse.quote(url, safe='')
227 conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=30)
228 try:
229 conn.request('GET', path, headers=headers or {})
230 resp = conn.getresponse()
231 return resp.status, {k.lower(): v for k, v in resp.getheaders()}, resp.read()
232 finally:
233 conn.close()
234
235 def assertRefused(self, url, status, code=None, headers=None):
236 dials_before = list(self.dialer.calls)
237 got, hdrs, body = self.get(url, headers=headers)
238 self.assertEqual(got, status, '%s → %s %s' % (url, got, body[:200]))
239 if code is not None:
240 self.assertEqual(hdrs.get('x-proxy-error'), code, url)
241 self.assertEqual(hdrs.get('x-content-type-options'), 'nosniff', url)
242 self.assertNotIn('access-control-allow-origin', hdrs, url)
243 self.assertEqual(self.dialer.calls, dials_before, '%s: el proxy llegó a conectar' % url)
244 return hdrs, body
245
246
247class RefusedVectors(ProxyCase):
248 def test_only_http_and_https(self):
249 for url in ('file:///etc/passwd', 'ftp://example.com/', 'gopher://example.com/',
250 'dict://example.com:11211/', 'ws://example.com/', 'javascript:alert(1)',
251 'data:text/html,hola', 'example.com/ok', '//example.com/ok'):
252 with self.subTest(url=url):
253 self.assertRefused(url, 400, 'bad-scheme')
254
255 def test_missing_or_malformed_url(self):
256 status, hdrs, _ = self.get(path='/proxy?otra=1')
257 self.assertEqual((status, hdrs.get('x-proxy-error')), (400, 'bad-url'))
258 for url in ('http://', 'http:///solo-ruta', 'http://exa mple.com/', 'http://example.com:80:80/',
259 'http://ex%61mple.com/', 'http://[::1/', 'http://[zz::1]/', 'http://[::1]x/',
260 'http://example.com/\r\nX-Inyectada: 1', 'http://example.com/' + 'a' * 5000):
261 with self.subTest(url=url):
262 self.assertRefused(url, 400)
263
264 def test_userinfo_refused(self):
265 for url in ('http://user:pw@example.com/', 'http://example.com@127.0.0.1/',
266 'http://@example.com/', 'http://example.com\\@127.0.0.1/'):
267 with self.subTest(url=url):
268 self.assertRefused(url, 400, 'userinfo')
269
270 def test_only_ports_80_and_443(self):
271 for url in ('http://example.com:22/', 'http://example.com:8643/', 'http://example.com:6379/',
272 'https://example.com:8443/', 'http://example.com:0/', 'http://example.com:65536/',
273 'http://example.com:99999999/', 'http://127.0.0.1:1/'):
274 with self.subTest(url=url):
275 self.assertRefused(url, 403, 'forbidden-port')
276 self.assertEqual(self.dns.calls, [], 'un puerto prohibido no debe ni resolverse')
277
278 def test_non_public_ipv4_literals(self):
279 for ip in NON_PUBLIC_V4 + ('127.0.0.1.',):
280 with self.subTest(ip=ip):
281 self.assertRefused('http://%s/' % ip, 403, 'forbidden-destination')
282 self.assertEqual(self.dns.calls, [], 'una IP literal no pasa por el DNS')
283
284 def test_odd_ipv4_spellings(self):
285 for host in ('2130706433', '0x7f000001', '0X7F000001', '017700000001', '0177.0.0.1', '0x7f.0.0.1',
286 '127.1', '127.0.1', '127.0.0.01', '0x7f.1', '0', '0x0', '010.0.0.1', '1.2.3.4.5',
287 '256.1.1.1', '1.2.3', '134744072', '0x08.0x08.0x08.0x08',
288 '\uff10x7f.0.0.1', # cero de ancho completo: NFKC lo deja en 0x7f
289 '\u2460\u2461\u2466.0.0.1.1'): # dígitos en círculo: NFKC los deja en 127
290 with self.subTest(host=host):
291 self.assertRefused('http://%s/' % host, 400, 'odd-ip')
292 self.assertEqual(self.dns.calls, [])
293
294 def test_non_public_ipv6_literals(self):
295 for host in ['[%s]' % ip for ip in NON_PUBLIC_V6] + ['[fe80::1%25eth0]']:
296 with self.subTest(host=host):
297 self.assertRefused('http://%s/' % host, 403, 'forbidden-destination')
298 self.assertEqual(self.dns.calls, [])
299
300 def test_local_and_reserved_names_are_never_resolved(self):
301 for host in ('localhost', 'LOCALHOST.', 'foo.localhost', 'metadata.google.internal', 'printer.local',
302 'router.home.arpa', 'intranet', 'x.test', 'foo.example', 'nas.localdomain'):
303 with self.subTest(host=host):
304 self.assertRefused('http://%s/' % host, 403, 'forbidden-destination')
305 self.assertEqual(self.dns.calls, [])
306
307 def test_names_resolving_to_non_public_addresses(self):
308 for host in ('internal.example.com', 'meta.example.com', 'loop.example.com', 'zero.example.com',
309 'cgnat.example.com', 'mcast.example.com', 'bcast.example.com', 'v6loop.example.com',
310 'mapped.example.com', 'ula.example.com', 'linklocal6.example.com', 'nat64.example.com'):
311 with self.subTest(host=host):
312 _, body = self.assertRefused('http://%s/' % host, 403, 'forbidden-destination')
313 ip = self.dns.table[host][0]
314 self.assertNotIn(ip.encode(), body, 'el error no debe decir a qué resuelve')
315
316 def test_one_non_public_answer_refuses_the_whole_name(self):
317 self.assertRefused('http://mixed.example.com/ok', 403, 'forbidden-destination')
318
319 def test_dns_failure_is_a_502(self):
320 self.assertRefused('http://nxdomain.example.com/', 502, 'dns')
321
322 def test_deny_list_from_the_environment(self):
323 with mock.patch.object(serve, 'PROXY_DENY', (ipaddress.ip_network(PUBLIC_V4 + '/32'),)):
324 self.assertRefused('http://example.com/ok', 403, 'forbidden-destination')
325
326 def test_own_public_addresses_are_refused_without_any_configuration(self):
327 # Pedir la IP pública de la propia máquina, o un nombre alojado en
328 # ella, vuelve a entrar por su nginx con origen la propia máquina.
329 self.assertEqual(serve.PROXY_DENY, ())
330 self.own = frozenset({ipaddress.ip_address(PUBLIC_V4_B), ipaddress.ip_address(PUBLIC_V6)})
331 for url in ('http://%s/' % PUBLIC_V4_B, 'https://%s/ok' % PUBLIC_V4_B, 'http://[%s]/ok' % PUBLIC_V6,
332 'http://other.example.org/ok'): # este nombre resuelve a PUBLIC_V4_B
333 with self.subTest(url=url):
334 _, body = self.assertRefused(url, 403, 'forbidden-destination')
335 self.assertNotIn(PUBLIC_V4_B.encode(), body, 'el error no debe decir a qué resuelve')
336 self.upstream.routes['/to-self'] = (302, {'Location': 'http://other.example.org/ok'}, b'')
337 got, hdrs, _ = self.get('http://example.com/to-self')
338 self.assertEqual((got, hdrs.get('x-proxy-error')), (403, 'forbidden-redirect'))
339 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)], 'solo el primer salto conecta')
340 self.assertEqual(self.get('http://example.com/ok')[0], 200, 'las demás direcciones públicas siguen sirviendo')
341
342 def test_callers_other_than_the_app_itself(self):
343 for headers in ({'Sec-Fetch-Site': 'cross-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty'},
344 {'Sec-Fetch-Site': 'same-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty'},
345 {'Sec-Fetch-Site': 'none', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Dest': 'document'},
346 {'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Dest': 'iframe'},
347 {'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'no-cors', 'Sec-Fetch-Dest': 'image'},
348 {'Origin': 'https://evil.example.net'},
349 {'Origin': 'null'}):
350 with self.subTest(headers=headers):
351 self.assertRefused('http://example.com/ok', 403, 'cross-site', headers=headers)
352
353
354class Redirects(ProxyCase):
355 def redirect(self, path, location, status=302):
356 self.upstream.routes[path] = (status, {'Location': location}, b'')
357
358 def test_redirect_to_non_public_destinations(self):
359 cases = {
360 '/to-loopback': ('http://127.0.0.1/admin', 403),
361 '/to-metadata': ('http://169.254.169.254/latest/meta-data/', 403),
362 '/to-v6-loopback': ('http://[::1]/', 403),
363 '/to-mapped': ('http://[::ffff:127.0.0.1]/', 403),
364 '/to-internal-name': ('http://internal.example.com/', 403),
365 '/to-localhost': ('http://localhost/', 403),
366 '/to-port': ('http://example.com:6379/', 403),
367 '/to-odd': ('http://2130706433/', 502),
368 '/to-file': ('file:///etc/passwd', 502),
369 '/to-gopher': ('gopher://example.com/', 502),
370 '/to-userinfo': ('http://user@example.com/', 502),
371 }
372 for i, (path, (location, status)) in enumerate(cases.items()):
373 self.redirect(path, location, status=(301, 302, 303, 307, 308)[i % 5])
374 for path, (location, status) in cases.items():
375 with self.subTest(location=location):
376 self.dialer.calls.clear()
377 got, hdrs, _ = self.get('http://example.com' + path)
378 self.assertEqual(got, status)
379 self.assertEqual(hdrs.get('x-proxy-error'), 'forbidden-redirect' if status == 403 else 'bad-redirect')
380 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)], 'solo el primer salto conecta')
381
382 def test_every_hop_is_resolved_again(self):
383 # Mismo nombre en los dos saltos: la segunda vez resuelve a loopback.
384 self.redirect('/hop', 'http://flip.example.com/ok')
385 got, hdrs, _ = self.get('http://flip.example.com/hop')
386 self.assertEqual((got, hdrs.get('x-proxy-error')), (403, 'forbidden-redirect'))
387 self.assertEqual(self.dns.calls.count('flip.example.com'), 2)
388 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)])
389
390 def test_redirect_loop_stops(self):
391 self.redirect('/loop', '/loop')
392 got, hdrs, _ = self.get('http://example.com/loop')
393 self.assertEqual((got, hdrs.get('x-proxy-error')), (502, 'too-many-redirects'))
394 self.assertEqual(len(self.upstream.requests), serve.PROXY_MAX_REDIRECTS + 1)
395
396 def test_redirect_without_location(self):
397 self.upstream.routes['/nowhere'] = (302, {}, b'')
398 got, hdrs, _ = self.get('http://example.com/nowhere')
399 self.assertEqual((got, hdrs.get('x-proxy-error')), (502, 'bad-redirect'))
400
401 def test_relative_and_cross_host_redirects_are_followed(self):
402 self.redirect('/rel', '/ok', status=301)
403 got, hdrs, body = self.get('http://example.com/rel')
404 self.assertEqual((got, body), (200, b'<p>hola</p>'))
405 self.assertEqual([r['path'] for r in self.upstream.requests], ['/rel', '/ok'])
406 self.redirect('/away', 'https://other.example.org/ok', status=307)
407 got, _, body = self.get('http://example.com/away')
408 self.assertEqual((got, body), (200, b'<p>hola</p>'))
409 self.assertEqual(self.tls.server_hostnames, ['other.example.org'])
410 self.assertEqual(self.dialer.calls[-1], (PUBLIC_V4_B, 443))
411 self.assertEqual(self.upstream.requests[-1]['headers']['host'], 'other.example.org')
412
413
414class NormalFetch(ProxyCase):
415 def test_public_http_fetch(self):
416 status, hdrs, body = self.get('http://example.com/ok')
417 self.assertEqual((status, body), (200, b'<p>hola</p>'))
418 self.assertEqual(hdrs['content-type'], 'text/html; charset=utf-8')
419 self.assertEqual(hdrs['x-proxy-truncated'], '0')
420 self.assertEqual(hdrs['x-proxy-upstream-status'], '200')
421 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)])
422 self.assertEqual(self.upstream.requests[0]['headers']['host'], 'example.com')
423
424 def test_https_connects_to_the_checked_address_with_the_name_as_sni(self):
425 status, _, body = self.get('https://example.com/ok')
426 self.assertEqual((status, body), (200, b'<p>hola</p>'))
427 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 443)])
428 self.assertEqual(self.tls.server_hostnames, ['example.com'])
429 self.assertEqual(self.upstream.requests[0]['headers']['host'], 'example.com')
430
431 def test_ipv4_is_reached_when_the_first_answers_are_unreachable_ipv6(self):
432 # Máquina con IPv6 configurada pero sin ruta: las AAAA fallan al
433 # conectar. Antes se probaban solo las tres primeras (todas IPv6).
434 status, _, body = self.get('http://dual.example.com/ok')
435 self.assertEqual((status, body), (200, b'<p>hola</p>'))
436 self.assertEqual(self.dialer.calls, [(DUAL_V6[0], 80), (PUBLIC_V4, 80)])
437
438 def test_every_address_is_tried_up_to_the_cap(self):
439 status, _, _ = self.get('http://late.example.com/ok') # la buena es la quinta
440 self.assertEqual(status, 200)
441 self.assertEqual([ip for ip, _ in self.dialer.calls], list(MANY_V4[:4]) + [PUBLIC_V4])
442 self.dialer.calls.clear()
443 status, hdrs, _ = self.get('http://many.example.com/ok') # diez, ninguna contesta
444 self.assertEqual((status, hdrs.get('x-proxy-error')), (502, 'upstream'))
445 self.assertEqual([ip for ip, _ in self.dialer.calls], list(MANY_V4[:serve.PROXY_MAX_ADDRS]))
446
447 def test_resolved_once_then_pinned(self):
448 # El DNS cambia de respuesta tras la primera consulta: no se le vuelve a preguntar.
449 status, _, _ = self.get('http://rebind.example.com/ok')
450 self.assertEqual(status, 200)
451 self.assertEqual(self.dns.calls, ['rebind.example.com'])
452 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)])
453
454 def test_public_ipv6_literal_and_explicit_default_port(self):
455 status, _, _ = self.get('http://[%s]/ok' % PUBLIC_V6)
456 self.assertEqual(status, 200)
457 self.assertEqual(self.dialer.calls, [(PUBLIC_V6, 80)])
458 self.assertEqual(self.upstream.requests[0]['headers']['host'], '[%s]' % PUBLIC_V6)
459 status, _, _ = self.get('http://example.com:80/ok')
460 self.assertEqual(status, 200)
461
462 def test_international_domain_names(self):
463 status, _, _ = self.get('http://bücher.example.com/ok')
464 self.assertEqual(status, 200)
465 self.assertEqual(self.upstream.requests[0]['headers']['host'], 'xn--bcher-kva.example.com')
466
467 def test_client_headers_never_reach_the_destination(self):
468 status, _, _ = self.get('http://example.com/ok', headers={
469 'Cookie': 'session=secreto', 'Authorization': 'Bearer secreto', 'Proxy-Authorization': 'Basic eA==',
470 'User-Agent': 'otro', 'Referer': 'https://claw.elffuss.com/', 'X-Forwarded-For': '192.0.2.1',
471 'Accept-Language': 'es'})
472 self.assertEqual(status, 200)
473 sent = self.upstream.requests[0]['headers']
474 self.assertEqual(set(sent), {'host', 'user-agent', 'accept-encoding', 'connection'})
475 self.assertEqual(sent['user-agent'], serve.PROXY_USER_AGENT)
476 self.assertEqual(sent['accept-encoding'], 'identity')
477
478 def test_response_headers_are_minimal(self):
479 self.upstream.routes['/noisy'] = (200, {
480 'Content-Type': 'text/html', 'Set-Cookie': 'a=b', 'Access-Control-Allow-Origin': '*',
481 'Access-Control-Allow-Credentials': 'true', 'X-Frame-Options': 'ALLOWALL',
482 'Content-Security-Policy': "script-src *", 'Link': '</x>; rel=preload'}, b'cuerpo')
483 status, hdrs, body = self.get('http://example.com/noisy')
484 self.assertEqual((status, body), (200, b'cuerpo'))
485 allowed = {'content-type', 'content-length', 'x-proxy-truncated', 'x-proxy-upstream-status',
486 'x-content-type-options', 'content-security-policy', 'cross-origin-resource-policy',
487 'referrer-policy', 'cache-control', 'server', 'date'}
488 self.assertLessEqual(set(hdrs), allowed)
489 self.assertEqual(hdrs['x-content-type-options'], 'nosniff')
490 self.assertIn('sandbox', hdrs['content-security-policy'])
491 self.assertNotIn('script-src', hdrs['content-security-policy'])
492
493 def test_odd_content_type_is_replaced(self):
494 self.upstream.routes['/ct'] = (200, {'Content-Type': 'text/html\x7f'}, b'x')
495 _, hdrs, _ = self.get('http://example.com/ct')
496 self.assertEqual(hdrs['content-type'], 'application/octet-stream')
497
498 def test_truncation_is_announced(self):
499 self.upstream.routes['/big'] = (200, {'Content-Type': 'text/plain'}, b'a' * 5000)
500 self.upstream.routes['/exact'] = (200, {'Content-Type': 'text/plain'}, b'b' * 1000)
501 with mock.patch.object(serve, 'MAX_PROXY_BYTES', 1000):
502 status, hdrs, body = self.get('http://example.com/big')
503 self.assertEqual((status, len(body), hdrs['x-proxy-truncated']), (200, 1000, '1'))
504 status, hdrs, body = self.get('http://example.com/exact')
505 self.assertEqual((status, len(body), hdrs['x-proxy-truncated']), (200, 1000, '0'))
506
507 def test_upstream_status_is_passed_through(self):
508 self.upstream.routes['/boom'] = (500, {'Content-Type': 'text/plain'}, b'roto')
509 for path, code in (('/missing', 404), ('/boom', 500)):
510 status, hdrs, _ = self.get('http://example.com' + path)
511 self.assertEqual((status, hdrs['x-proxy-upstream-status']), (code, str(code)))
512
513 def test_gzip_is_decoded_with_a_ceiling(self):
514 self.upstream.routes['/gz'] = (200, {'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'},
515 gzip.compress(b'hola ' * 100))
516 self.upstream.routes['/bomb'] = (200, {'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'},
517 gzip.compress(b'\0' * 5_000_000))
518 self.upstream.routes['/br'] = (200, {'Content-Type': 'text/plain', 'Content-Encoding': 'br'}, b'xx')
519 status, hdrs, body = self.get('http://example.com/gz')
520 self.assertEqual((status, body), (200, b'hola ' * 100))
521 self.assertNotIn('content-encoding', hdrs)
522 with mock.patch.object(serve, 'MAX_PROXY_BYTES', 1000):
523 status, hdrs, body = self.get('http://example.com/bomb')
524 self.assertEqual((status, len(body), hdrs['x-proxy-truncated']), (200, 1000, '1'))
525 status, hdrs, _ = self.get('http://example.com/br')
526 self.assertEqual((status, hdrs.get('x-proxy-error')), (502, 'encoding'))
527
528 def test_total_deadline_cuts_a_dripping_server(self):
529 def drip_body(h):
530 h.send_response(200)
531 h.send_header('Content-Type', 'text/plain')
532 h.end_headers()
533 try:
534 for _ in range(400):
535 h.wfile.write(b'x')
536 h.wfile.flush()
537 time.sleep(0.05)
538 except OSError:
539 pass
540
541 def drip_headers(h):
542 try:
543 h.wfile.write(b'HTTP/1.1 200 OK\r\n')
544 for _ in range(400):
545 h.wfile.write(b'X-Goteo: 1\r\n')
546 h.wfile.flush()
547 time.sleep(0.05)
548 except OSError:
549 pass
550 self.upstream.routes['/drip-body'] = drip_body
551 self.upstream.routes['/drip-headers'] = drip_headers
552 with mock.patch.object(serve, 'PROXY_TOTAL_TIMEOUT_S', 1), mock.patch.object(serve, 'PROXY_READ_TIMEOUT_S', 10):
553 for path in ('/drip-body', '/drip-headers'):
554 with self.subTest(path=path):
555 started = time.monotonic()
556 status, hdrs, _ = self.get('http://example.com' + path)
557 self.assertEqual((status, hdrs.get('x-proxy-error')), (504, 'timeout'))
558 self.assertLess(time.monotonic() - started, 8, 'el plazo total no cortó la conexión')
559
560 def test_rate_limit_per_client_ip(self):
561 with mock.patch.object(serve, 'PROXY_RATE', serve._RateLimiter(60, 3)):
562 codes = [self.get('http://example.com/ok', headers={'X-Forwarded-For': '192.0.2.10'})[0]
563 for _ in range(4)]
564 self.assertEqual(codes, [200, 200, 200, 429])
565 # La entrada que cuenta es la última (la que pone nginx), no la que escribe el cliente.
566 status, hdrs, _ = self.get('http://example.com/ok',
567 headers={'X-Forwarded-For': '192.0.2.99, 192.0.2.10'})
568 self.assertEqual((status, hdrs.get('x-proxy-error')), (429, 'rate-limited'))
569 self.assertIn('retry-after', hdrs)
570 status, _, _ = self.get('http://example.com/ok', headers={'X-Forwarded-For': '192.0.2.11'})
571 self.assertEqual(status, 200)
572 self.assertEqual(len(self.upstream.requests), 4)
573
574 def test_global_limit_counts_every_client(self):
575 # El límite por IP se salta repartiendo las peticiones entre muchas IP:
576 # el global no.
577 with mock.patch.object(serve, 'PROXY_GLOBAL_RATE', serve._RateLimiter(60, 3)):
578 answers = [self.get('http://example.com/ok', headers={'X-Forwarded-For': '192.0.2.%d' % (20 + i)})
579 for i in range(4)]
580 self.assertEqual([a[0] for a in answers], [200, 200, 200, 503])
581 self.assertEqual(answers[-1][1].get('x-proxy-error'), 'overloaded')
582 self.assertIn('retry-after', answers[-1][1])
583 self.assertEqual(len(self.upstream.requests), 3)
584
585 def test_non_browser_clients_are_served_the_proxy_is_an_open_relay(self):
586 # Lo que hay que saber de /proxy: sin Sec-Fetch-* ni Origin (curl, un
587 # script) se atiende. Las cabeceras de navegador frenan a OTRAS webs que
588 # usen el navegador del usuario, no a nadie más; lo que acota el relé
589 # son los destinos permitidos y los límites.
590 status, _, body = self.get('http://example.com/ok', headers={'User-Agent': 'curl/8.7.1'})
591 self.assertEqual((status, body), (200, b'<p>hola</p>'))
592
593 def test_busy_when_every_slot_is_taken(self):
594 slots = threading.BoundedSemaphore(1)
595 slots.acquire()
596 with mock.patch.object(serve, 'PROXY_SLOTS', slots):
597 status, hdrs, _ = self.get('http://example.com/ok')
598 slots.release()
599 self.assertEqual((status, hdrs.get('x-proxy-error')), (503, 'busy'))
600 self.assertEqual(self.dialer.calls, [])
601
602 def test_same_origin_callers_are_served(self):
603 for headers in ({'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty'},
604 {'Origin': 'http://127.0.0.1:%d' % self.port}):
605 with self.subTest(headers=headers):
606 status, _, _ = self.get('http://example.com/ok', headers=headers)
607 self.assertEqual(status, 200)
608
609 def test_log_keeps_only_the_destination_host(self):
610 self.get('http://example.com/ruta-secreta?token=abc123')
611 line = [entry for entry in self.logs if '/proxy?' in entry]
612 self.assertEqual(len(line), 1, self.logs)
613 self.assertIn('http://example.com', line[0])
614 self.assertNotIn('ruta-secreta', line[0])
615 self.assertNotIn('abc123', line[0])
616
617 @unittest.skipUnless(hasattr(serve.Handler, 'report'), 'solo el servidor de Claw recoge /proxy/report')
618 def test_report_counts_the_address_nginx_appended(self):
619 with tempfile.TemporaryDirectory() as tmp:
620 reports = os.path.join(tmp, 'reports.jsonl')
621 with mock.patch.object(serve, 'REPORTS_PATH', reports), mock.patch.object(serve, 'REPORT_RATE', {}):
622 conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=10)
623 conn.request('POST', '/proxy/report', body=json.dumps({'app': 'prueba', 'message': 'hola'}),
624 headers={'Content-Type': 'application/json',
625 'X-Forwarded-For': 'escrito-por-el-cliente, 192.0.2.44'})
626 self.assertEqual(conn.getresponse().status, 200)
627 conn.close()
628 with open(reports, encoding='utf-8') as f:
629 self.assertEqual(json.loads(f.readline())['ip'], '192.0.2.44')
630
631
632FIB_TRIE = """Main:
633 +-- 0.0.0.0/0 3 0 5
634 |-- 0.0.0.0
635 /0 universe UNICAST
636 +-- 93.184.215.0/24 2 0 2
637 |-- 93.184.215.0
638 /24 link UNICAST
639 |-- 93.184.215.20
640 /32 host LOCAL
641 |-- 93.184.215.255
642 /32 link BROADCAST
643 +-- 127.0.0.0/8 2 0 2
644 |-- 127.0.0.1
645 /32 host LOCAL
646 +-- 172.17.0.0/16 2 0 2
647 |-- 172.17.0.1
648 /32 host LOCAL
649Local:
650 +-- 0.0.0.0/0 3 0 5
651 |-- 93.184.215.20
652 /32 host LOCAL
653"""
654IF_INET6 = """00000000000000000000000000000001 01 80 10 80 lo
655fe80000000000000021122fffe334455 02 40 20 80 eth0
6562a0000000000abcd0000000000000020 02 40 00 80 eth0
657"""
658
659
660class Units(unittest.TestCase):
661 def setUp(self):
662 # Nada de las direcciones reales de la máquina que corre la prueba.
663 patcher = mock.patch.object(serve, '_self_addresses', lambda: frozenset())
664 patcher.start()
665 self.addCleanup(patcher.stop)
666
667 def test_own_addresses_from_proc_and_the_egress_route(self):
668 self.assertEqual(serve._local_v4_from_fib_trie(FIB_TRIE), {'93.184.215.20', '127.0.0.1', '172.17.0.1'})
669 self.assertEqual(serve._local_v6_from_if_inet6(IF_INET6),
670 {'::1', 'fe80::211:22ff:fe33:4455', '2a00:0:0:abcd::20'})
671 with tempfile.TemporaryDirectory() as tmp:
672 fib, inet6 = os.path.join(tmp, 'fib_trie'), os.path.join(tmp, 'if_inet6')
673 Path(fib).write_text(FIB_TRIE, encoding='ascii')
674 Path(inet6).write_text(IF_INET6, encoding='ascii')
675 with mock.patch.object(serve, '_PROC_FIB_TRIE', fib), mock.patch.object(serve, '_PROC_IF_INET6', inet6), \
676 mock.patch.object(serve, '_egress_addresses', lambda: {'192.168.1.20', '2001:4860:4860::8888'}):
677 own = serve._own_addresses()
678 # Solo las de internet: loopback, docker, enlace local y LAN ya se rechazan solas.
679 self.assertEqual(own, frozenset(ipaddress.ip_address(a) for a in
680 ('93.184.215.20', '2a00:0:0:abcd::20', '2001:4860:4860::8888')))
681 with mock.patch.object(serve, '_PROC_FIB_TRIE', os.path.join(tmp, 'no-existe')), \
682 mock.patch.object(serve, '_PROC_IF_INET6', os.path.join(tmp, 'no-existe')), \
683 mock.patch.object(serve, '_egress_addresses', lambda: {'93.184.215.21'}):
684 self.assertEqual(serve._own_addresses(), frozenset({ipaddress.ip_address('93.184.215.21')}),
685 'sin /proc (fuera de Linux) queda la dirección de salida')
686
687 def test_own_addresses_are_refused_by_ip_is_public(self):
688 own = frozenset({ipaddress.ip_address('93.184.215.20')})
689 with mock.patch.object(serve, '_self_addresses', lambda: own):
690 self.assertFalse(serve._ip_is_public(ipaddress.ip_address('93.184.215.20')))
691 self.assertTrue(serve._ip_is_public(ipaddress.ip_address('93.184.215.21')))
692
693 def test_own_addresses_are_enumerated_again_after_a_while(self):
694 answers = iter([frozenset({ipaddress.ip_address('93.184.215.20')}),
695 frozenset({ipaddress.ip_address('93.184.215.21')})])
696 calls = []
697
698 def enumerate_once():
699 calls.append(1)
700 return next(answers)
701 # REAL_SELF_ADDRESSES: el de verdad, no el sustituto del setUp.
702 with mock.patch.object(serve, '_own_addresses', enumerate_once), \
703 mock.patch.dict(serve._self_cache, {'at': None, 'addrs': frozenset()}):
704 with mock.patch.object(serve, 'PROXY_SELF_REFRESH_S', 3600):
705 first = REAL_SELF_ADDRESSES()
706 self.assertEqual(REAL_SELF_ADDRESSES(), first)
707 self.assertEqual(len(calls), 1, 'cada petición no vuelve a enumerar')
708 with mock.patch.object(serve, 'PROXY_SELF_REFRESH_S', 0):
709 self.assertEqual(REAL_SELF_ADDRESSES(), frozenset({ipaddress.ip_address('93.184.215.21')}))
710 self.assertEqual(len(calls), 2)
711
712 def test_dial_order_alternates_families_and_has_a_cap(self):
713 v6 = [(socket.AF_INET6, (ip, 80, 0, 0)) for ip in DUAL_V6]
714 v4 = [(socket.AF_INET, (ip, 80)) for ip in (PUBLIC_V4, PUBLIC_V4_B)]
715 self.assertEqual([a[1][0] for a in serve._dial_order(v6 + v4)],
716 [DUAL_V6[0], PUBLIC_V4, DUAL_V6[1], PUBLIC_V4_B, DUAL_V6[2], DUAL_V6[3]])
717 self.assertEqual([a[1][0] for a in serve._dial_order(v4 + v6)][:3], [PUBLIC_V4, DUAL_V6[0], PUBLIC_V4_B])
718 many = [(socket.AF_INET, (ip, 80)) for ip in MANY_V4]
719 self.assertEqual(len(serve._dial_order(many)), serve.PROXY_MAX_ADDRS)
720 self.assertEqual(serve._dial_order([]), [])
721
722 def test_public_addresses_pass(self):
723 for ip in ('8.8.8.8', '1.1.1.1', PUBLIC_V4, PUBLIC_V6, '2001:4860:4860::8888', '2a00:1450:4001:80b::200e'):
724 with self.subTest(ip=ip):
725 self.assertTrue(serve._ip_is_public(ipaddress.ip_address(ip)))
726
727 def test_block_lists_alone_refuse_every_special_range(self):
728 # Las banderas de ipaddress cambian entre versiones de Python: las
729 # listas propias tienen que bastar por sí solas.
730 for ip in NON_PUBLIC_V4 + NON_PUBLIC_V6:
731 with self.subTest(ip=ip):
732 self.assertTrue(serve._in_block_lists(ipaddress.ip_address(ip)))
733 for ip in ('8.8.8.8', PUBLIC_V4, PUBLIC_V6, '2001:4860:4860::8888'):
734 self.assertFalse(serve._in_block_lists(ipaddress.ip_address(ip)))
735
736 def test_a_gzip_bomb_never_expands_past_the_ceiling(self):
737 packer = zlib.compressobj(9, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
738 zeros = b'\0' * (1 << 20)
739 bomb = b''.join(packer.compress(zeros) for _ in range(64)) + packer.flush() # 64 MB al descomprimir
740 tracemalloc.start()
741 try:
742 body, truncated = serve._inflate(bomb, 'gzip', 1000)
743 peak = tracemalloc.get_traced_memory()[1]
744 finally:
745 tracemalloc.stop()
746 self.assertEqual((len(body), truncated), (1000, True))
747 self.assertLess(peak, 8 << 20, 'descomprimió la bomba entera en memoria')
748
749 def test_forwarded_for_is_trusted_only_from_loopback(self):
750 def ip(peer, xff=None):
751 fake = types.SimpleNamespace(client_address=(peer, 40000),
752 headers={'X-Forwarded-For': xff} if xff is not None else {})
753 return serve.Handler.client_ip(fake)
754 self.assertEqual(ip('127.0.0.1', '203.0.113.5, 192.0.2.9'), '192.0.2.9')
755 self.assertEqual(ip('::1', '192.0.2.9'), '192.0.2.9')
756 self.assertEqual(ip('::ffff:127.0.0.1', '192.0.2.9'), '192.0.2.9')
757 self.assertEqual(ip('198.51.100.20', '192.0.2.9'), '198.51.100.20')
758 self.assertEqual(ip('127.0.0.1'), '127.0.0.1')
759
760 def test_ipv6_clients_are_limited_per_64(self):
761 self.assertEqual(serve._rate_key('2001:db8:1:2:3:4:5:6'), serve._rate_key('2001:db8:1:2:ffff::1'))
762 self.assertNotEqual(serve._rate_key('2001:db8:1:2::1'), serve._rate_key('2001:db8:1:3::1'))
763 self.assertEqual(serve._rate_key('::ffff:192.0.2.1'), '192.0.2.1')
764
765 def test_real_tls_context_verifies_certificates_and_names(self):
766 ctx = serve._tls_context()
767 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
768 self.assertTrue(ctx.check_hostname)
769
770 def test_listens_on_loopback_unless_told_otherwise(self):
771 seen = []
772
773 class FakeServer:
774 allow_reuse_address = False
775
776 def __init__(self, address, handler):
777 seen.append(address)
778
779 def __enter__(self):
780 return self
781
782 def __exit__(self, *exc):
783 return False
784
785 def serve_forever(self):
786 pass
787 env = {k: v for k, v in os.environ.items() if k != 'ELFFUSS_BIND'}
788 with mock.patch.object(serve.socketserver, 'ThreadingTCPServer', FakeServer), \
789 mock.patch.dict(os.environ, env, clear=True), mock.patch('builtins.print') as printed:
790 serve.main(['serve.py', '8642'])
791 os.environ['ELFFUSS_BIND'] = '0.0.0.0'
792 serve.main(['serve.py', '8650'])
793 self.assertEqual(seen, [('127.0.0.1', 8642), ('0.0.0.0', 8650)])
794 said = ' '.join(str(c.args[0]) for c in printed.call_args_list)
795 self.assertIn('/proxy rechaza 0 dirección(es) pública(s) de esta máquina', said,
796 'al arrancar dice cuántas direcciones propias rechaza (nunca cuáles)')
797
798
799if __name__ == '__main__':
800 unittest.main()