utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | 5a0e2f408d4ae55ded31c97e3c394ec8b324df6312a90759c6f61ed6c9fea0ce |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-11 17:40 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 17:40 +02:00 |
| Parents | 7c24e7b60e19 |
2 files changed
modified server/serve.py +608 −20
| @@ -1,18 +1,33 @@ | ||
| 1 | 1 | #!/usr/bin/env python3 |
| 2 | -"""Servidor de desarrollo de Elffuss Code: sirve web/ y hace de proxy CORS en /proxy?url=… | |
| 2 | +"""Servidor de desarrollo de Elffuss Code: sirve web/ y hace de proxy en /proxy?url=… | |
| 3 | + | |
| 4 | +En producción, /proxy de code.elffuss.com lo atiende el backend compartido | |
| 5 | +(server/serve.py de elffuss-claw); este fichero es el de desarrollo, con el | |
| 6 | +mismo proxy. | |
| 3 | 7 | |
| 4 | 8 | Uso: python3 server/serve.py [puerto] (por defecto 8642) |
| 9 | + Escucha solo en 127.0.0.1; ELFFUSS_BIND=0.0.0.0 lo abre a la red. | |
| 5 | 10 | """ |
| 11 | +import functools | |
| 12 | +import http.client | |
| 6 | 13 | import http.server |
| 14 | +import ipaddress | |
| 15 | +import re | |
| 16 | +import socket | |
| 7 | 17 | import socketserver |
| 18 | +import ssl | |
| 8 | 19 | import sys |
| 20 | +import threading | |
| 21 | +import time | |
| 9 | 22 | import urllib.parse |
| 10 | 23 | import urllib.request |
| 24 | +import zlib | |
| 25 | +from collections import namedtuple | |
| 26 | +from http import HTTPStatus | |
| 11 | 27 | from pathlib import Path |
| 12 | 28 | |
| 13 | 29 | import os |
| 14 | 30 | |
| 15 | -PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8642 | |
| 16 | 31 | ROOT = os.environ.get('ELFFUSSCODE_ROOT') or str(Path(__file__).resolve().parent.parent / 'web') |
| 17 | 32 | MAX_PROXY_BYTES = 2_000_000 |
| 18 | 33 | # En desarrollo, /v1 (modelo) se reenvía a producción; en producción lo |
| @@ -20,6 +35,499 @@ | ||
| 20 | 35 | LM_UPSTREAM = os.environ.get('ELFFUSS_LM') or 'https://elffuss.com' |
| 21 | 36 | |
| 22 | 37 | |
| 38 | +# ---------------------------------------------------------------- /proxy?url=… | |
| 39 | +# El agente lee por aquí las webs que no mandan CORS. La petición la hace EL | |
| 40 | +# SERVIDOR, así que sin cerrojos esto es un SSRF de manual: cualquiera podría | |
| 41 | +# pedirle 127.0.0.1:<otro servicio de la máquina> o la metadata de la nube | |
| 42 | +# (169.254.169.254). Reglas: | |
| 43 | +# · solo http/https a los puertos 80 y 443, sin usuario:contraseña en la url; | |
| 44 | +# · el nombre se resuelve UNA vez, se rechaza si CUALQUIERA de sus direcciones | |
| 45 | +# no es pública, y se conecta a ESA dirección (Host y SNI siguen siendo el | |
| 46 | +# nombre): un DNS que cambie de respuesta entre la comprobación y la | |
| 47 | +# conexión (DNS rebinding) no cuela nada; | |
| 48 | +# · IPv4 solo en forma canónica a.b.c.d: 2130706433, 0x7f.1 o 0177.0.0.1 son | |
| 49 | +# 127.0.0.1 para el resolver, y se rechazan antes de llegar a él; | |
| 50 | +# · las redirecciones se siguen a mano y cada salto se valida igual; | |
| 51 | +# · no viaja ninguna cabecera del cliente (ni cookies ni Authorization) y el | |
| 52 | +# User-Agent es fijo; | |
| 53 | +# · tope de bytes con aviso (X-Proxy-Truncated: 1, nunca un 200 mudo), plazo | |
| 54 | +# total, y límites por IP y de peticiones simultáneas. | |
| 55 | +# El mismo código vive en server/serve.py de elffuss-claw (el backend de | |
| 56 | +# producción, que también atiende /proxy de code.elffuss.com): cambiar los dos. | |
| 57 | +PROXY_USER_AGENT = 'Mozilla/5.0 (Elffuss Code)' | |
| 58 | +PROXY_PORTS = (80, 443) | |
| 59 | +PROXY_MAX_URL = 4096 | |
| 60 | +PROXY_MAX_REDIRECTS = 5 | |
| 61 | +PROXY_CONNECT_TIMEOUT_S = 8 | |
| 62 | +PROXY_READ_TIMEOUT_S = 15 | |
| 63 | +PROXY_TOTAL_TIMEOUT_S = 30 # el proxy_read_timeout de nginx tiene que quedar por encima | |
| 64 | +PROXY_RATE_WINDOW_S, PROXY_RATE_MAX = 60, 30 | |
| 65 | +PROXY_SLOTS = threading.BoundedSemaphore(8) | |
| 66 | + | |
| 67 | +# Además de lo no público, lo que se liste aquí (CIDR separados por comas), por | |
| 68 | +# ejemplo las IP públicas de la propia máquina si algún vhost confía en ellas. | |
| 69 | +PROXY_DENY = tuple(ipaddress.ip_network(n.strip(), strict=False) | |
| 70 | + for n in (os.environ.get('ELFFUSS_PROXY_DENY') or '').split(',') if n.strip()) | |
| 71 | + | |
| 72 | +_V4_BLOCKED = tuple(ipaddress.ip_network(n) for n in ( | |
| 73 | + '0.0.0.0/8', # «esta red»: 0.0.0.0 acaba en localhost en Linux | |
| 74 | + '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', # privadas | |
| 75 | + '100.64.0.0/10', # CGNAT, con la metadata de algunas nubes (100.100.100.200) | |
| 76 | + '127.0.0.0/8', # loopback | |
| 77 | + '169.254.0.0/16', # enlace local, con la metadata de la nube (169.254.169.254) | |
| 78 | + '192.0.0.0/24', '192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', # IETF y documentación | |
| 79 | + '192.88.99.0/24', # relé 6to4 | |
| 80 | + '198.18.0.0/15', # bancos de pruebas | |
| 81 | + '224.0.0.0/4', # multicast (Python lo da por «global») | |
| 82 | + '240.0.0.0/4', # reservada, con 255.255.255.255 | |
| 83 | +)) | |
| 84 | +# Fuera de 2000::/3 queda todo lo que no es unicast global: ::, ::1, las | |
| 85 | +# IPv4-mapeadas (::ffff:a.b.c.d) y compatibles (::a.b.c.d), NAT64 (64:ff9b::), | |
| 86 | +# ULA (fc00::/7), enlace local (fe80::/10) y multicast (ff00::/8). | |
| 87 | +_V6_UNICAST = ipaddress.ip_network('2000::/3') | |
| 88 | +_V6_BLOCKED = tuple(ipaddress.ip_network(n) for n in ( | |
| 89 | + '2001::/23', # asignaciones del IETF, con Teredo (2001::/32) | |
| 90 | + '2001:db8::/32', # documentación | |
| 91 | + '2002::/16', # 6to4: lleva una IPv4 dentro | |
| 92 | + '3fff::/20', # documentación (RFC 9637) | |
| 93 | +)) | |
| 94 | +# Nombres que nunca son internet, se resuelvan a lo que se resuelvan. | |
| 95 | +_RESERVED_NAMES = ('localhost', 'local', 'internal', 'localdomain', 'home.arpa', | |
| 96 | + 'invalid', 'test', 'example', 'onion', 'alt') | |
| 97 | + | |
| 98 | +_CTRL_RE = re.compile(r'[\x00-\x1f\x7f]') | |
| 99 | +_NETLOC_RE = re.compile(r'(\[[^\[\]]*\]|[^\[\]:]*)(?::([0-9]*))?') | |
| 100 | +_LABEL_RE = re.compile(r'[a-z0-9_-]{1,63}') | |
| 101 | +_NUMERIC_LABEL_RE = re.compile(r'0x[0-9a-f]*|[0-9]+') | |
| 102 | +_OCTET_RE = re.compile(r'0|[1-9][0-9]{0,2}') | |
| 103 | +_CONTENT_TYPE_RE = re.compile(r'[\x21-\x7e][\x20-\x7e]{0,199}') | |
| 104 | +_REDIRECTS = (301, 302, 303, 307, 308) | |
| 105 | +_UPSTREAM_HEADERS = { # lo ÚNICO que se manda al destino, además de Host | |
| 106 | + 'User-Agent': PROXY_USER_AGENT, | |
| 107 | + 'Accept-Encoding': 'identity', | |
| 108 | + 'Connection': 'close', | |
| 109 | +} | |
| 110 | +_AI_FLAGS = getattr(socket, 'AI_ADDRCONFIG', 0) | |
| 111 | + | |
| 112 | +Target = namedtuple('Target', 'scheme host port path url addrs') | |
| 113 | +ProxyResult = namedtuple('ProxyResult', 'status upstream_status content_type body truncated') | |
| 114 | + | |
| 115 | + | |
| 116 | +class ProxyRefused(Exception): | |
| 117 | + """Respuesta de error del proxy: estado HTTP, código corto para la cabecera | |
| 118 | + X-Proxy-Error y un motivo legible. Nunca lleva la dirección resuelta.""" | |
| 119 | + | |
| 120 | + def __init__(self, status, code, detail): | |
| 121 | + super().__init__(detail) | |
| 122 | + self.status, self.code, self.detail = status, code, detail | |
| 123 | + | |
| 124 | + | |
| 125 | +def _parse_ip(text): | |
| 126 | + try: | |
| 127 | + return ipaddress.ip_address(str(text).split('%', 1)[0]) | |
| 128 | + except ValueError: | |
| 129 | + return None | |
| 130 | + | |
| 131 | + | |
| 132 | +def _in_block_lists(ip): | |
| 133 | + """Las listas de arriba, solas: no dependen de la versión de Python.""" | |
| 134 | + if ip.version == 6: | |
| 135 | + return ip not in _V6_UNICAST or any(ip in n for n in _V6_BLOCKED) | |
| 136 | + return any(ip in n for n in _V4_BLOCKED) | |
| 137 | + | |
| 138 | + | |
| 139 | +def _ip_is_public(ip): | |
| 140 | + """¿Se puede conectar a esta dirección? Las listas propias, y además las | |
| 141 | + banderas de ipaddress, que cambian de una versión de Python a otra (para | |
| 142 | + ellas 224.0.0.1 es «global»).""" | |
| 143 | + if _in_block_lists(ip): | |
| 144 | + return False | |
| 145 | + if (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast | |
| 146 | + or ip.is_reserved or ip.is_unspecified or not ip.is_global): | |
| 147 | + return False | |
| 148 | + return not any(ip in n for n in PROXY_DENY) | |
| 149 | + | |
| 150 | + | |
| 151 | +def _is_loopback(text): | |
| 152 | + ip = _parse_ip(text) | |
| 153 | + if ip is not None and ip.version == 6 and ip.ipv4_mapped is not None: | |
| 154 | + ip = ip.ipv4_mapped | |
| 155 | + return ip is not None and ip.is_loopback | |
| 156 | + | |
| 157 | + | |
| 158 | +def _rate_key(ip_text): | |
| 159 | + """Clave del límite por IP: una IPv6 cuenta por su /64, que es lo que | |
| 160 | + tiene cualquier cliente para él solo.""" | |
| 161 | + ip = _parse_ip(ip_text) | |
| 162 | + if ip is None: | |
| 163 | + return str(ip_text)[:64] | |
| 164 | + if ip.version == 6: | |
| 165 | + if ip.ipv4_mapped is not None: | |
| 166 | + return str(ip.ipv4_mapped) | |
| 167 | + return str(ipaddress.IPv6Network((int(ip) >> 64 << 64, 64))) | |
| 168 | + return str(ip) | |
| 169 | + | |
| 170 | + | |
| 171 | +def _parse_host(raw): | |
| 172 | + """→ (ip, host): ip si el host es una dirección literal (y host su forma | |
| 173 | + canónica); si es un nombre, (None, nombre en ASCII y minúsculas).""" | |
| 174 | + if raw.startswith('['): | |
| 175 | + inner = raw[1:-1] | |
| 176 | + if '%' in inner: # zona (fe80::1%eth0): solo existe en enlace local | |
| 177 | + raise ProxyRefused(403, 'forbidden-destination', 'destino no permitido (dirección de enlace local)') | |
| 178 | + try: | |
| 179 | + ip = ipaddress.IPv6Address(inner) | |
| 180 | + except ValueError: | |
| 181 | + raise ProxyRefused(400, 'bad-host', 'dirección IPv6 mal formada') from None | |
| 182 | + return ip, str(ip) | |
| 183 | + host = raw[:-1] if raw.endswith('.') else raw | |
| 184 | + try: | |
| 185 | + host = host.encode('idna').decode('ascii').lower() | |
| 186 | + except UnicodeError: | |
| 187 | + raise ProxyRefused(400, 'bad-host', 'nombre de host no válido') from None | |
| 188 | + labels = host.split('.') | |
| 189 | + if not all(_LABEL_RE.fullmatch(label) for label in labels): | |
| 190 | + raise ProxyRefused(400, 'bad-host', 'nombre de host no válido') | |
| 191 | + # Si la última etiqueta es un número, el resolver lo toma por una IPv4 | |
| 192 | + # (inet_aton acepta decimal, octal, hex y formas cortas): solo se admite | |
| 193 | + # la forma a.b.c.d, en decimal y sin ceros a la izquierda. | |
| 194 | + if _NUMERIC_LABEL_RE.fullmatch(labels[-1]): | |
| 195 | + if len(labels) != 4 or not all(_OCTET_RE.fullmatch(x) and int(x) <= 255 for x in labels): | |
| 196 | + raise ProxyRefused(400, 'odd-ip', 'las IPv4 van en forma a.b.c.d, en decimal') | |
| 197 | + return ipaddress.IPv4Address(host), host | |
| 198 | + if len(labels) < 2 or any(host == s or host.endswith('.' + s) for s in _RESERVED_NAMES): | |
| 199 | + raise ProxyRefused(403, 'forbidden-destination', 'destino no permitido (nombre local o reservado)') | |
| 200 | + return None, host | |
| 201 | + | |
| 202 | + | |
| 203 | +def _getaddrinfo(*args): # los tests sustituyen esto: es el único punto de DNS | |
| 204 | + return socket.getaddrinfo(*args) | |
| 205 | + | |
| 206 | + | |
| 207 | +def _resolve(host, port): | |
| 208 | + """Resuelve UNA vez. Si alguna dirección no es pública se rechaza todo: | |
| 209 | + elegir la buena dejaría a un DNS hostil decidir a cuál se conecta.""" | |
| 210 | + try: | |
| 211 | + infos = _getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP, _AI_FLAGS) | |
| 212 | + except (OSError, UnicodeError): | |
| 213 | + raise ProxyRefused(502, 'dns', 'no se pudo resolver el host') from None | |
| 214 | + addrs = [] | |
| 215 | + for family, _type, _proto, _canon, sockaddr in infos: | |
| 216 | + ip = _parse_ip(sockaddr[0]) if family in (socket.AF_INET, socket.AF_INET6) else None | |
| 217 | + if ip is None or not _ip_is_public(ip): | |
| 218 | + raise ProxyRefused(403, 'forbidden-destination', | |
| 219 | + 'destino no permitido (el nombre resuelve a una dirección no pública)') | |
| 220 | + if (family, sockaddr) not in addrs: | |
| 221 | + addrs.append((family, sockaddr)) | |
| 222 | + if not addrs: | |
| 223 | + raise ProxyRefused(502, 'dns', 'el host no tiene direcciones') | |
| 224 | + return addrs | |
| 225 | + | |
| 226 | + | |
| 227 | +def _check_url(url): | |
| 228 | + """Valida una url y la resuelve: → Target con las direcciones ya | |
| 229 | + comprobadas, que son las únicas a las que se conectará.""" | |
| 230 | + if not url: | |
| 231 | + raise ProxyRefused(400, 'bad-url', 'falta el parámetro url') | |
| 232 | + if len(url) > PROXY_MAX_URL or _CTRL_RE.search(url): | |
| 233 | + raise ProxyRefused(400, 'bad-url', 'url demasiado larga o con caracteres de control') | |
| 234 | + try: | |
| 235 | + parts = urllib.parse.urlsplit(url.strip()) | |
| 236 | + except ValueError: | |
| 237 | + raise ProxyRefused(400, 'bad-url', 'url mal formada') from None | |
| 238 | + scheme = parts.scheme.lower() | |
| 239 | + if scheme not in ('http', 'https'): | |
| 240 | + raise ProxyRefused(400, 'bad-scheme', 'solo http:// y https://') | |
| 241 | + if '@' in parts.netloc: | |
| 242 | + raise ProxyRefused(400, 'userinfo', 'la url no puede llevar usuario ni contraseña') | |
| 243 | + m = _NETLOC_RE.fullmatch(parts.netloc) | |
| 244 | + if not m or not m.group(1): | |
| 245 | + raise ProxyRefused(400, 'bad-host', 'url sin host válido') | |
| 246 | + default_port = 443 if scheme == 'https' else 80 | |
| 247 | + port = int(m.group(2)) if m.group(2) else default_port | |
| 248 | + if port not in PROXY_PORTS: | |
| 249 | + raise ProxyRefused(403, 'forbidden-port', 'solo se permiten los puertos 80 y 443') | |
| 250 | + ip, host = _parse_host(m.group(1)) | |
| 251 | + if ip is None: | |
| 252 | + addrs = _resolve(host, port) | |
| 253 | + elif not _ip_is_public(ip): | |
| 254 | + raise ProxyRefused(403, 'forbidden-destination', 'destino no permitido (dirección no pública)') | |
| 255 | + elif ip.version == 6: | |
| 256 | + addrs = [(socket.AF_INET6, (host, port, 0, 0))] | |
| 257 | + else: | |
| 258 | + addrs = [(socket.AF_INET, (host, port))] | |
| 259 | + try: | |
| 260 | + path = urllib.parse.quote(parts.path or '/', safe="/%:@!$&'()*+,;=~") | |
| 261 | + if parts.query: | |
| 262 | + path += '?' + urllib.parse.quote(parts.query, safe="/?%:@!$&'()*+,;=~") | |
| 263 | + except UnicodeError: | |
| 264 | + raise ProxyRefused(400, 'bad-url', 'url mal formada') from None | |
| 265 | + netloc = ('[%s]' % host if ':' in host else host) + ('' if port == default_port else ':%d' % port) | |
| 266 | + return Target(scheme, host, port, path, '%s://%s%s' % (scheme, netloc, path), tuple(addrs)) | |
| 267 | + | |
| 268 | + | |
| 269 | +def _shutdown(sock): | |
| 270 | + try: # socket.socket.shutdown también sobre un SSLSocket: corta el fd sin tocar el estado TLS | |
| 271 | + socket.socket.shutdown(sock, socket.SHUT_RDWR) | |
| 272 | + except (OSError, TypeError, ValueError): | |
| 273 | + pass | |
| 274 | + | |
| 275 | + | |
| 276 | +class _Deadline: | |
| 277 | + """Plazo TOTAL de una petición al proxy, redirecciones incluidas. Los | |
| 278 | + timeouts de socket cuentan por operación, y un servidor que gotea un byte | |
| 279 | + cada pocos segundos los esquiva todos: al vencer el plazo se corta el | |
| 280 | + socket en uso y la lectura bloqueada falla.""" | |
| 281 | + | |
| 282 | + def __init__(self, seconds): | |
| 283 | + self._end = time.monotonic() + seconds | |
| 284 | + self._lock = threading.Lock() | |
| 285 | + self._sock = None | |
| 286 | + self._fired = False | |
| 287 | + self._timer = threading.Timer(seconds, self._fire) | |
| 288 | + self._timer.daemon = True | |
| 289 | + self._timer.start() | |
| 290 | + | |
| 291 | + def remaining(self): | |
| 292 | + return self._end - time.monotonic() | |
| 293 | + | |
| 294 | + def expired(self): | |
| 295 | + return self._fired or self.remaining() <= 0 | |
| 296 | + | |
| 297 | + def watch(self, sock): | |
| 298 | + with self._lock: | |
| 299 | + self._sock = sock | |
| 300 | + fired = self._fired | |
| 301 | + if fired: | |
| 302 | + _shutdown(sock) | |
| 303 | + | |
| 304 | + def _fire(self): | |
| 305 | + with self._lock: | |
| 306 | + self._fired = True | |
| 307 | + sock = self._sock | |
| 308 | + if sock is not None: | |
| 309 | + _shutdown(sock) | |
| 310 | + | |
| 311 | + def cancel(self): | |
| 312 | + self._timer.cancel() | |
| 313 | + with self._lock: | |
| 314 | + self._sock = None | |
| 315 | + | |
| 316 | + | |
| 317 | +def _dial(family, sockaddr, timeout): | |
| 318 | + """Conexión TCP a una dirección YA validada (los tests sustituyen esto).""" | |
| 319 | + sock = socket.socket(family, socket.SOCK_STREAM) | |
| 320 | + try: | |
| 321 | + sock.settimeout(timeout) | |
| 322 | + sock.connect(sockaddr) | |
| 323 | + except BaseException: | |
| 324 | + sock.close() | |
| 325 | + raise | |
| 326 | + return sock | |
| 327 | + | |
| 328 | + | |
| 329 | +def _connect(target, deadline): | |
| 330 | + last = None | |
| 331 | + for family, sockaddr in target.addrs[:3]: | |
| 332 | + remaining = deadline.remaining() | |
| 333 | + if remaining <= 0: | |
| 334 | + break | |
| 335 | + try: | |
| 336 | + sock = _dial(family, sockaddr, min(PROXY_CONNECT_TIMEOUT_S, remaining)) | |
| 337 | + except OSError as e: | |
| 338 | + last = e | |
| 339 | + continue | |
| 340 | + sock.settimeout(PROXY_READ_TIMEOUT_S) | |
| 341 | + deadline.watch(sock) | |
| 342 | + return sock | |
| 343 | + if deadline.expired(): | |
| 344 | + raise socket.timeout('plazo agotado') | |
| 345 | + raise last or OSError('sin conexión') | |
| 346 | + | |
| 347 | + | |
| 348 | +@functools.lru_cache(maxsize=None) | |
| 349 | +def _tls_context(): | |
| 350 | + ctx = ssl.create_default_context() # verifica certificado y nombre | |
| 351 | + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 | |
| 352 | + return ctx | |
| 353 | + | |
| 354 | + | |
| 355 | +class _PinnedHTTPConnection(http.client.HTTPConnection): | |
| 356 | + """HTTP contra la dirección ya validada; Host sigue siendo el nombre.""" | |
| 357 | + | |
| 358 | + def __init__(self, target, deadline): | |
| 359 | + super().__init__(target.host, target.port, timeout=PROXY_READ_TIMEOUT_S) | |
| 360 | + self._target, self._deadline = target, deadline | |
| 361 | + | |
| 362 | + def connect(self): | |
| 363 | + self.sock = _connect(self._target, self._deadline) | |
| 364 | + | |
| 365 | + | |
| 366 | +class _PinnedHTTPSConnection(http.client.HTTPSConnection): | |
| 367 | + """HTTPS contra la dirección ya validada; el SNI y la verificación del | |
| 368 | + certificado van contra el nombre, no contra la IP.""" | |
| 369 | + | |
| 370 | + def __init__(self, target, deadline): | |
| 371 | + self._tls = _tls_context() | |
| 372 | + super().__init__(target.host, target.port, timeout=PROXY_READ_TIMEOUT_S, context=self._tls) | |
| 373 | + self._target, self._deadline = target, deadline | |
| 374 | + | |
| 375 | + def connect(self): | |
| 376 | + raw = _connect(self._target, self._deadline) | |
| 377 | + try: | |
| 378 | + tls = self._tls.wrap_socket(raw, server_hostname=self._target.host, | |
| 379 | + do_handshake_on_connect=False) | |
| 380 | + except BaseException: | |
| 381 | + raw.close() | |
| 382 | + raise | |
| 383 | + try: | |
| 384 | + tls.settimeout(PROXY_READ_TIMEOUT_S) | |
| 385 | + self._deadline.watch(tls) # el socket de antes ya no es dueño del fd | |
| 386 | + tls.do_handshake() | |
| 387 | + except BaseException: | |
| 388 | + tls.close() | |
| 389 | + raise | |
| 390 | + self.sock = tls | |
| 391 | + | |
| 392 | + | |
| 393 | +def _header_text(value): | |
| 394 | + """http.client entrega las cabeceras como latin-1; una Location con UTF-8 | |
| 395 | + crudo se recupera aquí antes de volver a codificarla.""" | |
| 396 | + try: | |
| 397 | + return value.encode('latin-1').decode('utf-8') | |
| 398 | + except UnicodeError: | |
| 399 | + return value | |
| 400 | + | |
| 401 | + | |
| 402 | +def _inflate(data, encoding, limit): | |
| 403 | + for wbits in ((16 + zlib.MAX_WBITS,) if encoding != 'deflate' else (zlib.MAX_WBITS, -zlib.MAX_WBITS)): | |
| 404 | + try: | |
| 405 | + out = zlib.decompressobj(wbits).decompress(data, limit + 1) # nunca más de limit+1 | |
| 406 | + except zlib.error: | |
| 407 | + continue | |
| 408 | + return out[:limit], len(out) > limit | |
| 409 | + raise ProxyRefused(502, 'encoding', 'la web mandó un cuerpo comprimido corrupto') | |
| 410 | + | |
| 411 | + | |
| 412 | +def _read_body(resp): | |
| 413 | + limit = MAX_PROXY_BYTES | |
| 414 | + chunks, total = [], 0 | |
| 415 | + while total <= limit: | |
| 416 | + chunk = resp.read(min(1 << 16, limit + 1 - total)) | |
| 417 | + if not chunk: | |
| 418 | + break | |
| 419 | + chunks.append(chunk) | |
| 420 | + total += len(chunk) | |
| 421 | + raw, truncated = b''.join(chunks), total > limit | |
| 422 | + # Se pide identity; si aun así llega comprimido, se descomprime con tope | |
| 423 | + # (una bomba gzip no pasa de limit+1 bytes) y el cliente lo recibe plano. | |
| 424 | + encoding = (resp.getheader('Content-Encoding') or '').strip().lower() | |
| 425 | + if encoding in ('', 'identity'): | |
| 426 | + return raw[:limit], truncated | |
| 427 | + if encoding not in ('gzip', 'x-gzip', 'deflate'): | |
| 428 | + raise ProxyRefused(502, 'encoding', 'la web respondió comprimida en un formato no soportado') | |
| 429 | + body, more = _inflate(raw, encoding, limit) | |
| 430 | + return body, truncated or more | |
| 431 | + | |
| 432 | + | |
| 433 | +def _fetch(url, deadline): | |
| 434 | + for hop in range(PROXY_MAX_REDIRECTS + 1): | |
| 435 | + try: | |
| 436 | + target = _check_url(url) | |
| 437 | + except ProxyRefused as e: | |
| 438 | + if hop == 0 or e.code == 'dns': | |
| 439 | + raise | |
| 440 | + if e.status == 403: | |
| 441 | + raise ProxyRefused(403, 'forbidden-redirect', 'la web redirige a un destino no permitido') from None | |
| 442 | + raise ProxyRefused(502, 'bad-redirect', 'la web redirige a una url no válida') from None | |
| 443 | + conn_class = _PinnedHTTPSConnection if target.scheme == 'https' else _PinnedHTTPConnection | |
| 444 | + conn = conn_class(target, deadline) | |
| 445 | + try: | |
| 446 | + conn.request('GET', target.path, headers=_UPSTREAM_HEADERS) | |
| 447 | + resp = conn.getresponse() | |
| 448 | + if resp.status in _REDIRECTS: | |
| 449 | + location = resp.getheader('Location') | |
| 450 | + if not location or not location.strip(): | |
| 451 | + raise ProxyRefused(502, 'bad-redirect', 'redirección sin destino') | |
| 452 | + url = urllib.parse.urljoin(target.url, _header_text(location).strip()) | |
| 453 | + continue | |
| 454 | + content_type = (resp.getheader('Content-Type') or '').strip() | |
| 455 | + if not _CONTENT_TYPE_RE.fullmatch(content_type): | |
| 456 | + content_type = 'application/octet-stream' | |
| 457 | + body, truncated = _read_body(resp) | |
| 458 | + # Cortar el socket al vencer el plazo se lee como un fin de | |
| 459 | + # fichero, y para http.client eso puede ser un final normal (unas | |
| 460 | + # cabeceras a medias, un cuerpo sin longitud): lo leído después | |
| 461 | + # del corte no es la respuesta, es un 504. | |
| 462 | + if deadline.expired(): | |
| 463 | + raise socket.timeout('plazo agotado') | |
| 464 | + # El estado real del destino (un 404 es un 404, no un 200 ni un | |
| 465 | + # 502); lo que no es un final normal (1xx, 3xx sueltos) es un 502. | |
| 466 | + status = resp.status if 200 <= resp.status < 300 or 400 <= resp.status < 600 else 502 | |
| 467 | + return ProxyResult(status, resp.status, content_type, body, truncated) | |
| 468 | + finally: | |
| 469 | + conn.close() | |
| 470 | + raise ProxyRefused(502, 'too-many-redirects', 'demasiadas redirecciones') | |
| 471 | + | |
| 472 | + | |
| 473 | +def proxy_fetch(url): | |
| 474 | + """GET a una url pública con todas las reglas de arriba → ProxyResult, o | |
| 475 | + ProxyRefused con el estado y el motivo.""" | |
| 476 | + deadline = _Deadline(PROXY_TOTAL_TIMEOUT_S) | |
| 477 | + try: | |
| 478 | + return _fetch(url, deadline) | |
| 479 | + except ProxyRefused: | |
| 480 | + raise | |
| 481 | + except Exception as e: # noqa: BLE001 — cualquier fallo del destino es un 502/504 con motivo | |
| 482 | + if deadline.expired() or isinstance(e, socket.timeout): | |
| 483 | + raise ProxyRefused(504, 'timeout', 'la web no respondió a tiempo') from None | |
| 484 | + if isinstance(e, ssl.SSLError): | |
| 485 | + raise ProxyRefused(502, 'tls', 'fallo TLS con la web (%s)' % type(e).__name__) from None | |
| 486 | + raise ProxyRefused(502, 'upstream', 'no se pudo leer la web (%s)' % type(e).__name__) from None | |
| 487 | + finally: | |
| 488 | + deadline.cancel() | |
| 489 | + | |
| 490 | + | |
| 491 | +class _RateLimiter: | |
| 492 | + """Ventana deslizante por clave, segura entre hilos, que olvida las claves | |
| 493 | + viejas (la de /proxy/report crece sin fin).""" | |
| 494 | + | |
| 495 | + def __init__(self, window_s, max_hits): | |
| 496 | + self.window_s, self.max_hits = window_s, max_hits | |
| 497 | + self._hits = {} | |
| 498 | + self._lock = threading.Lock() | |
| 499 | + self._swept = time.monotonic() | |
| 500 | + | |
| 501 | + def allow(self, key): | |
| 502 | + now = time.monotonic() | |
| 503 | + with self._lock: | |
| 504 | + if now - self._swept > self.window_s: | |
| 505 | + self._hits = {k: v for k, v in self._hits.items() if v and now - v[-1] < self.window_s} | |
| 506 | + self._swept = now | |
| 507 | + hits = [t for t in self._hits.get(key, ()) if now - t < self.window_s] | |
| 508 | + ok = len(hits) < self.max_hits | |
| 509 | + if ok: | |
| 510 | + hits.append(now) | |
| 511 | + self._hits[key] = hits | |
| 512 | + return ok | |
| 513 | + | |
| 514 | + | |
| 515 | +PROXY_RATE = _RateLimiter(PROXY_RATE_WINDOW_S, PROXY_RATE_MAX) | |
| 516 | + | |
| 517 | + | |
| 518 | +def _log_target(path): | |
| 519 | + """Para el log, solo esquema y host del destino: la ruta y la query pueden | |
| 520 | + llevar tokens, y lo que el usuario lee no tiene por qué quedar escrito.""" | |
| 521 | + try: | |
| 522 | + url = (urllib.parse.parse_qs(urllib.parse.urlsplit(path).query).get('url') or [''])[0] | |
| 523 | + parts = urllib.parse.urlsplit(url.strip()) | |
| 524 | + host = parts.hostname or '' | |
| 525 | + shown = '%s://%s' % (parts.scheme, '[%s]' % host if ':' in host else host) | |
| 526 | + except ValueError: | |
| 527 | + shown = '?' | |
| 528 | + return re.sub(r'[^A-Za-z0-9.:_\-\[\]/]', '?', shown)[:120] | |
| 529 | + | |
| 530 | + | |
| 23 | 531 | class Handler(http.server.SimpleHTTPRequestHandler): |
| 24 | 532 | def __init__(self, *args, **kwargs): |
| 25 | 533 | super().__init__(*args, directory=ROOT, **kwargs) |
| @@ -40,6 +548,19 @@ | ||
| 40 | 548 | return self.forward_lm() |
| 41 | 549 | self.send_error(404) |
| 42 | 550 | |
| 551 | + def client_ip(self): | |
| 552 | + """IP del cliente para los límites. Detrás de nginx la conexión llega | |
| 553 | + SIEMPRE de 127.0.0.1, así que manda X-Forwarded-For, pero solo si lo | |
| 554 | + pone alguien en loopback (nginx) y tomando la ÚLTIMA entrada: con | |
| 555 | + $proxy_add_x_forwarded_for las anteriores las escribe el propio cliente.""" | |
| 556 | + peer = self.client_address[0] | |
| 557 | + xff = self.headers.get('X-Forwarded-For') or '' | |
| 558 | + if xff.strip() and _is_loopback(peer): | |
| 559 | + last = xff.split(',')[-1].strip() | |
| 560 | + if last: | |
| 561 | + return last[:64] | |
| 562 | + return peer | |
| 563 | + | |
| 43 | 564 | def forward_lm(self): |
| 44 | 565 | """Reenvía /v1/* (API del modelo) al servidor de producción, con streaming.""" |
| 45 | 566 | length = int(self.headers.get('Content-Length') or 0) |
| @@ -61,29 +582,96 @@ | ||
| 61 | 582 | except Exception as e: # noqa: BLE001 |
| 62 | 583 | self.send_error(502, f'lm: {e}') |
| 63 | 584 | |
| 585 | + def _proxy_caller_ok(self): | |
| 586 | + """Solo la propia página (fetch del mismo origen) o un cliente que no es | |
| 587 | + un navegador (curl, el chequeo de salud). Fuera navegaciones, iframes, | |
| 588 | + <img>/<script> y cualquier otro origen: así una web ajena no usa este | |
| 589 | + servidor de proxy ni abre aquí HTML de terceros con nuestro origen.""" | |
| 590 | + site = (self.headers.get('Sec-Fetch-Site') or '').strip().lower() | |
| 591 | + dest = (self.headers.get('Sec-Fetch-Dest') or '').strip().lower() | |
| 592 | + if site not in ('', 'same-origin') or dest not in ('', 'empty'): | |
| 593 | + return False | |
| 594 | + origin = self.headers.get('Origin') | |
| 595 | + if origin is not None: | |
| 596 | + host = (self.headers.get('Host') or '').strip().lower() | |
| 597 | + try: | |
| 598 | + return urllib.parse.urlsplit(origin.strip()).netloc.lower() == host | |
| 599 | + except ValueError: | |
| 600 | + return False | |
| 601 | + return True | |
| 602 | + | |
| 603 | + def _proxy_safety_headers(self): | |
| 604 | + # Lo que sale de aquí es contenido de TERCEROS servido con NUESTRO | |
| 605 | + # origen: si alguien abre /proxy?url=<su html> como página, el sandbox | |
| 606 | + # sin scripts le quita el origen y no ejecuta nada. Sin CORS: la app lo | |
| 607 | + # pide desde su mismo origen y ninguna otra web tiene por qué leerlo. | |
| 608 | + self.send_header('X-Content-Type-Options', 'nosniff') | |
| 609 | + self.send_header('Content-Security-Policy', "sandbox; default-src 'none'; frame-ancestors 'none'") | |
| 610 | + self.send_header('Cross-Origin-Resource-Policy', 'same-origin') | |
| 611 | + self.send_header('Referrer-Policy', 'no-referrer') | |
| 612 | + | |
| 613 | + def _proxy_fail(self, status, code, detail, retry_after=None): | |
| 614 | + body = (detail + '\n').encode('utf-8') | |
| 615 | + self.send_response(status) | |
| 616 | + self.send_header('Content-Type', 'text/plain; charset=utf-8') | |
| 617 | + self.send_header('Content-Length', str(len(body))) | |
| 618 | + self.send_header('X-Proxy-Error', code) | |
| 619 | + if retry_after: | |
| 620 | + self.send_header('Retry-After', str(retry_after)) | |
| 621 | + self._proxy_safety_headers() | |
| 622 | + self.end_headers() | |
| 623 | + self.wfile.write(body) | |
| 624 | + | |
| 64 | 625 | def proxy(self): |
| 65 | - qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) | |
| 66 | - url = (qs.get('url') or [None])[0] | |
| 67 | - if not url or not url.startswith(('http://', 'https://')): | |
| 68 | - return self.send_error(400, 'url invalida') | |
| 69 | - try: | |
| 70 | - req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (Elffuss Code)'}) | |
| 71 | - with urllib.request.urlopen(req, timeout=20) as r: | |
| 72 | - body = r.read(MAX_PROXY_BYTES) | |
| 73 | - self.send_response(200) | |
| 74 | - self.send_header('Content-Type', r.headers.get('Content-Type', 'text/html')) | |
| 75 | - self.send_header('Access-Control-Allow-Origin', '*') | |
| 76 | - self.end_headers() | |
| 77 | - self.wfile.write(body) | |
| 78 | - except Exception as e: # noqa: BLE001 — el agente recibe el motivo | |
| 79 | - self.send_error(502, f'proxy: {e}') | |
| 626 | + if not PROXY_RATE.allow(_rate_key(self.client_ip())): | |
| 627 | + return self._proxy_fail(429, 'rate-limited', 'demasiadas peticiones al proxy, espera un poco', | |
| 628 | + retry_after=PROXY_RATE_WINDOW_S) | |
| 629 | + if not self._proxy_caller_ok(): | |
| 630 | + return self._proxy_fail(403, 'cross-site', 'el proxy solo atiende a la propia app') | |
| 631 | + qs = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) | |
| 632 | + url = (qs.get('url') or [''])[0] | |
| 633 | + if not PROXY_SLOTS.acquire(blocking=False): | |
| 634 | + return self._proxy_fail(503, 'busy', 'proxy ocupado, prueba en unos segundos', retry_after=5) | |
| 635 | + try: | |
| 636 | + res = proxy_fetch(url) | |
| 637 | + except ProxyRefused as e: | |
| 638 | + return self._proxy_fail(e.status, e.code, e.detail) | |
| 639 | + finally: | |
| 640 | + PROXY_SLOTS.release() | |
| 641 | + body = b'' if res.status in (204, 205) else res.body | |
| 642 | + self.send_response(res.status) | |
| 643 | + self.send_header('Content-Type', res.content_type) | |
| 644 | + self.send_header('Content-Length', str(len(body))) | |
| 645 | + self.send_header('X-Proxy-Truncated', '1' if res.truncated else '0') | |
| 646 | + self.send_header('X-Proxy-Upstream-Status', str(res.upstream_status)) | |
| 647 | + self._proxy_safety_headers() | |
| 648 | + self.end_headers() | |
| 649 | + self.wfile.write(body) | |
| 650 | + | |
| 651 | + def log_request(self, code='-', size='-'): | |
| 652 | + if isinstance(code, HTTPStatus): | |
| 653 | + code = code.value | |
| 654 | + line = self.requestline | |
| 655 | + path = getattr(self, 'path', '') or '' | |
| 656 | + if path.startswith('/proxy?'): | |
| 657 | + line = '%s /proxy?url=%s' % (self.command, _log_target(path)) | |
| 658 | + self.log_message('"%s" %s %s', line, str(code), str(size)) | |
| 80 | 659 | |
| 81 | 660 | def log_message(self, fmt, *args): |
| 82 | 661 | sys.stderr.write('· %s\n' % (fmt % args)) |
| 83 | 662 | |
| 84 | 663 | |
| 85 | -if __name__ == '__main__': | |
| 664 | +def main(argv=None): | |
| 665 | + argv = sys.argv if argv is None else argv | |
| 666 | + port = int(argv[1]) if len(argv) > 1 else 8642 | |
| 667 | + # Solo loopback salvo que se pida: en local basta localhost, y abrirlo a la | |
| 668 | + # red expone también el proxy a cualquiera que llegue a este puerto. | |
| 669 | + bind = os.environ.get('ELFFUSS_BIND', '127.0.0.1') | |
| 86 | 670 | socketserver.ThreadingTCPServer.allow_reuse_address = True |
| 87 | - with socketserver.ThreadingTCPServer(('', PORT), Handler) as httpd: | |
| 88 | - print(f'✳ Elffuss Code · http://localhost:{PORT}') | |
| 671 | + with socketserver.ThreadingTCPServer((bind, port), Handler) as httpd: | |
| 672 | + print(f'✳ Elffuss Code · http://localhost:{port}') | |
| 89 | 673 | httpd.serve_forever() |
| 674 | + | |
| 675 | + | |
| 676 | +if __name__ == '__main__': | |
| 677 | + main() |
added tests/test_proxy.py +647 −0
| @@ -0,0 +1,647 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""Pruebas del proxy endurecido (/proxy?url=…) de server/serve.py. | |
| 3 | + | |
| 4 | +Sin red: el DNS (serve._getaddrinfo) y la conexión TCP (serve._dial) se | |
| 5 | +sustituyen, e «internet» es un servidor HTTP local al que el dialer desvía las | |
| 6 | +direcciones públicas de la prueba. Cualquier otra dirección a la que el proxy | |
| 7 | +intentara conectar queda apuntada en el dialer y se rechaza, así que cada | |
| 8 | +vector 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 | +""" | |
| 13 | +import gzip | |
| 14 | +import http.client | |
| 15 | +import http.server | |
| 16 | +import importlib.util | |
| 17 | +import ipaddress | |
| 18 | +import json | |
| 19 | +import os | |
| 20 | +import socket | |
| 21 | +import socketserver | |
| 22 | +import ssl | |
| 23 | +import sys | |
| 24 | +import tempfile | |
| 25 | +import threading | |
| 26 | +import time | |
| 27 | +import tracemalloc | |
| 28 | +import types | |
| 29 | +import unittest | |
| 30 | +import urllib.parse | |
| 31 | +import zlib | |
| 32 | +from pathlib import Path | |
| 33 | +from unittest import mock | |
| 34 | + | |
| 35 | +sys.dont_write_bytecode = True # que la prueba no deje __pycache__ junto a serve.py | |
| 36 | +SERVE_PY = Path(__file__).resolve().parent.parent / 'server' / 'serve.py' | |
| 37 | +_spec = importlib.util.spec_from_file_location('elffuss_serve', SERVE_PY) | |
| 38 | +serve = importlib.util.module_from_spec(_spec) | |
| 39 | +_spec.loader.exec_module(serve) | |
| 40 | + | |
| 41 | +PUBLIC_V4 = '93.184.215.14' | |
| 42 | +PUBLIC_V4_B = '93.184.215.15' | |
| 43 | +PUBLIC_V6 = '2606:4700:4700::1111' | |
| 44 | +NON_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') | |
| 48 | +NON_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 | + | |
| 54 | +class 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 | + | |
| 96 | +class 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 | + | |
| 119 | +class 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 | + | |
| 135 | +class _PlainAsTLS(socket.socket): | |
| 136 | + def do_handshake(self): | |
| 137 | + pass | |
| 138 | + | |
| 139 | + | |
| 140 | +class 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 | + | |
| 155 | +def _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 | + | |
| 166 | +class 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 | + | |
| 237 | +class 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 | + | |
| 328 | +class 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 | + | |
| 388 | +class 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 | + | |
| 571 | +class 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 | + | |
| 646 | +if __name__ == '__main__': | |
| 647 | + unittest.main() |