| 1 | #!/usr/bin/env python3 |
| 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. |
| 7 | |
| 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. |
| 10 | """ |
| 11 | import functools |
| 12 | import http.client |
| 13 | import http.server |
| 14 | import ipaddress |
| 15 | import re |
| 16 | import socket |
| 17 | import socketserver |
| 18 | import ssl |
| 19 | import sys |
| 20 | import threading |
| 21 | import time |
| 22 | import urllib.parse |
| 23 | import urllib.request |
| 24 | import zlib |
| 25 | from collections import namedtuple |
| 26 | from http import HTTPStatus |
| 27 | from pathlib import Path |
| 28 | |
| 29 | import os |
| 30 | |
| 31 | ROOT = os.environ.get('ELFFUSSCODE_ROOT') or str(Path(__file__).resolve().parent.parent / 'web') |
| 32 | MAX_PROXY_BYTES = 2_000_000 |
| 33 | # En desarrollo, /v1 (modelo) se reenvía a producción; en producción lo |
| 34 | # resuelve nginx directamente contra llama-server, no este forward. |
| 35 | LM_UPSTREAM = os.environ.get('ELFFUSS_LM') or 'https://elffuss.com' |
| 36 | |
| 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 | |
| 531 | class Handler(http.server.SimpleHTTPRequestHandler): |
| 532 | def __init__(self, *args, **kwargs): |
| 533 | super().__init__(*args, directory=ROOT, **kwargs) |
| 534 | |
| 535 | def end_headers(self): |
| 536 | self.send_header('Cache-Control', 'no-store') |
| 537 | super().end_headers() |
| 538 | |
| 539 | def do_GET(self): |
| 540 | if self.path.startswith('/proxy?'): |
| 541 | return self.proxy() |
| 542 | if self.path.startswith('/v1/'): |
| 543 | return self.forward_lm() |
| 544 | super().do_GET() |
| 545 | |
| 546 | def do_POST(self): |
| 547 | if self.path.startswith('/v1/'): |
| 548 | return self.forward_lm() |
| 549 | self.send_error(404) |
| 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 | |
| 564 | def forward_lm(self): |
| 565 | """Reenvía /v1/* (API del modelo) al servidor de producción, con streaming.""" |
| 566 | length = int(self.headers.get('Content-Length') or 0) |
| 567 | body = self.rfile.read(length) if length else None |
| 568 | req = urllib.request.Request( |
| 569 | LM_UPSTREAM + self.path, data=body, method=self.command, |
| 570 | headers={'Content-Type': self.headers.get('Content-Type', 'application/json')}) |
| 571 | try: |
| 572 | with urllib.request.urlopen(req, timeout=300) as r: |
| 573 | self.send_response(r.status) |
| 574 | self.send_header('Content-Type', r.headers.get('Content-Type', 'application/json')) |
| 575 | self.end_headers() |
| 576 | while True: |
| 577 | chunk = r.read(1024) |
| 578 | if not chunk: |
| 579 | break |
| 580 | self.wfile.write(chunk) |
| 581 | self.wfile.flush() |
| 582 | except Exception as e: # noqa: BLE001 |
| 583 | self.send_error(502, f'lm: {e}') |
| 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 | |
| 625 | def proxy(self): |
| 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)) |
| 659 | |
| 660 | def log_message(self, fmt, *args): |
| 661 | sys.stderr.write('· %s\n' % (fmt % args)) |
| 662 | |
| 663 | |
| 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') |
| 670 | socketserver.ThreadingTCPServer.allow_reuse_address = True |
| 671 | with socketserver.ThreadingTCPServer((bind, port), Handler) as httpd: |
| 672 | print(f'✳ Elffuss Code · http://localhost:{port}') |
| 673 | httpd.serve_forever() |
| 674 | |
| 675 | |
| 676 | if __name__ == '__main__': |
| 677 | main() |