Elffuss BraidHub

utopia-ia/elffuss-code public

main · 31.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)
40
41PUBLIC_V4 = '93.184.215.14'
42PUBLIC_V4_B = '93.184.215.15'
43PUBLIC_V6 = '2606:4700:4700::1111'
44NON_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',
45 '192.168.0.1', '169.254.169.254', '100.64.0.1', '100.100.100.200', '224.0.0.1',
46 '239.255.255.250', '240.0.0.1', '255.255.255.255', '192.0.0.170', '192.0.2.1',
47 '198.18.0.1', '198.51.100.1', '203.0.113.1', '192.88.99.1')
48NON_PUBLIC_V6 = ('::1', '::', '::ffff:127.0.0.1', '::ffff:7f00:1', '::ffff:169.254.169.254', '::ffff:8.8.8.8',
49 '::127.0.0.1', '::ffff:0:7f00:1', 'fe80::1', 'fc00::1', 'fd00:ec2::254', 'ff02::1',
50 '64:ff9b::7f00:1', '64:ff9b::a9fe:a9fe', '2002:7f00:1::1', '2001::1',
51 '2001:0:4136:e378:8000:63bf:3fff:fdd2', '2001:db8::1', '100::1', '3fff::1')
52
53
54class Upstream:
55 """El «internet» de las pruebas: responde según la ruta y apunta cada
56 petición con sus cabeceras."""
57
58 def __init__(self):
59 self.requests = []
60 self.routes = {}
61 upstream = self
62
63 class H(http.server.BaseHTTPRequestHandler):
64 protocol_version = 'HTTP/1.1'
65
66 def do_GET(self):
67 upstream.requests.append({'path': self.path,
68 'headers': {k.lower(): v for k, v in self.headers.items()}})
69 route = upstream.routes.get(urllib.parse.urlsplit(self.path).path)
70 if route is None:
71 route = (404, {'Content-Type': 'text/plain'}, b'no existe')
72 if callable(route):
73 return route(self)
74 status, headers, body = route
75 self.send_response(status)
76 for k, v in headers.items():
77 self.send_header(k, v)
78 if 'Content-Length' not in headers:
79 self.send_header('Content-Length', str(len(body)))
80 self.send_header('Connection', 'close')
81 self.end_headers()
82 self.wfile.write(body)
83
84 def log_message(self, *args):
85 pass
86
87 self.httpd = http.server.ThreadingHTTPServer(('127.0.0.1', 0), H)
88 self.addr = self.httpd.server_address[:2]
89 threading.Thread(target=self.httpd.serve_forever, kwargs={'poll_interval': 0.05}, daemon=True).start()
90
91 def close(self):
92 self.httpd.shutdown()
93 self.httpd.server_close()
94
95
96class FakeDNS:
97 """Sustituye a getaddrinfo: nombre → lista de IP (o función que la da)."""
98
99 def __init__(self, table):
100 self.table = table
101 self.calls = []
102
103 def __call__(self, host, port, *args):
104 self.calls.append(host)
105 answer = self.table.get(host)
106 if callable(answer):
107 answer = answer()
108 if not answer:
109 raise socket.gaierror(socket.EAI_NONAME, 'Name or service not known')
110 out = []
111 for ip in answer:
112 if ':' in ip:
113 out.append((socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', (ip, port, 0, 0)))
114 else:
115 out.append((socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', (ip, port)))
116 return out
117
118
119class Dialer:
120 """Sustituye a la conexión TCP: las IP públicas de la prueba van al
121 servidor local; cualquier otra se apunta y se rechaza."""
122
123 def __init__(self, routes):
124 self.routes = routes
125 self.calls = []
126
127 def __call__(self, family, sockaddr, timeout):
128 self.calls.append((sockaddr[0], sockaddr[1]))
129 dest = self.routes.get(sockaddr[0])
130 if dest is None:
131 raise ConnectionRefusedError('dirección no prevista en la prueba')
132 return socket.create_connection(dest, timeout=timeout)
133
134
135class _PlainAsTLS(socket.socket):
136 def do_handshake(self):
137 pass
138
139
140class FakeTLSContext:
141 """Contexto TLS de mentira: apunta el server_hostname (SNI y nombre que se
142 verifica) y deja la conexión en claro hacia el servidor local."""
143 verify_mode = ssl.CERT_REQUIRED
144 check_hostname = True
145 post_handshake_auth = None
146
147 def __init__(self):
148 self.server_hostnames = []
149
150 def wrap_socket(self, sock, server_hostname=None, do_handshake_on_connect=True):
151 self.server_hostnames.append(server_hostname)
152 return _PlainAsTLS(sock.family, sock.type, sock.proto, fileno=sock.detach())
153
154
155def _flip(first, then):
156 """Respuesta DNS que cambia tras la primera consulta (DNS rebinding)."""
157 answers = [first]
158
159 def answer():
160 out = answers[0]
161 answers[0] = then
162 return out
163 return answer
164
165
166class ProxyCase(unittest.TestCase):
167 def setUp(self):
168 self.upstream = Upstream()
169 self.addCleanup(self.upstream.close)
170 self.upstream.routes['/ok'] = (200, {'Content-Type': 'text/html; charset=utf-8'}, b'<p>hola</p>')
171 self.dns = FakeDNS({
172 'example.com': [PUBLIC_V4],
173 'www.example.com': [PUBLIC_V4],
174 'other.example.org': [PUBLIC_V4_B],
175 'xn--bcher-kva.example.com': [PUBLIC_V4],
176 'internal.example.com': ['10.0.0.7'],
177 'meta.example.com': ['169.254.169.254'],
178 'loop.example.com': ['127.0.0.1'],
179 'zero.example.com': ['0.0.0.0'],
180 'cgnat.example.com': ['100.100.100.200'],
181 'mcast.example.com': ['224.0.0.251'],
182 'bcast.example.com': ['255.255.255.255'],
183 'v6loop.example.com': ['::1'],
184 'mapped.example.com': ['::ffff:10.0.0.1'],
185 'ula.example.com': ['fd00:ec2::254'],
186 'linklocal6.example.com': ['fe80::1'],
187 'nat64.example.com': ['64:ff9b::a9fe:a9fe'],
188 'mixed.example.com': [PUBLIC_V4, '192.168.1.10'],
189 'rebind.example.com': _flip([PUBLIC_V4], ['127.0.0.1']),
190 'flip.example.com': _flip([PUBLIC_V4], ['127.0.0.1']),
191 })
192 self.dialer = Dialer({PUBLIC_V4: self.upstream.addr, PUBLIC_V4_B: self.upstream.addr,
193 PUBLIC_V6: self.upstream.addr})
194 self.tls = FakeTLSContext()
195 self.logs = []
196 logs = self.logs
197 for name, value in (('_getaddrinfo', self.dns), ('_dial', self.dialer),
198 ('_tls_context', lambda: self.tls),
199 ('PROXY_RATE', serve._RateLimiter(60, 10_000)),
200 ('PROXY_SLOTS', threading.BoundedSemaphore(8))):
201 patcher = mock.patch.object(serve, name, value)
202 patcher.start()
203 self.addCleanup(patcher.stop)
204 patcher = mock.patch.object(serve.Handler, 'log_message', lambda h, fmt, *a: logs.append(fmt % a))
205 patcher.start()
206 self.addCleanup(patcher.stop)
207 self.server = socketserver.ThreadingTCPServer(('127.0.0.1', 0), serve.Handler)
208 self.server.daemon_threads = True
209 self.port = self.server.server_address[1]
210 threading.Thread(target=self.server.serve_forever, kwargs={'poll_interval': 0.05}, daemon=True).start()
211 self.addCleanup(self.server.server_close)
212 self.addCleanup(self.server.shutdown)
213
214 def get(self, url=None, headers=None, path=None):
215 if path is None:
216 path = '/proxy?url=' + urllib.parse.quote(url, safe='')
217 conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=30)
218 try:
219 conn.request('GET', path, headers=headers or {})
220 resp = conn.getresponse()
221 return resp.status, {k.lower(): v for k, v in resp.getheaders()}, resp.read()
222 finally:
223 conn.close()
224
225 def assertRefused(self, url, status, code=None, headers=None):
226 dials_before = list(self.dialer.calls)
227 got, hdrs, body = self.get(url, headers=headers)
228 self.assertEqual(got, status, '%s → %s %s' % (url, got, body[:200]))
229 if code is not None:
230 self.assertEqual(hdrs.get('x-proxy-error'), code, url)
231 self.assertEqual(hdrs.get('x-content-type-options'), 'nosniff', url)
232 self.assertNotIn('access-control-allow-origin', hdrs, url)
233 self.assertEqual(self.dialer.calls, dials_before, '%s: el proxy llegó a conectar' % url)
234 return hdrs, body
235
236
237class RefusedVectors(ProxyCase):
238 def test_only_http_and_https(self):
239 for url in ('file:///etc/passwd', 'ftp://example.com/', 'gopher://example.com/',
240 'dict://example.com:11211/', 'ws://example.com/', 'javascript:alert(1)',
241 'data:text/html,hola', 'example.com/ok', '//example.com/ok'):
242 with self.subTest(url=url):
243 self.assertRefused(url, 400, 'bad-scheme')
244
245 def test_missing_or_malformed_url(self):
246 status, hdrs, _ = self.get(path='/proxy?otra=1')
247 self.assertEqual((status, hdrs.get('x-proxy-error')), (400, 'bad-url'))
248 for url in ('http://', 'http:///solo-ruta', 'http://exa mple.com/', 'http://example.com:80:80/',
249 'http://ex%61mple.com/', 'http://[::1/', 'http://[zz::1]/', 'http://[::1]x/',
250 'http://example.com/\r\nX-Inyectada: 1', 'http://example.com/' + 'a' * 5000):
251 with self.subTest(url=url):
252 self.assertRefused(url, 400)
253
254 def test_userinfo_refused(self):
255 for url in ('http://user:pw@example.com/', 'http://example.com@127.0.0.1/',
256 'http://@example.com/', 'http://example.com\\@127.0.0.1/'):
257 with self.subTest(url=url):
258 self.assertRefused(url, 400, 'userinfo')
259
260 def test_only_ports_80_and_443(self):
261 for url in ('http://example.com:22/', 'http://example.com:8643/', 'http://example.com:6379/',
262 'https://example.com:8443/', 'http://example.com:0/', 'http://example.com:65536/',
263 'http://example.com:99999999/', 'http://127.0.0.1:1/'):
264 with self.subTest(url=url):
265 self.assertRefused(url, 403, 'forbidden-port')
266 self.assertEqual(self.dns.calls, [], 'un puerto prohibido no debe ni resolverse')
267
268 def test_non_public_ipv4_literals(self):
269 for ip in NON_PUBLIC_V4 + ('127.0.0.1.',):
270 with self.subTest(ip=ip):
271 self.assertRefused('http://%s/' % ip, 403, 'forbidden-destination')
272 self.assertEqual(self.dns.calls, [], 'una IP literal no pasa por el DNS')
273
274 def test_odd_ipv4_spellings(self):
275 for host in ('2130706433', '0x7f000001', '0X7F000001', '017700000001', '0177.0.0.1', '0x7f.0.0.1',
276 '127.1', '127.0.1', '127.0.0.01', '0x7f.1', '0', '0x0', '010.0.0.1', '1.2.3.4.5',
277 '256.1.1.1', '1.2.3', '134744072', '0x08.0x08.0x08.0x08',
278 '\uff10x7f.0.0.1', # cero de ancho completo: NFKC lo deja en 0x7f
279 '\u2460\u2461\u2466.0.0.1.1'): # dígitos en círculo: NFKC los deja en 127
280 with self.subTest(host=host):
281 self.assertRefused('http://%s/' % host, 400, 'odd-ip')
282 self.assertEqual(self.dns.calls, [])
283
284 def test_non_public_ipv6_literals(self):
285 for host in ['[%s]' % ip for ip in NON_PUBLIC_V6] + ['[fe80::1%25eth0]']:
286 with self.subTest(host=host):
287 self.assertRefused('http://%s/' % host, 403, 'forbidden-destination')
288 self.assertEqual(self.dns.calls, [])
289
290 def test_local_and_reserved_names_are_never_resolved(self):
291 for host in ('localhost', 'LOCALHOST.', 'foo.localhost', 'metadata.google.internal', 'printer.local',
292 'router.home.arpa', 'intranet', 'x.test', 'foo.example', 'nas.localdomain'):
293 with self.subTest(host=host):
294 self.assertRefused('http://%s/' % host, 403, 'forbidden-destination')
295 self.assertEqual(self.dns.calls, [])
296
297 def test_names_resolving_to_non_public_addresses(self):
298 for host in ('internal.example.com', 'meta.example.com', 'loop.example.com', 'zero.example.com',
299 'cgnat.example.com', 'mcast.example.com', 'bcast.example.com', 'v6loop.example.com',
300 'mapped.example.com', 'ula.example.com', 'linklocal6.example.com', 'nat64.example.com'):
301 with self.subTest(host=host):
302 _, body = self.assertRefused('http://%s/' % host, 403, 'forbidden-destination')
303 ip = self.dns.table[host][0]
304 self.assertNotIn(ip.encode(), body, 'el error no debe decir a qué resuelve')
305
306 def test_one_non_public_answer_refuses_the_whole_name(self):
307 self.assertRefused('http://mixed.example.com/ok', 403, 'forbidden-destination')
308
309 def test_dns_failure_is_a_502(self):
310 self.assertRefused('http://nxdomain.example.com/', 502, 'dns')
311
312 def test_deny_list_from_the_environment(self):
313 with mock.patch.object(serve, 'PROXY_DENY', (ipaddress.ip_network(PUBLIC_V4 + '/32'),)):
314 self.assertRefused('http://example.com/ok', 403, 'forbidden-destination')
315
316 def test_callers_other_than_the_app_itself(self):
317 for headers in ({'Sec-Fetch-Site': 'cross-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty'},
318 {'Sec-Fetch-Site': 'same-site', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty'},
319 {'Sec-Fetch-Site': 'none', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Dest': 'document'},
320 {'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Dest': 'iframe'},
321 {'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'no-cors', 'Sec-Fetch-Dest': 'image'},
322 {'Origin': 'https://evil.example.net'},
323 {'Origin': 'null'}):
324 with self.subTest(headers=headers):
325 self.assertRefused('http://example.com/ok', 403, 'cross-site', headers=headers)
326
327
328class Redirects(ProxyCase):
329 def redirect(self, path, location, status=302):
330 self.upstream.routes[path] = (status, {'Location': location}, b'')
331
332 def test_redirect_to_non_public_destinations(self):
333 cases = {
334 '/to-loopback': ('http://127.0.0.1/admin', 403),
335 '/to-metadata': ('http://169.254.169.254/latest/meta-data/', 403),
336 '/to-v6-loopback': ('http://[::1]/', 403),
337 '/to-mapped': ('http://[::ffff:127.0.0.1]/', 403),
338 '/to-internal-name': ('http://internal.example.com/', 403),
339 '/to-localhost': ('http://localhost/', 403),
340 '/to-port': ('http://example.com:6379/', 403),
341 '/to-odd': ('http://2130706433/', 502),
342 '/to-file': ('file:///etc/passwd', 502),
343 '/to-gopher': ('gopher://example.com/', 502),
344 '/to-userinfo': ('http://user@example.com/', 502),
345 }
346 for i, (path, (location, status)) in enumerate(cases.items()):
347 self.redirect(path, location, status=(301, 302, 303, 307, 308)[i % 5])
348 for path, (location, status) in cases.items():
349 with self.subTest(location=location):
350 self.dialer.calls.clear()
351 got, hdrs, _ = self.get('http://example.com' + path)
352 self.assertEqual(got, status)
353 self.assertEqual(hdrs.get('x-proxy-error'), 'forbidden-redirect' if status == 403 else 'bad-redirect')
354 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)], 'solo el primer salto conecta')
355
356 def test_every_hop_is_resolved_again(self):
357 # Mismo nombre en los dos saltos: la segunda vez resuelve a loopback.
358 self.redirect('/hop', 'http://flip.example.com/ok')
359 got, hdrs, _ = self.get('http://flip.example.com/hop')
360 self.assertEqual((got, hdrs.get('x-proxy-error')), (403, 'forbidden-redirect'))
361 self.assertEqual(self.dns.calls.count('flip.example.com'), 2)
362 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)])
363
364 def test_redirect_loop_stops(self):
365 self.redirect('/loop', '/loop')
366 got, hdrs, _ = self.get('http://example.com/loop')
367 self.assertEqual((got, hdrs.get('x-proxy-error')), (502, 'too-many-redirects'))
368 self.assertEqual(len(self.upstream.requests), serve.PROXY_MAX_REDIRECTS + 1)
369
370 def test_redirect_without_location(self):
371 self.upstream.routes['/nowhere'] = (302, {}, b'')
372 got, hdrs, _ = self.get('http://example.com/nowhere')
373 self.assertEqual((got, hdrs.get('x-proxy-error')), (502, 'bad-redirect'))
374
375 def test_relative_and_cross_host_redirects_are_followed(self):
376 self.redirect('/rel', '/ok', status=301)
377 got, hdrs, body = self.get('http://example.com/rel')
378 self.assertEqual((got, body), (200, b'<p>hola</p>'))
379 self.assertEqual([r['path'] for r in self.upstream.requests], ['/rel', '/ok'])
380 self.redirect('/away', 'https://other.example.org/ok', status=307)
381 got, _, body = self.get('http://example.com/away')
382 self.assertEqual((got, body), (200, b'<p>hola</p>'))
383 self.assertEqual(self.tls.server_hostnames, ['other.example.org'])
384 self.assertEqual(self.dialer.calls[-1], (PUBLIC_V4_B, 443))
385 self.assertEqual(self.upstream.requests[-1]['headers']['host'], 'other.example.org')
386
387
388class NormalFetch(ProxyCase):
389 def test_public_http_fetch(self):
390 status, hdrs, body = self.get('http://example.com/ok')
391 self.assertEqual((status, body), (200, b'<p>hola</p>'))
392 self.assertEqual(hdrs['content-type'], 'text/html; charset=utf-8')
393 self.assertEqual(hdrs['x-proxy-truncated'], '0')
394 self.assertEqual(hdrs['x-proxy-upstream-status'], '200')
395 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)])
396 self.assertEqual(self.upstream.requests[0]['headers']['host'], 'example.com')
397
398 def test_https_connects_to_the_checked_address_with_the_name_as_sni(self):
399 status, _, body = self.get('https://example.com/ok')
400 self.assertEqual((status, body), (200, b'<p>hola</p>'))
401 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 443)])
402 self.assertEqual(self.tls.server_hostnames, ['example.com'])
403 self.assertEqual(self.upstream.requests[0]['headers']['host'], 'example.com')
404
405 def test_resolved_once_then_pinned(self):
406 # El DNS cambia de respuesta tras la primera consulta: no se le vuelve a preguntar.
407 status, _, _ = self.get('http://rebind.example.com/ok')
408 self.assertEqual(status, 200)
409 self.assertEqual(self.dns.calls, ['rebind.example.com'])
410 self.assertEqual(self.dialer.calls, [(PUBLIC_V4, 80)])
411
412 def test_public_ipv6_literal_and_explicit_default_port(self):
413 status, _, _ = self.get('http://[%s]/ok' % PUBLIC_V6)
414 self.assertEqual(status, 200)
415 self.assertEqual(self.dialer.calls, [(PUBLIC_V6, 80)])
416 self.assertEqual(self.upstream.requests[0]['headers']['host'], '[%s]' % PUBLIC_V6)
417 status, _, _ = self.get('http://example.com:80/ok')
418 self.assertEqual(status, 200)
419
420 def test_international_domain_names(self):
421 status, _, _ = self.get('http://bücher.example.com/ok')
422 self.assertEqual(status, 200)
423 self.assertEqual(self.upstream.requests[0]['headers']['host'], 'xn--bcher-kva.example.com')
424
425 def test_client_headers_never_reach_the_destination(self):
426 status, _, _ = self.get('http://example.com/ok', headers={
427 'Cookie': 'session=secreto', 'Authorization': 'Bearer secreto', 'Proxy-Authorization': 'Basic eA==',
428 'User-Agent': 'otro', 'Referer': 'https://claw.elffuss.com/', 'X-Forwarded-For': '192.0.2.1',
429 'Accept-Language': 'es'})
430 self.assertEqual(status, 200)
431 sent = self.upstream.requests[0]['headers']
432 self.assertEqual(set(sent), {'host', 'user-agent', 'accept-encoding', 'connection'})
433 self.assertEqual(sent['user-agent'], serve.PROXY_USER_AGENT)
434 self.assertEqual(sent['accept-encoding'], 'identity')
435
436 def test_response_headers_are_minimal(self):
437 self.upstream.routes['/noisy'] = (200, {
438 'Content-Type': 'text/html', 'Set-Cookie': 'a=b', 'Access-Control-Allow-Origin': '*',
439 'Access-Control-Allow-Credentials': 'true', 'X-Frame-Options': 'ALLOWALL',
440 'Content-Security-Policy': "script-src *", 'Link': '</x>; rel=preload'}, b'cuerpo')
441 status, hdrs, body = self.get('http://example.com/noisy')
442 self.assertEqual((status, body), (200, b'cuerpo'))
443 allowed = {'content-type', 'content-length', 'x-proxy-truncated', 'x-proxy-upstream-status',
444 'x-content-type-options', 'content-security-policy', 'cross-origin-resource-policy',
445 'referrer-policy', 'cache-control', 'server', 'date'}
446 self.assertLessEqual(set(hdrs), allowed)
447 self.assertEqual(hdrs['x-content-type-options'], 'nosniff')
448 self.assertIn('sandbox', hdrs['content-security-policy'])
449 self.assertNotIn('script-src', hdrs['content-security-policy'])
450
451 def test_odd_content_type_is_replaced(self):
452 self.upstream.routes['/ct'] = (200, {'Content-Type': 'text/html\x7f'}, b'x')
453 _, hdrs, _ = self.get('http://example.com/ct')
454 self.assertEqual(hdrs['content-type'], 'application/octet-stream')
455
456 def test_truncation_is_announced(self):
457 self.upstream.routes['/big'] = (200, {'Content-Type': 'text/plain'}, b'a' * 5000)
458 self.upstream.routes['/exact'] = (200, {'Content-Type': 'text/plain'}, b'b' * 1000)
459 with mock.patch.object(serve, 'MAX_PROXY_BYTES', 1000):
460 status, hdrs, body = self.get('http://example.com/big')
461 self.assertEqual((status, len(body), hdrs['x-proxy-truncated']), (200, 1000, '1'))
462 status, hdrs, body = self.get('http://example.com/exact')
463 self.assertEqual((status, len(body), hdrs['x-proxy-truncated']), (200, 1000, '0'))
464
465 def test_upstream_status_is_passed_through(self):
466 self.upstream.routes['/boom'] = (500, {'Content-Type': 'text/plain'}, b'roto')
467 for path, code in (('/missing', 404), ('/boom', 500)):
468 status, hdrs, _ = self.get('http://example.com' + path)
469 self.assertEqual((status, hdrs['x-proxy-upstream-status']), (code, str(code)))
470
471 def test_gzip_is_decoded_with_a_ceiling(self):
472 self.upstream.routes['/gz'] = (200, {'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'},
473 gzip.compress(b'hola ' * 100))
474 self.upstream.routes['/bomb'] = (200, {'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'},
475 gzip.compress(b'\0' * 5_000_000))
476 self.upstream.routes['/br'] = (200, {'Content-Type': 'text/plain', 'Content-Encoding': 'br'}, b'xx')
477 status, hdrs, body = self.get('http://example.com/gz')
478 self.assertEqual((status, body), (200, b'hola ' * 100))
479 self.assertNotIn('content-encoding', hdrs)
480 with mock.patch.object(serve, 'MAX_PROXY_BYTES', 1000):
481 status, hdrs, body = self.get('http://example.com/bomb')
482 self.assertEqual((status, len(body), hdrs['x-proxy-truncated']), (200, 1000, '1'))
483 status, hdrs, _ = self.get('http://example.com/br')
484 self.assertEqual((status, hdrs.get('x-proxy-error')), (502, 'encoding'))
485
486 def test_total_deadline_cuts_a_dripping_server(self):
487 def drip_body(h):
488 h.send_response(200)
489 h.send_header('Content-Type', 'text/plain')
490 h.end_headers()
491 try:
492 for _ in range(400):
493 h.wfile.write(b'x')
494 h.wfile.flush()
495 time.sleep(0.05)
496 except OSError:
497 pass
498
499 def drip_headers(h):
500 try:
501 h.wfile.write(b'HTTP/1.1 200 OK\r\n')
502 for _ in range(400):
503 h.wfile.write(b'X-Goteo: 1\r\n')
504 h.wfile.flush()
505 time.sleep(0.05)
506 except OSError:
507 pass
508 self.upstream.routes['/drip-body'] = drip_body
509 self.upstream.routes['/drip-headers'] = drip_headers
510 with mock.patch.object(serve, 'PROXY_TOTAL_TIMEOUT_S', 1), mock.patch.object(serve, 'PROXY_READ_TIMEOUT_S', 10):
511 for path in ('/drip-body', '/drip-headers'):
512 with self.subTest(path=path):
513 started = time.monotonic()
514 status, hdrs, _ = self.get('http://example.com' + path)
515 self.assertEqual((status, hdrs.get('x-proxy-error')), (504, 'timeout'))
516 self.assertLess(time.monotonic() - started, 8, 'el plazo total no cortó la conexión')
517
518 def test_rate_limit_per_client_ip(self):
519 with mock.patch.object(serve, 'PROXY_RATE', serve._RateLimiter(60, 3)):
520 codes = [self.get('http://example.com/ok', headers={'X-Forwarded-For': '192.0.2.10'})[0]
521 for _ in range(4)]
522 self.assertEqual(codes, [200, 200, 200, 429])
523 # La entrada que cuenta es la última (la que pone nginx), no la que escribe el cliente.
524 status, hdrs, _ = self.get('http://example.com/ok',
525 headers={'X-Forwarded-For': '192.0.2.99, 192.0.2.10'})
526 self.assertEqual((status, hdrs.get('x-proxy-error')), (429, 'rate-limited'))
527 self.assertIn('retry-after', hdrs)
528 status, _, _ = self.get('http://example.com/ok', headers={'X-Forwarded-For': '192.0.2.11'})
529 self.assertEqual(status, 200)
530 self.assertEqual(len(self.upstream.requests), 4)
531
532 def test_busy_when_every_slot_is_taken(self):
533 slots = threading.BoundedSemaphore(1)
534 slots.acquire()
535 with mock.patch.object(serve, 'PROXY_SLOTS', slots):
536 status, hdrs, _ = self.get('http://example.com/ok')
537 slots.release()
538 self.assertEqual((status, hdrs.get('x-proxy-error')), (503, 'busy'))
539 self.assertEqual(self.dialer.calls, [])
540
541 def test_same_origin_callers_are_served(self):
542 for headers in ({'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty'},
543 {'Origin': 'http://127.0.0.1:%d' % self.port}):
544 with self.subTest(headers=headers):
545 status, _, _ = self.get('http://example.com/ok', headers=headers)
546 self.assertEqual(status, 200)
547
548 def test_log_keeps_only_the_destination_host(self):
549 self.get('http://example.com/ruta-secreta?token=abc123')
550 line = [entry for entry in self.logs if '/proxy?' in entry]
551 self.assertEqual(len(line), 1, self.logs)
552 self.assertIn('http://example.com', line[0])
553 self.assertNotIn('ruta-secreta', line[0])
554 self.assertNotIn('abc123', line[0])
555
556 @unittest.skipUnless(hasattr(serve.Handler, 'report'), 'solo el servidor de Claw recoge /proxy/report')
557 def test_report_counts_the_address_nginx_appended(self):
558 with tempfile.TemporaryDirectory() as tmp:
559 reports = os.path.join(tmp, 'reports.jsonl')
560 with mock.patch.object(serve, 'REPORTS_PATH', reports), mock.patch.object(serve, 'REPORT_RATE', {}):
561 conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=10)
562 conn.request('POST', '/proxy/report', body=json.dumps({'app': 'prueba', 'message': 'hola'}),
563 headers={'Content-Type': 'application/json',
564 'X-Forwarded-For': 'escrito-por-el-cliente, 192.0.2.44'})
565 self.assertEqual(conn.getresponse().status, 200)
566 conn.close()
567 with open(reports, encoding='utf-8') as f:
568 self.assertEqual(json.loads(f.readline())['ip'], '192.0.2.44')
569
570
571class Units(unittest.TestCase):
572 def test_public_addresses_pass(self):
573 for ip in ('8.8.8.8', '1.1.1.1', PUBLIC_V4, PUBLIC_V6, '2001:4860:4860::8888', '2a00:1450:4001:80b::200e'):
574 with self.subTest(ip=ip):
575 self.assertTrue(serve._ip_is_public(ipaddress.ip_address(ip)))
576
577 def test_block_lists_alone_refuse_every_special_range(self):
578 # Las banderas de ipaddress cambian entre versiones de Python: las
579 # listas propias tienen que bastar por sí solas.
580 for ip in NON_PUBLIC_V4 + NON_PUBLIC_V6:
581 with self.subTest(ip=ip):
582 self.assertTrue(serve._in_block_lists(ipaddress.ip_address(ip)))
583 for ip in ('8.8.8.8', PUBLIC_V4, PUBLIC_V6, '2001:4860:4860::8888'):
584 self.assertFalse(serve._in_block_lists(ipaddress.ip_address(ip)))
585
586 def test_a_gzip_bomb_never_expands_past_the_ceiling(self):
587 packer = zlib.compressobj(9, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
588 zeros = b'\0' * (1 << 20)
589 bomb = b''.join(packer.compress(zeros) for _ in range(64)) + packer.flush() # 64 MB al descomprimir
590 tracemalloc.start()
591 try:
592 body, truncated = serve._inflate(bomb, 'gzip', 1000)
593 peak = tracemalloc.get_traced_memory()[1]
594 finally:
595 tracemalloc.stop()
596 self.assertEqual((len(body), truncated), (1000, True))
597 self.assertLess(peak, 8 << 20, 'descomprimió la bomba entera en memoria')
598
599 def test_forwarded_for_is_trusted_only_from_loopback(self):
600 def ip(peer, xff=None):
601 fake = types.SimpleNamespace(client_address=(peer, 40000),
602 headers={'X-Forwarded-For': xff} if xff is not None else {})
603 return serve.Handler.client_ip(fake)
604 self.assertEqual(ip('127.0.0.1', '203.0.113.5, 192.0.2.9'), '192.0.2.9')
605 self.assertEqual(ip('::1', '192.0.2.9'), '192.0.2.9')
606 self.assertEqual(ip('::ffff:127.0.0.1', '192.0.2.9'), '192.0.2.9')
607 self.assertEqual(ip('198.51.100.20', '192.0.2.9'), '198.51.100.20')
608 self.assertEqual(ip('127.0.0.1'), '127.0.0.1')
609
610 def test_ipv6_clients_are_limited_per_64(self):
611 self.assertEqual(serve._rate_key('2001:db8:1:2:3:4:5:6'), serve._rate_key('2001:db8:1:2:ffff::1'))
612 self.assertNotEqual(serve._rate_key('2001:db8:1:2::1'), serve._rate_key('2001:db8:1:3::1'))
613 self.assertEqual(serve._rate_key('::ffff:192.0.2.1'), '192.0.2.1')
614
615 def test_real_tls_context_verifies_certificates_and_names(self):
616 ctx = serve._tls_context()
617 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
618 self.assertTrue(ctx.check_hostname)
619
620 def test_listens_on_loopback_unless_told_otherwise(self):
621 seen = []
622
623 class FakeServer:
624 allow_reuse_address = False
625
626 def __init__(self, address, handler):
627 seen.append(address)
628
629 def __enter__(self):
630 return self
631
632 def __exit__(self, *exc):
633 return False
634
635 def serve_forever(self):
636 pass
637 env = {k: v for k, v in os.environ.items() if k != 'ELFFUSS_BIND'}
638 with mock.patch.object(serve.socketserver, 'ThreadingTCPServer', FakeServer), \
639 mock.patch.dict(os.environ, env, clear=True), mock.patch('builtins.print'):
640 serve.main(['serve.py', '8642'])
641 os.environ['ELFFUSS_BIND'] = '0.0.0.0'
642 serve.main(['serve.py', '8650'])
643 self.assertEqual(seen, [('127.0.0.1', 8642), ('0.0.0.0', 8650)])
644
645
646if __name__ == '__main__':
647 unittest.main()