| 1 | #!/usr/bin/env python3 |
| 2 | """Servidor de desarrollo de Elffuss: sirve web/, hace de proxy en /proxy?url=… |
| 3 | y recoge /proxy/report. |
| 4 | |
| 5 | En producción este mismo fichero es el backend del servicio elffuss-proxy, |
| 6 | detrás de nginx, que solo le pasa /proxy y /proxy/report. Se instala con |
| 7 | deploy.sh en ~/elffuss-proxy/ (ver server/install-proxy.sh), no en ~/elffuss/. |
| 8 | |
| 9 | /proxy es un relé GET ABIERTO hacia la web pública (http y https, puertos 80 |
| 10 | y 443): no autentica a nadie. Ver el bloque de /proxy más abajo. |
| 11 | |
| 12 | Uso: python3 server/serve.py [puerto] (por defecto 8642) |
| 13 | Escucha solo en 127.0.0.1; ELFFUSS_BIND=0.0.0.0 lo abre a la red. |
| 14 | """ |
| 15 | import functools |
| 16 | import http.client |
| 17 | import http.server |
| 18 | import ipaddress |
| 19 | import json |
| 20 | import re |
| 21 | import socket |
| 22 | import socketserver |
| 23 | import ssl |
| 24 | import sys |
| 25 | import threading |
| 26 | import time |
| 27 | import urllib.parse |
| 28 | import urllib.request |
| 29 | import zlib |
| 30 | from collections import namedtuple |
| 31 | from http import HTTPStatus |
| 32 | from pathlib import Path |
| 33 | |
| 34 | import os |
| 35 | |
| 36 | ROOT = os.environ.get('ELFFUSS_ROOT') or str(Path(__file__).resolve().parent.parent / 'web') |
| 37 | MAX_PROXY_BYTES = 2_000_000 |
| 38 | # En desarrollo, /v1 (modelo) se reenvía a producción; en producción lo |
| 39 | # resuelve nginx directamente contra llama-server, no este forward. |
| 40 | LM_UPSTREAM = os.environ.get('ELFFUSS_LM') or 'https://elffuss.com' |
| 41 | |
| 42 | # /proxy/report — buzón de errores/feedback (opt-in, ver web/js/telemetry.js). |
| 43 | # Nunca lleva código del proyecto del usuario, solo el mensaje técnico y |
| 44 | # metadatos (app, versión, user-agent) — se anexa tal cual a un .jsonl para |
| 45 | # revisarlo a mano, sin base de datos ni dependencias. |
| 46 | REPORTS_PATH = os.environ.get('ELFFUSS_REPORTS') or str(Path.home() / 'elffuss' / 'reports.jsonl') |
| 47 | MAX_REPORT_BYTES = 20_000 |
| 48 | REPORT_RATE = {} # ip -> [timestamps] — límite simple sin dependencias |
| 49 | RATE_WINDOW_S, RATE_MAX = 60, 20 |
| 50 | |
| 51 | |
| 52 | # ---------------------------------------------------------------- /proxy?url=… |
| 53 | # El agente lee por aquí las webs que no mandan CORS. La petición la hace EL |
| 54 | # SERVIDOR, así que sin cerrojos esto es un SSRF de manual: cualquiera podría |
| 55 | # pedirle 127.0.0.1:<otro servicio de la máquina> o la metadata de la nube |
| 56 | # (169.254.169.254). Reglas: |
| 57 | # · solo http/https a los puertos 80 y 443, sin usuario:contraseña en la url; |
| 58 | # · el nombre se resuelve UNA vez, se rechaza si CUALQUIERA de sus direcciones |
| 59 | # no es pública, y se conecta a ESA dirección (Host y SNI siguen siendo el |
| 60 | # nombre): un DNS que cambie de respuesta entre la comprobación y la |
| 61 | # conexión (DNS rebinding) no cuela nada; |
| 62 | # · IPv4 solo en forma canónica a.b.c.d: 2130706433, 0x7f.1 o 0177.0.0.1 son |
| 63 | # 127.0.0.1 para el resolver, y se rechazan antes de llegar a él; |
| 64 | # · las redirecciones se siguen a mano y cada salto se valida igual; |
| 65 | # · no viaja ninguna cabecera del cliente (ni cookies ni Authorization) y el |
| 66 | # User-Agent es fijo; |
| 67 | # · las direcciones de ESTA máquina tampoco: pedir su IP pública (o un nombre |
| 68 | # que resuelva a ella, como cualquier otro vhost alojado aquí) vuelve a |
| 69 | # entrar por el nginx de aquí mismo con origen la propia máquina, y /proxy |
| 70 | # se podría llamar a sí mismo en bucle; |
| 71 | # · tope de bytes con aviso (X-Proxy-Truncated: 1, nunca un 200 mudo), plazo |
| 72 | # total, y límites por IP, global y de peticiones simultáneas. |
| 73 | # |
| 74 | # QUÉ NO ES: control de acceso. /proxy es un relé GET ABIERTO a la web pública, |
| 75 | # y no puede ser otra cosa: la app corre entera en el navegador y sin cuentas, |
| 76 | # así que cualquier secreto o cabecera que la página mandase la mandaría igual |
| 77 | # un script (está en el JS que se sirve a todo el mundo). _proxy_caller_ok solo |
| 78 | # impide que OTRA web use el navegador del usuario contra este origen; curl, o |
| 79 | # cualquier cliente que no sea un navegador, pasa. Lo que acota el relé son las |
| 80 | # reglas de destino y los topes: el global existe porque el límite por IP se |
| 81 | # salta repartiendo las peticiones entre muchas IP. |
| 82 | # El mismo código vive en server/serve.py de elffuss-code: cambiar los dos. |
| 83 | PROXY_USER_AGENT = 'Mozilla/5.0 (Elffuss)' |
| 84 | PROXY_PORTS = (80, 443) |
| 85 | PROXY_MAX_URL = 4096 |
| 86 | PROXY_MAX_REDIRECTS = 5 |
| 87 | PROXY_MAX_ADDRS = 8 # direcciones a las que se intenta conectar, como mucho, por salto |
| 88 | PROXY_CONNECT_TIMEOUT_S = 8 |
| 89 | PROXY_READ_TIMEOUT_S = 15 |
| 90 | PROXY_TOTAL_TIMEOUT_S = 30 # el proxy_read_timeout de nginx tiene que quedar por encima |
| 91 | PROXY_RATE_WINDOW_S, PROXY_RATE_MAX = 60, 30 |
| 92 | # Entre TODOS los clientes, por ventana. Holgado para el uso de la app (una |
| 93 | # búsqueda son dos peticiones), y lo que acota el relé ante una red de bots. |
| 94 | PROXY_GLOBAL_MAX = int(os.environ.get('ELFFUSS_PROXY_GLOBAL_MAX') or 300) |
| 95 | PROXY_SLOTS = threading.BoundedSemaphore(8) |
| 96 | PROXY_SELF_REFRESH_S = 300 # cada cuánto se vuelven a enumerar las direcciones propias |
| 97 | |
| 98 | # Además de lo no público y de las direcciones propias que se ven desde aquí, lo |
| 99 | # que se liste en ELFFUSS_PROXY_DENY (CIDR separados por comas): por ejemplo la |
| 100 | # IP pública de la máquina cuando está detrás de NAT y no aparece en ninguna |
| 101 | # interfaz, que es el único caso que la enumeración no ve. |
| 102 | PROXY_DENY = tuple(ipaddress.ip_network(n.strip(), strict=False) |
| 103 | for n in (os.environ.get('ELFFUSS_PROXY_DENY') or '').split(',') if n.strip()) |
| 104 | |
| 105 | _V4_BLOCKED = tuple(ipaddress.ip_network(n) for n in ( |
| 106 | '0.0.0.0/8', # «esta red»: 0.0.0.0 acaba en localhost en Linux |
| 107 | '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', # privadas |
| 108 | '100.64.0.0/10', # CGNAT, con la metadata de algunas nubes (100.100.100.200) |
| 109 | '127.0.0.0/8', # loopback |
| 110 | '169.254.0.0/16', # enlace local, con la metadata de la nube (169.254.169.254) |
| 111 | '192.0.0.0/24', '192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', # IETF y documentación |
| 112 | '192.88.99.0/24', # relé 6to4 |
| 113 | '198.18.0.0/15', # bancos de pruebas |
| 114 | '224.0.0.0/4', # multicast (Python lo da por «global») |
| 115 | '240.0.0.0/4', # reservada, con 255.255.255.255 |
| 116 | )) |
| 117 | # Fuera de 2000::/3 queda todo lo que no es unicast global: ::, ::1, las |
| 118 | # IPv4-mapeadas (::ffff:a.b.c.d) y compatibles (::a.b.c.d), NAT64 (64:ff9b::), |
| 119 | # ULA (fc00::/7), enlace local (fe80::/10) y multicast (ff00::/8). |
| 120 | _V6_UNICAST = ipaddress.ip_network('2000::/3') |
| 121 | _V6_BLOCKED = tuple(ipaddress.ip_network(n) for n in ( |
| 122 | '2001::/23', # asignaciones del IETF, con Teredo (2001::/32) |
| 123 | '2001:db8::/32', # documentación |
| 124 | '2002::/16', # 6to4: lleva una IPv4 dentro |
| 125 | '3fff::/20', # documentación (RFC 9637) |
| 126 | )) |
| 127 | # Nombres que nunca son internet, se resuelvan a lo que se resuelvan. |
| 128 | _RESERVED_NAMES = ('localhost', 'local', 'internal', 'localdomain', 'home.arpa', |
| 129 | 'invalid', 'test', 'example', 'onion', 'alt') |
| 130 | |
| 131 | _CTRL_RE = re.compile(r'[\x00-\x1f\x7f]') |
| 132 | _NETLOC_RE = re.compile(r'(\[[^\[\]]*\]|[^\[\]:]*)(?::([0-9]*))?') |
| 133 | _LABEL_RE = re.compile(r'[a-z0-9_-]{1,63}') |
| 134 | _NUMERIC_LABEL_RE = re.compile(r'0x[0-9a-f]*|[0-9]+') |
| 135 | _OCTET_RE = re.compile(r'0|[1-9][0-9]{0,2}') |
| 136 | _CONTENT_TYPE_RE = re.compile(r'[\x21-\x7e][\x20-\x7e]{0,199}') |
| 137 | _REDIRECTS = (301, 302, 303, 307, 308) |
| 138 | _UPSTREAM_HEADERS = { # lo ÚNICO que se manda al destino, además de Host |
| 139 | 'User-Agent': PROXY_USER_AGENT, |
| 140 | 'Accept-Encoding': 'identity', |
| 141 | 'Connection': 'close', |
| 142 | } |
| 143 | _AI_FLAGS = getattr(socket, 'AI_ADDRCONFIG', 0) |
| 144 | |
| 145 | Target = namedtuple('Target', 'scheme host port path url addrs') |
| 146 | ProxyResult = namedtuple('ProxyResult', 'status upstream_status content_type body truncated') |
| 147 | |
| 148 | |
| 149 | class ProxyRefused(Exception): |
| 150 | """Respuesta de error del proxy: estado HTTP, código corto para la cabecera |
| 151 | X-Proxy-Error y un motivo legible. Nunca lleva la dirección resuelta.""" |
| 152 | |
| 153 | def __init__(self, status, code, detail): |
| 154 | super().__init__(detail) |
| 155 | self.status, self.code, self.detail = status, code, detail |
| 156 | |
| 157 | |
| 158 | def _parse_ip(text): |
| 159 | try: |
| 160 | return ipaddress.ip_address(str(text).split('%', 1)[0]) |
| 161 | except ValueError: |
| 162 | return None |
| 163 | |
| 164 | |
| 165 | def _in_block_lists(ip): |
| 166 | """Las listas de arriba, solas: no dependen de la versión de Python.""" |
| 167 | if ip.version == 6: |
| 168 | return ip not in _V6_UNICAST or any(ip in n for n in _V6_BLOCKED) |
| 169 | return any(ip in n for n in _V4_BLOCKED) |
| 170 | |
| 171 | |
| 172 | def _routable(ip): |
| 173 | """¿Es una dirección de internet? Las listas propias, y además las banderas |
| 174 | de ipaddress, que cambian de una versión de Python a otra (para ellas |
| 175 | 224.0.0.1 es «global»).""" |
| 176 | if _in_block_lists(ip): |
| 177 | return False |
| 178 | return not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast |
| 179 | or ip.is_reserved or ip.is_unspecified or not ip.is_global) |
| 180 | |
| 181 | |
| 182 | def _ip_is_public(ip): |
| 183 | """¿Se puede conectar a esta dirección? De internet, fuera de |
| 184 | ELFFUSS_PROXY_DENY y que no sea de esta misma máquina.""" |
| 185 | return (_routable(ip) and not any(ip in n for n in PROXY_DENY) |
| 186 | and ip not in _self_addresses()) |
| 187 | |
| 188 | |
| 189 | # ------------------------------------------------- las direcciones de esta máquina |
| 190 | _PROC_FIB_TRIE = '/proc/net/fib_trie' # Linux: cada IPv4 local, «/32 host LOCAL» |
| 191 | _PROC_IF_INET6 = '/proc/net/if_inet6' # Linux: cada IPv6 de cada interfaz |
| 192 | |
| 193 | |
| 194 | def _local_v4_from_fib_trie(text): |
| 195 | """Las IPv4 locales de /proc/net/fib_trie: cada hoja «|-- a.b.c.d» que |
| 196 | lleva debajo una línea «/32 host LOCAL».""" |
| 197 | found, leaf = set(), None |
| 198 | for line in text.splitlines(): |
| 199 | line = line.strip() |
| 200 | if line.startswith('|-- '): |
| 201 | leaf = line[4:].strip() |
| 202 | elif leaf and line.startswith('/32 host LOCAL'): |
| 203 | found.add(leaf) |
| 204 | return found |
| 205 | |
| 206 | |
| 207 | def _local_v6_from_if_inet6(text): |
| 208 | """Las IPv6 de /proc/net/if_inet6: la primera columna, 32 cifras hex.""" |
| 209 | found = set() |
| 210 | for line in text.splitlines(): |
| 211 | cols = line.split() |
| 212 | if cols and len(cols[0]) == 32: |
| 213 | try: |
| 214 | found.add(str(ipaddress.IPv6Address(int(cols[0], 16)))) |
| 215 | except ValueError: |
| 216 | pass |
| 217 | return found |
| 218 | |
| 219 | |
| 220 | def _egress_addresses(): |
| 221 | """La dirección con la que la máquina sale a internet, por familia: un |
| 222 | connect() UDP elige ruta y origen sin mandar ningún paquete. Es lo único |
| 223 | que hay donde no existe /proc (fuera de Linux).""" |
| 224 | found = set() |
| 225 | for family, probe in ((socket.AF_INET, ('192.0.2.1', 9)), (socket.AF_INET6, ('2001:db8::1', 9, 0, 0))): |
| 226 | try: |
| 227 | with socket.socket(family, socket.SOCK_DGRAM) as s: |
| 228 | s.connect(probe) |
| 229 | found.add(s.getsockname()[0]) |
| 230 | except OSError: |
| 231 | pass |
| 232 | return found |
| 233 | |
| 234 | |
| 235 | def _own_addresses(): |
| 236 | """Las direcciones de internet de esta máquina: las de sus interfaces y la |
| 237 | de salida. Las privadas y de loopback ya se rechazan por sí solas.""" |
| 238 | found = set() |
| 239 | for path, parse in ((_PROC_FIB_TRIE, _local_v4_from_fib_trie), (_PROC_IF_INET6, _local_v6_from_if_inet6)): |
| 240 | try: |
| 241 | with open(path, encoding='ascii', errors='replace') as f: |
| 242 | found |= parse(f.read()) |
| 243 | except OSError: |
| 244 | pass |
| 245 | found |= _egress_addresses() |
| 246 | ips = (_parse_ip(a) for a in found) |
| 247 | return frozenset(ip for ip in ips if ip is not None and _routable(ip)) |
| 248 | |
| 249 | |
| 250 | _self_lock = threading.Lock() |
| 251 | _self_cache = {'at': None, 'addrs': frozenset()} |
| 252 | |
| 253 | |
| 254 | def _self_addresses(): |
| 255 | """_own_addresses(), vuelta a enumerar como mucho cada PROXY_SELF_REFRESH_S |
| 256 | (una IP que se añade con la máquina en marcha también cuenta).""" |
| 257 | with _self_lock: |
| 258 | now = time.monotonic() |
| 259 | if _self_cache['at'] is None or now - _self_cache['at'] >= PROXY_SELF_REFRESH_S: |
| 260 | _self_cache['addrs'] = _own_addresses() |
| 261 | _self_cache['at'] = now |
| 262 | return _self_cache['addrs'] |
| 263 | |
| 264 | |
| 265 | def _is_loopback(text): |
| 266 | ip = _parse_ip(text) |
| 267 | if ip is not None and ip.version == 6 and ip.ipv4_mapped is not None: |
| 268 | ip = ip.ipv4_mapped |
| 269 | return ip is not None and ip.is_loopback |
| 270 | |
| 271 | |
| 272 | def _rate_key(ip_text): |
| 273 | """Clave del límite por IP: una IPv6 cuenta por su /64, que es lo que |
| 274 | tiene cualquier cliente para él solo.""" |
| 275 | ip = _parse_ip(ip_text) |
| 276 | if ip is None: |
| 277 | return str(ip_text)[:64] |
| 278 | if ip.version == 6: |
| 279 | if ip.ipv4_mapped is not None: |
| 280 | return str(ip.ipv4_mapped) |
| 281 | return str(ipaddress.IPv6Network((int(ip) >> 64 << 64, 64))) |
| 282 | return str(ip) |
| 283 | |
| 284 | |
| 285 | def _parse_host(raw): |
| 286 | """→ (ip, host): ip si el host es una dirección literal (y host su forma |
| 287 | canónica); si es un nombre, (None, nombre en ASCII y minúsculas).""" |
| 288 | if raw.startswith('['): |
| 289 | inner = raw[1:-1] |
| 290 | if '%' in inner: # zona (fe80::1%eth0): solo existe en enlace local |
| 291 | raise ProxyRefused(403, 'forbidden-destination', 'destino no permitido (dirección de enlace local)') |
| 292 | try: |
| 293 | ip = ipaddress.IPv6Address(inner) |
| 294 | except ValueError: |
| 295 | raise ProxyRefused(400, 'bad-host', 'dirección IPv6 mal formada') from None |
| 296 | return ip, str(ip) |
| 297 | host = raw[:-1] if raw.endswith('.') else raw |
| 298 | try: |
| 299 | host = host.encode('idna').decode('ascii').lower() |
| 300 | except UnicodeError: |
| 301 | raise ProxyRefused(400, 'bad-host', 'nombre de host no válido') from None |
| 302 | labels = host.split('.') |
| 303 | if not all(_LABEL_RE.fullmatch(label) for label in labels): |
| 304 | raise ProxyRefused(400, 'bad-host', 'nombre de host no válido') |
| 305 | # Si la última etiqueta es un número, el resolver lo toma por una IPv4 |
| 306 | # (inet_aton acepta decimal, octal, hex y formas cortas): solo se admite |
| 307 | # la forma a.b.c.d, en decimal y sin ceros a la izquierda. |
| 308 | if _NUMERIC_LABEL_RE.fullmatch(labels[-1]): |
| 309 | if len(labels) != 4 or not all(_OCTET_RE.fullmatch(x) and int(x) <= 255 for x in labels): |
| 310 | raise ProxyRefused(400, 'odd-ip', 'las IPv4 van en forma a.b.c.d, en decimal') |
| 311 | return ipaddress.IPv4Address(host), host |
| 312 | if len(labels) < 2 or any(host == s or host.endswith('.' + s) for s in _RESERVED_NAMES): |
| 313 | raise ProxyRefused(403, 'forbidden-destination', 'destino no permitido (nombre local o reservado)') |
| 314 | return None, host |
| 315 | |
| 316 | |
| 317 | def _getaddrinfo(*args): # los tests sustituyen esto: es el único punto de DNS |
| 318 | return socket.getaddrinfo(*args) |
| 319 | |
| 320 | |
| 321 | def _resolve(host, port): |
| 322 | """Resuelve UNA vez. Si alguna dirección no es pública se rechaza todo: |
| 323 | elegir la buena dejaría a un DNS hostil decidir a cuál se conecta.""" |
| 324 | try: |
| 325 | infos = _getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP, _AI_FLAGS) |
| 326 | except (OSError, UnicodeError): |
| 327 | raise ProxyRefused(502, 'dns', 'no se pudo resolver el host') from None |
| 328 | addrs = [] |
| 329 | for family, _type, _proto, _canon, sockaddr in infos: |
| 330 | ip = _parse_ip(sockaddr[0]) if family in (socket.AF_INET, socket.AF_INET6) else None |
| 331 | if ip is None or not _ip_is_public(ip): |
| 332 | raise ProxyRefused(403, 'forbidden-destination', |
| 333 | 'destino no permitido (el nombre resuelve a una dirección no pública o de esta máquina)') |
| 334 | if (family, sockaddr) not in addrs: |
| 335 | addrs.append((family, sockaddr)) |
| 336 | if not addrs: |
| 337 | raise ProxyRefused(502, 'dns', 'el host no tiene direcciones') |
| 338 | return addrs |
| 339 | |
| 340 | |
| 341 | def _check_url(url): |
| 342 | """Valida una url y la resuelve: → Target con las direcciones ya |
| 343 | comprobadas, que son las únicas a las que se conectará.""" |
| 344 | if not url: |
| 345 | raise ProxyRefused(400, 'bad-url', 'falta el parámetro url') |
| 346 | if len(url) > PROXY_MAX_URL or _CTRL_RE.search(url): |
| 347 | raise ProxyRefused(400, 'bad-url', 'url demasiado larga o con caracteres de control') |
| 348 | try: |
| 349 | parts = urllib.parse.urlsplit(url.strip()) |
| 350 | except ValueError: |
| 351 | raise ProxyRefused(400, 'bad-url', 'url mal formada') from None |
| 352 | scheme = parts.scheme.lower() |
| 353 | if scheme not in ('http', 'https'): |
| 354 | raise ProxyRefused(400, 'bad-scheme', 'solo http:// y https://') |
| 355 | if '@' in parts.netloc: |
| 356 | raise ProxyRefused(400, 'userinfo', 'la url no puede llevar usuario ni contraseña') |
| 357 | m = _NETLOC_RE.fullmatch(parts.netloc) |
| 358 | if not m or not m.group(1): |
| 359 | raise ProxyRefused(400, 'bad-host', 'url sin host válido') |
| 360 | default_port = 443 if scheme == 'https' else 80 |
| 361 | port = int(m.group(2)) if m.group(2) else default_port |
| 362 | if port not in PROXY_PORTS: |
| 363 | raise ProxyRefused(403, 'forbidden-port', 'solo se permiten los puertos 80 y 443') |
| 364 | ip, host = _parse_host(m.group(1)) |
| 365 | if ip is None: |
| 366 | addrs = _resolve(host, port) |
| 367 | elif not _ip_is_public(ip): |
| 368 | raise ProxyRefused(403, 'forbidden-destination', 'destino no permitido (dirección no pública o de esta máquina)') |
| 369 | elif ip.version == 6: |
| 370 | addrs = [(socket.AF_INET6, (host, port, 0, 0))] |
| 371 | else: |
| 372 | addrs = [(socket.AF_INET, (host, port))] |
| 373 | try: |
| 374 | path = urllib.parse.quote(parts.path or '/', safe="/%:@!$&'()*+,;=~") |
| 375 | if parts.query: |
| 376 | path += '?' + urllib.parse.quote(parts.query, safe="/?%:@!$&'()*+,;=~") |
| 377 | except UnicodeError: |
| 378 | raise ProxyRefused(400, 'bad-url', 'url mal formada') from None |
| 379 | netloc = ('[%s]' % host if ':' in host else host) + ('' if port == default_port else ':%d' % port) |
| 380 | return Target(scheme, host, port, path, '%s://%s%s' % (scheme, netloc, path), tuple(addrs)) |
| 381 | |
| 382 | |
| 383 | def _shutdown(sock): |
| 384 | try: # socket.socket.shutdown también sobre un SSLSocket: corta el fd sin tocar el estado TLS |
| 385 | socket.socket.shutdown(sock, socket.SHUT_RDWR) |
| 386 | except (OSError, TypeError, ValueError): |
| 387 | pass |
| 388 | |
| 389 | |
| 390 | class _Deadline: |
| 391 | """Plazo TOTAL de una petición al proxy, redirecciones incluidas. Los |
| 392 | timeouts de socket cuentan por operación, y un servidor que gotea un byte |
| 393 | cada pocos segundos los esquiva todos: al vencer el plazo se corta el |
| 394 | socket en uso y la lectura bloqueada falla.""" |
| 395 | |
| 396 | def __init__(self, seconds): |
| 397 | self._end = time.monotonic() + seconds |
| 398 | self._lock = threading.Lock() |
| 399 | self._sock = None |
| 400 | self._fired = False |
| 401 | self._timer = threading.Timer(seconds, self._fire) |
| 402 | self._timer.daemon = True |
| 403 | self._timer.start() |
| 404 | |
| 405 | def remaining(self): |
| 406 | return self._end - time.monotonic() |
| 407 | |
| 408 | def expired(self): |
| 409 | return self._fired or self.remaining() <= 0 |
| 410 | |
| 411 | def watch(self, sock): |
| 412 | with self._lock: |
| 413 | self._sock = sock |
| 414 | fired = self._fired |
| 415 | if fired: |
| 416 | _shutdown(sock) |
| 417 | |
| 418 | def _fire(self): |
| 419 | with self._lock: |
| 420 | self._fired = True |
| 421 | sock = self._sock |
| 422 | if sock is not None: |
| 423 | _shutdown(sock) |
| 424 | |
| 425 | def cancel(self): |
| 426 | self._timer.cancel() |
| 427 | with self._lock: |
| 428 | self._sock = None |
| 429 | |
| 430 | |
| 431 | def _dial(family, sockaddr, timeout): |
| 432 | """Conexión TCP a una dirección YA validada (los tests sustituyen esto).""" |
| 433 | sock = socket.socket(family, socket.SOCK_STREAM) |
| 434 | try: |
| 435 | sock.settimeout(timeout) |
| 436 | sock.connect(sockaddr) |
| 437 | except BaseException: |
| 438 | sock.close() |
| 439 | raise |
| 440 | return sock |
| 441 | |
| 442 | |
| 443 | def _dial_order(addrs): |
| 444 | """Orden de intento: alternando familias, empezando por la que dio primero |
| 445 | el resolver (RFC 8305 §4). Con IPv6 configurada pero sin ruta, y una |
| 446 | respuesta que trae primero cuatro AAAA, la primera IPv4 es el segundo |
| 447 | intento y no queda fuera. Como mucho PROXY_MAX_ADDRS: quien controla el DNS |
| 448 | de un nombre no convierte una petición en cien conexiones.""" |
| 449 | if not addrs: |
| 450 | return [] |
| 451 | first = [a for a in addrs if a[0] == addrs[0][0]] |
| 452 | other = [a for a in addrs if a[0] != addrs[0][0]] |
| 453 | order = [] |
| 454 | for i in range(max(len(first), len(other))): |
| 455 | order.extend(group[i] for group in (first, other) if i < len(group)) |
| 456 | return order[:PROXY_MAX_ADDRS] |
| 457 | |
| 458 | |
| 459 | def _connect(target, deadline): |
| 460 | last = None |
| 461 | for family, sockaddr in _dial_order(target.addrs): |
| 462 | remaining = deadline.remaining() |
| 463 | if remaining <= 0: |
| 464 | break |
| 465 | try: |
| 466 | sock = _dial(family, sockaddr, min(PROXY_CONNECT_TIMEOUT_S, remaining)) |
| 467 | except OSError as e: |
| 468 | last = e |
| 469 | continue |
| 470 | sock.settimeout(PROXY_READ_TIMEOUT_S) |
| 471 | deadline.watch(sock) |
| 472 | return sock |
| 473 | if deadline.expired(): |
| 474 | raise socket.timeout('plazo agotado') |
| 475 | raise last or OSError('sin conexión') |
| 476 | |
| 477 | |
| 478 | @functools.lru_cache(maxsize=None) |
| 479 | def _tls_context(): |
| 480 | ctx = ssl.create_default_context() # verifica certificado y nombre |
| 481 | ctx.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 482 | return ctx |
| 483 | |
| 484 | |
| 485 | class _PinnedHTTPConnection(http.client.HTTPConnection): |
| 486 | """HTTP contra la dirección ya validada; Host sigue siendo el nombre.""" |
| 487 | |
| 488 | def __init__(self, target, deadline): |
| 489 | super().__init__(target.host, target.port, timeout=PROXY_READ_TIMEOUT_S) |
| 490 | self._target, self._deadline = target, deadline |
| 491 | |
| 492 | def connect(self): |
| 493 | self.sock = _connect(self._target, self._deadline) |
| 494 | |
| 495 | |
| 496 | class _PinnedHTTPSConnection(http.client.HTTPSConnection): |
| 497 | """HTTPS contra la dirección ya validada; el SNI y la verificación del |
| 498 | certificado van contra el nombre, no contra la IP.""" |
| 499 | |
| 500 | def __init__(self, target, deadline): |
| 501 | self._tls = _tls_context() |
| 502 | super().__init__(target.host, target.port, timeout=PROXY_READ_TIMEOUT_S, context=self._tls) |
| 503 | self._target, self._deadline = target, deadline |
| 504 | |
| 505 | def connect(self): |
| 506 | raw = _connect(self._target, self._deadline) |
| 507 | try: |
| 508 | tls = self._tls.wrap_socket(raw, server_hostname=self._target.host, |
| 509 | do_handshake_on_connect=False) |
| 510 | except BaseException: |
| 511 | raw.close() |
| 512 | raise |
| 513 | try: |
| 514 | tls.settimeout(PROXY_READ_TIMEOUT_S) |
| 515 | self._deadline.watch(tls) # el socket de antes ya no es dueño del fd |
| 516 | tls.do_handshake() |
| 517 | except BaseException: |
| 518 | tls.close() |
| 519 | raise |
| 520 | self.sock = tls |
| 521 | |
| 522 | |
| 523 | def _header_text(value): |
| 524 | """http.client entrega las cabeceras como latin-1; una Location con UTF-8 |
| 525 | crudo se recupera aquí antes de volver a codificarla.""" |
| 526 | try: |
| 527 | return value.encode('latin-1').decode('utf-8') |
| 528 | except UnicodeError: |
| 529 | return value |
| 530 | |
| 531 | |
| 532 | def _inflate(data, encoding, limit): |
| 533 | for wbits in ((16 + zlib.MAX_WBITS,) if encoding != 'deflate' else (zlib.MAX_WBITS, -zlib.MAX_WBITS)): |
| 534 | try: |
| 535 | out = zlib.decompressobj(wbits).decompress(data, limit + 1) # nunca más de limit+1 |
| 536 | except zlib.error: |
| 537 | continue |
| 538 | return out[:limit], len(out) > limit |
| 539 | raise ProxyRefused(502, 'encoding', 'la web mandó un cuerpo comprimido corrupto') |
| 540 | |
| 541 | |
| 542 | def _read_body(resp): |
| 543 | limit = MAX_PROXY_BYTES |
| 544 | chunks, total = [], 0 |
| 545 | while total <= limit: |
| 546 | chunk = resp.read(min(1 << 16, limit + 1 - total)) |
| 547 | if not chunk: |
| 548 | break |
| 549 | chunks.append(chunk) |
| 550 | total += len(chunk) |
| 551 | raw, truncated = b''.join(chunks), total > limit |
| 552 | # Se pide identity; si aun así llega comprimido, se descomprime con tope |
| 553 | # (una bomba gzip no pasa de limit+1 bytes) y el cliente lo recibe plano. |
| 554 | encoding = (resp.getheader('Content-Encoding') or '').strip().lower() |
| 555 | if encoding in ('', 'identity'): |
| 556 | return raw[:limit], truncated |
| 557 | if encoding not in ('gzip', 'x-gzip', 'deflate'): |
| 558 | raise ProxyRefused(502, 'encoding', 'la web respondió comprimida en un formato no soportado') |
| 559 | body, more = _inflate(raw, encoding, limit) |
| 560 | return body, truncated or more |
| 561 | |
| 562 | |
| 563 | def _fetch(url, deadline): |
| 564 | for hop in range(PROXY_MAX_REDIRECTS + 1): |
| 565 | try: |
| 566 | target = _check_url(url) |
| 567 | except ProxyRefused as e: |
| 568 | if hop == 0 or e.code == 'dns': |
| 569 | raise |
| 570 | if e.status == 403: |
| 571 | raise ProxyRefused(403, 'forbidden-redirect', 'la web redirige a un destino no permitido') from None |
| 572 | raise ProxyRefused(502, 'bad-redirect', 'la web redirige a una url no válida') from None |
| 573 | conn_class = _PinnedHTTPSConnection if target.scheme == 'https' else _PinnedHTTPConnection |
| 574 | conn = conn_class(target, deadline) |
| 575 | try: |
| 576 | conn.request('GET', target.path, headers=_UPSTREAM_HEADERS) |
| 577 | resp = conn.getresponse() |
| 578 | if resp.status in _REDIRECTS: |
| 579 | location = resp.getheader('Location') |
| 580 | if not location or not location.strip(): |
| 581 | raise ProxyRefused(502, 'bad-redirect', 'redirección sin destino') |
| 582 | url = urllib.parse.urljoin(target.url, _header_text(location).strip()) |
| 583 | continue |
| 584 | content_type = (resp.getheader('Content-Type') or '').strip() |
| 585 | if not _CONTENT_TYPE_RE.fullmatch(content_type): |
| 586 | content_type = 'application/octet-stream' |
| 587 | body, truncated = _read_body(resp) |
| 588 | # Cortar el socket al vencer el plazo se lee como un fin de |
| 589 | # fichero, y para http.client eso puede ser un final normal (unas |
| 590 | # cabeceras a medias, un cuerpo sin longitud): lo leído después |
| 591 | # del corte no es la respuesta, es un 504. |
| 592 | if deadline.expired(): |
| 593 | raise socket.timeout('plazo agotado') |
| 594 | # El estado real del destino (un 404 es un 404, no un 200 ni un |
| 595 | # 502); lo que no es un final normal (1xx, 3xx sueltos) es un 502. |
| 596 | status = resp.status if 200 <= resp.status < 300 or 400 <= resp.status < 600 else 502 |
| 597 | return ProxyResult(status, resp.status, content_type, body, truncated) |
| 598 | finally: |
| 599 | conn.close() |
| 600 | raise ProxyRefused(502, 'too-many-redirects', 'demasiadas redirecciones') |
| 601 | |
| 602 | |
| 603 | def proxy_fetch(url): |
| 604 | """GET a una url pública con todas las reglas de arriba → ProxyResult, o |
| 605 | ProxyRefused con el estado y el motivo.""" |
| 606 | deadline = _Deadline(PROXY_TOTAL_TIMEOUT_S) |
| 607 | try: |
| 608 | return _fetch(url, deadline) |
| 609 | except ProxyRefused: |
| 610 | raise |
| 611 | except Exception as e: # noqa: BLE001 — cualquier fallo del destino es un 502/504 con motivo |
| 612 | if deadline.expired() or isinstance(e, socket.timeout): |
| 613 | raise ProxyRefused(504, 'timeout', 'la web no respondió a tiempo') from None |
| 614 | if isinstance(e, ssl.SSLError): |
| 615 | raise ProxyRefused(502, 'tls', 'fallo TLS con la web (%s)' % type(e).__name__) from None |
| 616 | raise ProxyRefused(502, 'upstream', 'no se pudo leer la web (%s)' % type(e).__name__) from None |
| 617 | finally: |
| 618 | deadline.cancel() |
| 619 | |
| 620 | |
| 621 | class _RateLimiter: |
| 622 | """Ventana deslizante por clave, segura entre hilos, que olvida las claves |
| 623 | viejas (la de /proxy/report crece sin fin).""" |
| 624 | |
| 625 | def __init__(self, window_s, max_hits): |
| 626 | self.window_s, self.max_hits = window_s, max_hits |
| 627 | self._hits = {} |
| 628 | self._lock = threading.Lock() |
| 629 | self._swept = time.monotonic() |
| 630 | |
| 631 | def allow(self, key): |
| 632 | now = time.monotonic() |
| 633 | with self._lock: |
| 634 | if now - self._swept > self.window_s: |
| 635 | self._hits = {k: v for k, v in self._hits.items() if v and now - v[-1] < self.window_s} |
| 636 | self._swept = now |
| 637 | hits = [t for t in self._hits.get(key, ()) if now - t < self.window_s] |
| 638 | ok = len(hits) < self.max_hits |
| 639 | if ok: |
| 640 | hits.append(now) |
| 641 | self._hits[key] = hits |
| 642 | return ok |
| 643 | |
| 644 | |
| 645 | PROXY_RATE = _RateLimiter(PROXY_RATE_WINDOW_S, PROXY_RATE_MAX) |
| 646 | PROXY_GLOBAL_RATE = _RateLimiter(PROXY_RATE_WINDOW_S, PROXY_GLOBAL_MAX) # una sola clave: '*' |
| 647 | |
| 648 | |
| 649 | def _log_target(path): |
| 650 | """Para el log, solo esquema y host del destino: la ruta y la query pueden |
| 651 | llevar tokens, y lo que el usuario lee no tiene por qué quedar escrito.""" |
| 652 | try: |
| 653 | url = (urllib.parse.parse_qs(urllib.parse.urlsplit(path).query).get('url') or [''])[0] |
| 654 | parts = urllib.parse.urlsplit(url.strip()) |
| 655 | host = parts.hostname or '' |
| 656 | shown = '%s://%s' % (parts.scheme, '[%s]' % host if ':' in host else host) |
| 657 | except ValueError: |
| 658 | shown = '?' |
| 659 | return re.sub(r'[^A-Za-z0-9.:_\-\[\]/]', '?', shown)[:120] |
| 660 | |
| 661 | |
| 662 | class Handler(http.server.SimpleHTTPRequestHandler): |
| 663 | def __init__(self, *args, **kwargs): |
| 664 | super().__init__(*args, directory=ROOT, **kwargs) |
| 665 | |
| 666 | def end_headers(self): |
| 667 | self.send_header('Cache-Control', 'no-store') |
| 668 | super().end_headers() |
| 669 | |
| 670 | # SimpleHTTPRequestHandler NO implementa Range, y el runtime propio lee los |
| 671 | # pesos por TROZOS: sin esto, un GGUF de cientos de MB simplemente no se |
| 672 | # puede cargar contra el servidor de desarrollo — falla en la primera |
| 673 | # petición parcial, no al final. En producción lo resuelve nginx. |
| 674 | def send_head(self): |
| 675 | rng = self.headers.get('Range') |
| 676 | if not rng: |
| 677 | return super().send_head() |
| 678 | path = self.translate_path(self.path) |
| 679 | if os.path.isdir(path): |
| 680 | return super().send_head() |
| 681 | try: |
| 682 | f = open(path, 'rb') |
| 683 | except OSError: |
| 684 | self.send_error(404) |
| 685 | return None |
| 686 | size = os.fstat(f.fileno()).st_size |
| 687 | m = re.match(r'^bytes=(\d*)-(\d*)$', rng.strip()) |
| 688 | if not m: |
| 689 | f.close() |
| 690 | self.send_error(400, 'Range mal formado') |
| 691 | return None |
| 692 | ini, fin = m.group(1), m.group(2) |
| 693 | if ini == '': # sufijo: los últimos N bytes |
| 694 | start, end = max(0, size - int(fin or 0)), size - 1 |
| 695 | else: |
| 696 | start = int(ini) |
| 697 | end = int(fin) if fin else size - 1 |
| 698 | if start >= size or start > end: |
| 699 | f.close() |
| 700 | self.send_response(416) |
| 701 | self.send_header('Content-Range', 'bytes */%d' % size) |
| 702 | self.end_headers() |
| 703 | return None |
| 704 | end = min(end, size - 1) |
| 705 | f.seek(start) |
| 706 | self.send_response(206) |
| 707 | self.send_header('Content-Type', self.guess_type(path)) |
| 708 | self.send_header('Content-Range', 'bytes %d-%d/%d' % (start, end, size)) |
| 709 | self.send_header('Content-Length', str(end - start + 1)) |
| 710 | self.send_header('Accept-Ranges', 'bytes') |
| 711 | self.end_headers() |
| 712 | self._range_left = end - start + 1 |
| 713 | return f |
| 714 | |
| 715 | # copyfile() del padre volcaría el fichero ENTERO desde el offset: hay que |
| 716 | # cortarlo en los bytes pedidos o una petición de 4 bytes devuelve gigas. |
| 717 | def copyfile(self, source, outputfile): |
| 718 | left = getattr(self, '_range_left', None) |
| 719 | if left is None: |
| 720 | return super().copyfile(source, outputfile) |
| 721 | self._range_left = None |
| 722 | while left > 0: |
| 723 | chunk = source.read(min(1 << 16, left)) |
| 724 | if not chunk: |
| 725 | break |
| 726 | outputfile.write(chunk) |
| 727 | left -= len(chunk) |
| 728 | |
| 729 | def do_GET(self): |
| 730 | if self.path.startswith('/proxy?'): |
| 731 | return self.proxy() |
| 732 | if self.path.startswith('/v1/'): |
| 733 | return self.forward_lm() |
| 734 | super().do_GET() |
| 735 | |
| 736 | def do_POST(self): |
| 737 | if self.path.startswith('/v1/'): |
| 738 | return self.forward_lm() |
| 739 | if self.path == '/proxy/report': |
| 740 | return self.report() |
| 741 | self.send_error(404) |
| 742 | |
| 743 | def client_ip(self): |
| 744 | """IP del cliente para los límites. Detrás de nginx la conexión llega |
| 745 | SIEMPRE de 127.0.0.1, así que manda X-Forwarded-For, pero solo si lo |
| 746 | pone alguien en loopback (nginx) y tomando la ÚLTIMA entrada: con |
| 747 | $proxy_add_x_forwarded_for las anteriores las escribe el propio cliente.""" |
| 748 | peer = self.client_address[0] |
| 749 | xff = self.headers.get('X-Forwarded-For') or '' |
| 750 | if xff.strip() and _is_loopback(peer): |
| 751 | last = xff.split(',')[-1].strip() |
| 752 | if last: |
| 753 | return last[:64] |
| 754 | return peer |
| 755 | |
| 756 | def forward_lm(self): |
| 757 | """Reenvía /v1/* (API del modelo) al servidor de producción, con streaming.""" |
| 758 | length = int(self.headers.get('Content-Length') or 0) |
| 759 | body = self.rfile.read(length) if length else None |
| 760 | req = urllib.request.Request( |
| 761 | LM_UPSTREAM + self.path, data=body, method=self.command, |
| 762 | headers={'Content-Type': self.headers.get('Content-Type', 'application/json')}) |
| 763 | try: |
| 764 | with urllib.request.urlopen(req, timeout=300) as r: |
| 765 | self.send_response(r.status) |
| 766 | self.send_header('Content-Type', r.headers.get('Content-Type', 'application/json')) |
| 767 | self.end_headers() |
| 768 | while True: |
| 769 | chunk = r.read(1024) |
| 770 | if not chunk: |
| 771 | break |
| 772 | self.wfile.write(chunk) |
| 773 | self.wfile.flush() |
| 774 | except Exception as e: # noqa: BLE001 |
| 775 | self.send_error(502, f'lm: {e}') |
| 776 | |
| 777 | def _proxy_caller_ok(self): |
| 778 | """Solo la propia página (fetch del mismo origen) o un cliente que no es |
| 779 | un navegador (curl, el chequeo de salud). Fuera navegaciones, iframes, |
| 780 | <img>/<script> y cualquier otro origen: así una web ajena no usa el |
| 781 | navegador del usuario contra este proxy ni abre aquí HTML de terceros |
| 782 | con nuestro origen. NO es control de acceso: las cabeceras Sec-Fetch-* |
| 783 | y Origin solo las ponen los navegadores, y quien no las manda pasa.""" |
| 784 | site = (self.headers.get('Sec-Fetch-Site') or '').strip().lower() |
| 785 | dest = (self.headers.get('Sec-Fetch-Dest') or '').strip().lower() |
| 786 | if site not in ('', 'same-origin') or dest not in ('', 'empty'): |
| 787 | return False |
| 788 | origin = self.headers.get('Origin') |
| 789 | if origin is not None: |
| 790 | host = (self.headers.get('Host') or '').strip().lower() |
| 791 | try: |
| 792 | return urllib.parse.urlsplit(origin.strip()).netloc.lower() == host |
| 793 | except ValueError: |
| 794 | return False |
| 795 | return True |
| 796 | |
| 797 | def _proxy_safety_headers(self): |
| 798 | # Lo que sale de aquí es contenido de TERCEROS servido con NUESTRO |
| 799 | # origen: si alguien abre /proxy?url=<su html> como página, el sandbox |
| 800 | # sin scripts le quita el origen y no ejecuta nada. Sin CORS: la app lo |
| 801 | # pide desde su mismo origen y ninguna otra web tiene por qué leerlo. |
| 802 | self.send_header('X-Content-Type-Options', 'nosniff') |
| 803 | self.send_header('Content-Security-Policy', "sandbox; default-src 'none'; frame-ancestors 'none'") |
| 804 | self.send_header('Cross-Origin-Resource-Policy', 'same-origin') |
| 805 | self.send_header('Referrer-Policy', 'no-referrer') |
| 806 | |
| 807 | def _proxy_fail(self, status, code, detail, retry_after=None): |
| 808 | body = (detail + '\n').encode('utf-8') |
| 809 | self.send_response(status) |
| 810 | self.send_header('Content-Type', 'text/plain; charset=utf-8') |
| 811 | self.send_header('Content-Length', str(len(body))) |
| 812 | self.send_header('X-Proxy-Error', code) |
| 813 | if retry_after: |
| 814 | self.send_header('Retry-After', str(retry_after)) |
| 815 | self._proxy_safety_headers() |
| 816 | self.end_headers() |
| 817 | self.wfile.write(body) |
| 818 | |
| 819 | def proxy(self): |
| 820 | if not PROXY_RATE.allow(_rate_key(self.client_ip())): |
| 821 | return self._proxy_fail(429, 'rate-limited', 'demasiadas peticiones al proxy, espera un poco', |
| 822 | retry_after=PROXY_RATE_WINDOW_S) |
| 823 | if not self._proxy_caller_ok(): |
| 824 | return self._proxy_fail(403, 'cross-site', 'el proxy solo atiende a la propia app') |
| 825 | if not PROXY_GLOBAL_RATE.allow('*'): |
| 826 | return self._proxy_fail(503, 'overloaded', 'el proxy llegó a su límite de peticiones, prueba en un minuto', |
| 827 | retry_after=PROXY_RATE_WINDOW_S) |
| 828 | qs = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) |
| 829 | url = (qs.get('url') or [''])[0] |
| 830 | if not PROXY_SLOTS.acquire(blocking=False): |
| 831 | return self._proxy_fail(503, 'busy', 'proxy ocupado, prueba en unos segundos', retry_after=5) |
| 832 | try: |
| 833 | res = proxy_fetch(url) |
| 834 | except ProxyRefused as e: |
| 835 | return self._proxy_fail(e.status, e.code, e.detail) |
| 836 | finally: |
| 837 | PROXY_SLOTS.release() |
| 838 | body = b'' if res.status in (204, 205) else res.body |
| 839 | self.send_response(res.status) |
| 840 | self.send_header('Content-Type', res.content_type) |
| 841 | self.send_header('Content-Length', str(len(body))) |
| 842 | self.send_header('X-Proxy-Truncated', '1' if res.truncated else '0') |
| 843 | self.send_header('X-Proxy-Upstream-Status', str(res.upstream_status)) |
| 844 | self._proxy_safety_headers() |
| 845 | self.end_headers() |
| 846 | self.wfile.write(body) |
| 847 | |
| 848 | def report(self): |
| 849 | """Recibe {app, kind, message, stack, url, userAgent, extra} y lo |
| 850 | anexa a REPORTS_PATH. Solo texto/metadatos — nunca código ni |
| 851 | contenido del proyecto del usuario (eso jamás sale de su navegador).""" |
| 852 | # nginx (proxy_pass) hace que client_address SIEMPRE sea 127.0.0.1: |
| 853 | # con X-Forwarded-For (ver client_ip), el límite es por IP real. |
| 854 | ip = self.client_ip() |
| 855 | now = time.time() |
| 856 | hits = [t for t in REPORT_RATE.get(ip, []) if now - t < RATE_WINDOW_S] |
| 857 | if len(hits) >= RATE_MAX: |
| 858 | return self.send_error(429, 'demasiados informes, espera un poco') |
| 859 | hits.append(now) |
| 860 | REPORT_RATE[ip] = hits |
| 861 | |
| 862 | length = int(self.headers.get('Content-Length') or 0) |
| 863 | if length > MAX_REPORT_BYTES: |
| 864 | return self.send_error(413, 'informe demasiado grande') |
| 865 | body = self.rfile.read(length) if length else b'' |
| 866 | try: |
| 867 | payload = json.loads(body or b'{}') |
| 868 | if not isinstance(payload, dict): |
| 869 | raise ValueError('payload no es un objeto') |
| 870 | except Exception: |
| 871 | return self.send_error(400, 'JSON inválido') |
| 872 | |
| 873 | record = { |
| 874 | 'ts': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(now)), |
| 875 | 'ip': ip, |
| 876 | 'app': str(payload.get('app', ''))[:60], |
| 877 | 'kind': str(payload.get('kind', ''))[:30], |
| 878 | 'message': str(payload.get('message', ''))[:2000], |
| 879 | 'stack': str(payload.get('stack', ''))[:4000], |
| 880 | 'url': str(payload.get('url', ''))[:300], |
| 881 | 'userAgent': str(payload.get('userAgent', ''))[:300], |
| 882 | 'extra': str(payload.get('extra', ''))[:2000], |
| 883 | } |
| 884 | try: |
| 885 | path = Path(REPORTS_PATH) |
| 886 | path.parent.mkdir(parents=True, exist_ok=True) |
| 887 | with path.open('a', encoding='utf-8') as f: |
| 888 | f.write(json.dumps(record, ensure_ascii=False) + '\n') |
| 889 | except Exception as e: # noqa: BLE001 |
| 890 | return self.send_error(500, f'no pude guardar: {e}') |
| 891 | |
| 892 | self.send_response(200) |
| 893 | self.send_header('Content-Type', 'application/json') |
| 894 | self.end_headers() |
| 895 | self.wfile.write(b'{"ok":true}') |
| 896 | |
| 897 | def log_request(self, code='-', size='-'): |
| 898 | if isinstance(code, HTTPStatus): |
| 899 | code = code.value |
| 900 | line = self.requestline |
| 901 | path = getattr(self, 'path', '') or '' |
| 902 | if path.startswith('/proxy?'): |
| 903 | line = '%s /proxy?url=%s' % (self.command, _log_target(path)) |
| 904 | self.log_message('"%s" %s %s', line, str(code), str(size)) |
| 905 | |
| 906 | def log_message(self, fmt, *args): |
| 907 | sys.stderr.write('· %s\n' % (fmt % args)) |
| 908 | |
| 909 | |
| 910 | def main(argv=None): |
| 911 | argv = sys.argv if argv is None else argv |
| 912 | port = int(argv[1]) if len(argv) > 1 else 8642 |
| 913 | # Solo loopback salvo que se pida: en producción delante va nginx, y en |
| 914 | # local basta localhost. Abrirlo a la red expone también el proxy. |
| 915 | bind = os.environ.get('ELFFUSS_BIND', '127.0.0.1') |
| 916 | socketserver.ThreadingTCPServer.allow_reuse_address = True |
| 917 | with socketserver.ThreadingTCPServer((bind, port), Handler) as httpd: |
| 918 | print(f'✳ Elffuss · http://localhost:{port}') |
| 919 | # Cuántas, no cuáles: si sale 0 en un servidor con IP pública, esa IP |
| 920 | # no está en ninguna interfaz (NAT) y va a mano en ELFFUSS_PROXY_DENY. |
| 921 | print(f' /proxy rechaza {len(_self_addresses())} dirección(es) pública(s) de esta máquina' |
| 922 | f' y {len(PROXY_DENY)} red(es) de ELFFUSS_PROXY_DENY', flush=True) |
| 923 | httpd.serve_forever() |
| 924 | |
| 925 | |
| 926 | if __name__ == '__main__': |
| 927 | main() |