Autonomous OODA-loop pentesting agent. Hermes brain, Kali + Playwright tools over MCP, ATT&CK as the Orient language.
Python ai-agentsautonomous-agentskali-linuxllm-agentsoffensive-securityooda-looppentestingplaywrightsecurity
feat(kali): add Caido integration (caido_graphql, caido_request, caido_history)
G0dspbaed283d6820
diff --git a/.env.example b/.env.exampleindex 38f7b3a..62f109a 100644--- a/.env.example+++ b/.env.example@@ -135,3 +135,43 @@ DNSDUMPSTER_API_KEY=# (core/plugins/theme versions) WITHOUT a token; the token only adds known-vulnerability# (CVE) data to the results. Get one at https://wpscan.com/profile (free tier: 25 req/day).WPSCAN_API_TOKEN=++# --- Caido (web toolkit: proxy + Replay + HTTPQL + scope + workflows) ---------+# Powers the caido_graphql / caido_request / caido_history tools in kali-mcp (see docs/caido.md).+# The `caido` service (docker-compose.yml) runs the toolkit; kali-mcp reaches it on the internal+# network as http://caido:8080. ZERO-TOUCH BY DEFAULT: the service starts with --allow-guests and+# kali-mcp logs in headlessly (`loginAsGuest`) and picks/creates a project on its own, so with+# the defaults NOTHING in this section needs to be set.+#+# Leave CAIDO_URL empty to use the bundled service, or point it at an external Caido instance+# (e.g. an SSH tunnel to a remote host).+CAIDO_URL=++# OPTIONAL. Only if you use a Caido instance WITHOUT --allow-guests (e.g. an external one, or+# you published the bundled port and removed --allow-guests): a Personal Access Token from the+# Caido GUI (Developer page). Takes precedence over the guest login. CAIDO_ACCESS_TOKEN is the+# shorter-lived (~7 days) GUI session token, used only if CAIDO_PAT is empty.+CAIDO_PAT=+CAIDO_ACCESS_TOKEN=++# OPTIONAL. 0 disables the headless guest login, so ONLY CAIDO_PAT/CAIDO_ACCESS_TOKEN are valid+# (the tools return `unauthenticated` without one). Empty/1 = guest login allowed (default).+CAIDO_ALLOW_GUEST=++# OPTIONAL. Caido image. Empty = caido/caido:0.59.0, the release the caido_request/+# caido_history queries were verified against (Caido's GraphQL schema changes between+# releases; the caido_graphql passthrough stays version-agnostic).+CAIDO_IMAGE=++# OPTIONAL tuning (empty = built-in default): per-HTTP-call timeout in seconds (60); cap in+# bytes of the response returned by caido_request (20000); name of the project created when+# the instance has none (vulnerator).+CAIDO_TIMEOUT=+CAIDO_MAX_RESPONSE_BYTES=+CAIDO_PROJECT=++# OPTIONAL. HOST port to publish the Caido GUI/proxy on a CONTROLLED machine (also uncomment+# the caido service 'ports:' block). Empty = 7000. By default NOTHING is published (internal+# docker network only). If you publish it, drop --allow-guests from the service command and use+# CAIDO_PAT: a guest token would be obtainable by anyone who can reach the port.+CAIDO_HOST_PORT=diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 61d1e2d..2910c1f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Caido integration (`caido_graphql`, `caido_request`, `caido_history`)** — kali-mcp can now drive [Caido](https://caido.io) (proxy + Replay + HTTPQL + scope + workflows), so "anything Caido can do, Vulnerator can do". `caido_graphql` is a version-agnostic passthrough to Caido's whole public GraphQL API; `caido_request` sends a request through Caido's Replay (logged and searchable) **behind the same scope-guard as `kali_run`** (full `scheme://host:port` is validated, so `ports` in `scope.json` is honored); `caido_history` searches captured traffic by HTTPQL. New `caido` service in `docker-compose.yml` (internal network only, persistent volume, `--allow-guests`): fully zero-touch — kali-mcp logs in as guest and selects a project on its own. Stdlib-pure `docker/kali/caido_client.py` (no new dependencies), auto-renews a stale session if Caido is recreated, and reports `unauthenticated`/`unreachable` instead of faking success. See `docs/caido.md`.+## [1.7.0] - 2026-10-28### Addeddiff --git a/README.md b/README.mdindex 20697d7..97b3aaf 100644--- a/README.md+++ b/README.md@@ -204,7 +204,7 @@ Hermes uses **Mistral Large 4** as primary with automatic fallback to **GLM-5.3> **intentional.** Use it **only against explicitly authorized targets** and in a **controlled> environment**. All responsibility for the scope and for lawful use rests with the operator.-There are two opt-in controls (a deterministic scope-guard for `kali_run`/`kali_exec`, and the MCP+There are two opt-in controls (a deterministic scope-guard for `kali_run`/`kali_exec`/`caido_request`, and the MCPinbound token). Neither is consent or a firewall. See **[`docs/security.md`](docs/security.md)** forwhat each does and does **not** cover.diff --git a/docker-compose.yml b/docker-compose.ymlindex e1039ee..1c34d13 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -67,6 +67,24 @@ services:# guard even if the file says enabled:true (leave empty to honor the file).SCOPE_FILE: "${SCOPE_FILE:-/scope/scope.json}"SCOPE_ENFORCE: "${SCOPE_ENFORCE:-}"+ # --- Caido (toolkit web: proxy + Replay + HTTPQL + scope + workflows) ---+ # kali-mcp habla la API GraphQL de Caido para las tools caido_graphql/caido_request/+ # caido_history (ver docs/caido.md). El servicio `caido` (abajo) vive en la MISMA red+ # interna: se alcanza por DNS en http://caido:8080 (NO publicado al host). ZERO-TOUCH: el+ # servicio arranca con --allow-guests y caido_client inicia sesión como invitado y elige/+ # crea un proyecto solo, así que NO hace falta token. CAIDO_PAT/CAIDO_ACCESS_TOKEN son+ # OPCIONALES (Caido sin --allow-guests, o externo); CAIDO_ALLOW_GUEST=0 fuerza exigirlos.+ # Sin credenciales válidas las tools devuelven `unauthenticated` (no se finge).+ CAIDO_URL: "${CAIDO_URL:-http://caido:8080}"+ CAIDO_PAT: "${CAIDO_PAT:-}"+ CAIDO_ACCESS_TOKEN: "${CAIDO_ACCESS_TOKEN:-}"+ CAIDO_ALLOW_GUEST: "${CAIDO_ALLOW_GUEST:-1}"+ # Tuning (empty = built-in default): per-HTTP-call timeout in seconds (60), cap in bytes+ # of the response body returned by caido_request (20000), and the name of the project+ # created when the instance has none ("vulnerator").+ CAIDO_TIMEOUT: "${CAIDO_TIMEOUT:-}"+ CAIDO_MAX_RESPONSE_BYTES: "${CAIDO_MAX_RESPONSE_BYTES:-}"+ CAIDO_PROJECT: "${CAIDO_PROJECT:-}"# Scope-guard mount (OPT-IN): to turn the guard ON, create a `scope.json` at the repo# root (copy scope.example.json), set `enabled: true`, and UNCOMMENT the mount line# below (under this same volumes: block), then recreate the kali service. Keep it@@ -358,6 +376,94 @@ services:retries: 5start_period: 20s+ caido-init:+ # One-shot: make the caido-data named volume writable by Caido's non-root user.+ # Docker creates a NEW named volume root-owned, but the image runs as `caido` (uid/gid+ # 996, checked with `id`), so without this Caido panics at startup with "Unable to create+ # logging directory: Permission denied" (reproduced live). Uses the Caido image itself+ # (already pulled; no extra image) overriding the user to root just for the chown.+ image: "${CAIDO_IMAGE:-caido/caido:0.59.0}"+ user: "0:0"+ entrypoint: ["chown", "-R", "996:996", "/data"]+ command: []+ volumes:+ - caido-data:/data+ restart: "no"++ caido:+ # Caido — modern, Rust-powered web security toolkit (proxy + Replay + HTTPQL + scope ++ # workflows + findings), the engine behind the caido_graphql/caido_request/caido_history+ # tools in kali-mcp. Official image. It serves its GraphQL API (the one kali-mcp talks to)+ # and the GUI on :8080. It lives on the SAME internal compose network, so kali reaches it+ # by DNS as http://caido:8080. NO host port is published by default (internal network+ # only, like playwright-mcp/juice-shop), which keeps the surface confined to the+ # controlled environment; to reach the GUI from your machine, tunnel over SSH or+ # temporarily uncomment the ports: block below on a controlled host.+ #+ # VERSION: pinned by default to 0.59.0, the release the caido_request/caido_history queries+ # were verified against (Caido's GraphQL schema changes between releases; the caido_graphql+ # passthrough is version-agnostic). Override with CAIDO_IMAGE in .env to try another tag.+ image: "${CAIDO_IMAGE:-caido/caido:0.59.0}"+ # The image's ENTRYPOINT is ["tini","--"] and its default CMD is the full+ # `caido-cli --no-renderer-sandbox --no-open --listen 0.0.0.0:8080`. We restate that CMD+ # explicitly (binary INCLUDED — overriding with just flags drops caido-cli and tini fails+ # "exec --listen: No such file or directory") so a base-image change can't silently move+ # the listener off the address kali-mcp expects. --no-renderer-sandbox/--no-open are+ # required for headless (no GUI renderer, don't try to open a browser).+ #+ # --allow-guests is what makes the integration ZERO-TOUCH (verified live): without it a+ # fresh instance only hands out tokens after a human logs into the GUI with a Caido+ # account. With it, kali-mcp's caido_client calls the `loginAsGuest` GraphQL mutation and+ # gets a working token headlessly.+ #+ # TRADE-OFF (read this): "not published to the host" is NOT isolation from the other+ # services on this compose network. Any container on it — including a deliberately+ # vulnerable lab target such as juice-shop/DVWA, or an SSRF in one — can reach+ # http://caido:8080/graphql, call `loginAsGuest`, and obtain a full-privilege token (read+ # all captured traffic, send arbitrary Replay requests). This is acceptable for a local lab+ # and for engagements whose targets are EXTERNAL; if you put untrusted workloads on this+ # network, drop --allow-guests, set CAIDO_ALLOW_GUEST=0 and use a CAIDO_PAT instead (mint it+ # once via an SSH tunnel to the GUI). The same applies if you publish the port.+ command:+ - caido-cli+ - --no-renderer-sandbox+ - --no-open+ - --allow-guests+ # Caido's own anti-DNS-rebinding protection (same mechanism as playwright-mcp's+ # --allowed-hosts above): by default it ONLY accepts requests whose Host matches+ # localhost, so it rejects kali-mcp's calls with 403 ("Domain caido not allowed" in+ # the logs — reproduced live), which arrive with Host: caido:8080 (the service's+ # internal DNS name). That name is EXPLICITLY allowed (not a wildcard): it keeps the+ # protection scoped to the internal docker network, from which kali connects.+ - --ui-domain+ - caido+ - --listen+ - 0.0.0.0:8080+ depends_on:+ caido-init:+ condition: service_completed_successfully+ volumes:+ # Persist projects/sessions/token across recreates. The official image stores Caido+ # data under /home/caido/.local/share/caido; without this, projects created in the+ # container are lost on each `up`. NAMED volume (not a bind-mount) by the same WAL/+ # virtiofs discipline the rest of the stack follows.+ - caido-data:/home/caido/.local/share/caido+ # To reach the GUI from the host (optional; the tools do NOT need it), tunnel over SSH to+ # this service, or UNCOMMENT on a CONTROLLED machine (exposes the proxy/GUI to the host;+ # see the --allow-guests note above before doing so):+ # ports:+ # - "${CAIDO_HOST_PORT:-7000}:8080"+ healthcheck:+ # The image ships neither curl nor nc (checked), but it has bash: probe with a raw TCP+ # connect through /dev/tcp.+ test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/8080"]+ interval: 10s+ timeout: 5s+ retries: 12+ start_period: 30s+ restart: unless-stopped+ # Default compose network: kali reaches it as caido:8080 via internal DNS.+volumes:# Hermes state (profile + SQLite WAL). NAMED on purpose: avoids the bind-mount# that corrupts the SQLite WAL on macOS virtiofs.@@ -365,3 +471,5 @@ volumes:# Kali artifacts plane (/artifacts). NAMED so the staged raw output persists across# container recreations.kali-artifacts:+ # Caido projects/sessions/token — persisted across recreates (see the caido service).+ caido-data:diff --git a/docker/kali/Dockerfile b/docker/kali/Dockerfileindex c34cfb8..70ef720 100644--- a/docker/kali/Dockerfile+++ b/docker/kali/Dockerfile@@ -197,6 +197,13 @@ COPY docker/kali/scope_guard.py ./scope_guard.py# the native modules; without these COPY the server would abort when loading the plugins report.COPY docker/kali/plugin_api.py ./plugin_api.pyCOPY docker/kali/plugin_loader.py ./plugin_loader.py++# Cliente de la API GraphQL de Caido (proxy + Replay + HTTPQL). STDLIB PURA. Lo importa+# kali_mcp_server (import caido_client) para las tools caido_graphql/caido_request/+# caido_history, por lo que DEBE estar en la imagen; sin este COPY el servidor aborta al+# arrancar con ModuleNotFoundError: No module named 'caido_client'. Caido en sí corre en su+# propio servicio del compose (no se instala nada en esta imagen).+COPY docker/kali/caido_client.py ./caido_client.pyCOPY docker/kali/kali_mcp_server.py ./kali_mcp_server.py# Versioned plugins tree (plugins ONLY). It is frozen INSIDE the image atdiff --git a/docker/kali/caido_client.py b/docker/kali/caido_client.pynew file mode 100644index 0000000..23c4173--- /dev/null+++ b/docker/kali/caido_client.py@@ -0,0 +1,910 @@+"""Cliente de la API GraphQL de Caido (STDLIB PURA) — el canal del agente hacia Caido.++Es la LÓGICA testeable de las tools ``caido_graphql`` / ``caido_request`` / ``caido_history``+que ``kali_mcp_server`` expone como ``@mcp.tool``. Igual que ``dnsdumpster_client`` /+``shell_exec`` / ``scope_guard``, vive en un módulo aparte con SOLO la librería estándar+(sin ``mcp`` ni ``requests``; HTTP por ``urllib``) para cubrirse con tests unitarios en el+venv de dev, sin el SDK.++Qué resuelve: darle al bucle OODA acceso a TODA la superficie de Caido (el moderno toolkit+web, proxy + Replay + HTTPQL + workflows + scope + findings). Caido publica su API GraphQL+a propósito para herramientas de terceros, pero AVISA de que CAMBIA en cada release. Por eso+la pieza central es un passthrough genérico (``graphql``): Hermes manda la query/mutación y+funciona contra cualquier versión del esquema. Encima, dos orquestadores ergonómicos para+los caminos calientes —enviar una petición por Replay (``send_request``) y buscar en el+historial por HTTPQL (``search_history``)— construidos sobre el flujo REAL del esquema,+VERIFICADO EN VIVO contra una instancia + OWASP Juice Shop (ver docs/caido.md). Si el esquema+difiere en otra versión, el error GraphQL del servidor se transporta VERBATIM (no se finge).++Modelo de auth (verificado en vivo): la introspección del esquema NO necesita token, pero+TODA operación real (Replay, historial) exige ``Authorization: Bearer <token>`` y, además,+un PROYECTO seleccionado (el repositorio de datos es por-proyecto). Hay dos orígenes de token:+ - Token del operador por entorno: ``CAIDO_PAT`` (Personal Access Token) o+ ``CAIDO_ACCESS_TOKEN`` (token de sesión del GUI). Para un Caido con cuenta/licencia.+ - Invitado headless: si la instancia corre con ``--allow-guests`` (así la levanta el+ compose), ``loginAsGuest`` emite un token SIN cuenta ni login GUI -> integración+ ZERO-TOUCH. Es el camino por defecto para el lab autónomo.+``ensure_session`` resuelve ambos: usa el token de entorno si está; si no, inicia sesión de+invitado (cacheada), y en ambos casos SELECCIONA un proyecto (crea uno si no hay). Sin token+y sin invitados permitidos, las operaciones devuelven ``unauthenticated`` fail-closed (no se+finge; ``server_info`` refleja el estado).++Dato NO confiable: todo lo que devuelve Caido (``data``/``errors``) se transporta verbatim;+aquí sólo se NORMALIZA la forma del transporte (HTTP/JSON/errores GraphQL), nunca se+interpreta el contenido. Las funciones ``build_*``/``normalize_*``/``split_target_url`` son+PURAS y son el núcleo cubierto por tests; ``graphql``/``ensure_session``/``send_request``/+``search_history`` son los orquestadores con I/O de red.+"""++from __future__ import annotations++import base64+import http.client+import ipaddress+import json+import os+import re+import threading+import time+import urllib.error+import urllib.request+from typing import Any+from urllib.parse import urlsplit++# --- Configuración por entorno (overridable; defaults para la red interna docker) -------++DEFAULT_URL = os.environ.get("CAIDO_URL", "http://caido:8080")+GRAPHQL_PATH = os.environ.get("CAIDO_GRAPHQL_PATH", "/graphql")+TOKEN_ENV = "CAIDO_PAT"+ALT_TOKEN_ENV = "CAIDO_ACCESS_TOKEN"+++def _env_int(name: str, default: int) -> int:+ """Entero de entorno TOLERANTE: vacío o basura -> ``default`` (no aborta el servidor)."""+ try:+ return int((os.environ.get(name) or "").strip() or default)+ except ValueError:+ return default+++def _env_float(name: str, default: float) -> float:+ """Float de entorno TOLERANTE: vacío o basura -> ``default``."""+ try:+ return float((os.environ.get(name) or "").strip() or default)+ except ValueError:+ return default+++DEFAULT_TIMEOUT_S = _env_int("CAIDO_TIMEOUT", 60)++# Login de invitado headless (loginAsGuest). On por defecto: el compose levanta Caido con+# --allow-guests, así las tools funcionan sin que el operador monte una cuenta. Se puede+# desactivar (CAIDO_ALLOW_GUEST=0) para forzar que sólo valga un token de entorno.+# FAIL-CLOSED: sólo valores explícitamente afirmativos (o vacío = default) lo activan; cualquier+# otro (0/false/no/off/basura) lo DESACTIVA, así "no" nunca deja el invitado abierto en silencio.+ALLOW_GUEST = os.environ.get("CAIDO_ALLOW_GUEST", "1").strip().lower() in (+ "",+ "1",+ "true",+ "yes",+ "on",+)++# Nombre del proyecto que el cliente crea si la instancia no tiene ninguno (idempotente:+# si ya hay proyectos, selecciona el primero READY en vez de crear).+PROJECT_NAME = (os.environ.get("CAIDO_PROJECT") or "").strip() or "vulnerator"++# Sondeo de la respuesta de Replay (es asíncrona: startReplayTask lanza y la respuesta+# aparece en el historial). Tope y cadencia del polling.+REPLAY_POLL_TRIES = _env_int("CAIDO_REPLAY_POLL_TRIES", 30)+REPLAY_POLL_INTERVAL_S = _env_float("CAIDO_REPLAY_POLL_INTERVAL", 1.0)++# Tope (bytes) del raw de la respuesta que se devuelve al agente (cabeceras + cuerpo); el resto+# se corta con ``raw_truncated=True``. Evita que una descarga enorme reviente el contexto.+DEFAULT_MAX_RESPONSE_BYTES = _env_int("CAIDO_MAX_RESPONSE_BYTES", 20000)++# Tope defensivo del cuerpo que leemos de una respuesta de error (evita tragar MB de HTML).+_MAX_ERROR_BODY = 2000+++class CaidoError(ValueError):+ """Entrada inválida a una build_* (fail-closed: la tool no llega a llamar a Caido)."""+++# --- Resolución de endpoint / token (I/O de entorno, sin red) ---------------------------+++def resolve_url(url: str | None = None) -> str:+ """Normaliza la base de la instancia Caido (sin barra final), de arg o entorno."""+ base = (url or DEFAULT_URL or "").strip()+ if not base:+ raise CaidoError(+ "Falta la URL de Caido: pásala o exporta CAIDO_URL (p. ej. http://caido:8080)."+ )+ if "://" not in base:+ base = "http://" + base+ # Sólo http/https: `urlopen` aceptaría file://, ftp://... y CAIDO_URL es config del operador+ # pero no debe poder abrir ficheros locales por un descuido (bandit B310).+ try:+ scheme = urlsplit(base).scheme.lower()+ except ValueError as exc:+ raise CaidoError(f"CAIDO_URL inválida ({exc}): {base!r}") from exc+ if scheme not in ("http", "https"):+ raise CaidoError(+ f"CAIDO_URL con esquema no permitido ({scheme!r}): sólo http/https."+ )+ return base.rstrip("/")+++def resolve_url_safe(url: str | None = None) -> str:+ """Como ``resolve_url`` pero NO lanza: devuelve "" si no hay URL. Para ``server_info``."""+ try:+ return resolve_url(url)+ except CaidoError:+ return ""+++def env_token() -> str | None:+ """Token del operador por entorno (PAT > access token), o ``None`` si no hay ninguno."""+ for candidate in (os.environ.get(TOKEN_ENV), os.environ.get(ALT_TOKEN_ENV)):+ if candidate and candidate.strip():+ return candidate.strip()+ return None+++def token_present() -> bool:+ """¿Hay token de entorno configurado? Lo usa ``server_info`` (sin llamar a Caido)."""+ return env_token() is not None+++def graphql_endpoint(url: str | None = None) -> str:+ """URL completa del endpoint GraphQL (``<base><GRAPHQL_PATH>``)."""+ return resolve_url(url) + GRAPHQL_PATH+++# --- Normalización de la respuesta (PURA: dict de transporte -> dict de estado) ----------+++def normalize_graphql_response(payload: dict[str, Any]) -> dict[str, Any]:+ """Clasifica una respuesta GraphQL YA parseada (HTTP 200) en un estado uniforme.++ GraphQL devuelve 200 incluso con errores de resolución (array ``errors``). Caido marca+ los fallos de auth dentro de ``errors[].extensions.CAIDO.code == 'AUTHORIZATION'``; se+ detecta para devolver ``unauthenticated`` (señal accionable para el OODA), sin interpretar+ el resto. DATO NO CONFIABLE: ``data``/``errors`` verbatim.+ - ``{'status':'ok','data':...}`` sin ``errors``.+ - ``{'status':'unauthenticated','error':...,'errors':...}`` si algún error es de auth.+ - ``{'status':'graphql_error','errors':...,'data':...}`` otros errores GraphQL.+ """+ errors = payload.get("errors")+ if not errors:+ return {"status": "ok", "data": payload.get("data")}+ for e in errors:+ ext = (e or {}).get("extensions") or {}+ caido = ext.get("CAIDO") or {}+ if (+ caido.get("code") == "AUTHORIZATION"+ or caido.get("reason") == "INVALID_TOKEN"+ ):+ return {+ "status": "unauthenticated",+ "error": "Caido rechazó el token (AUTHORIZATION/INVALID_TOKEN).",+ "errors": errors,+ }+ return {"status": "graphql_error", "errors": errors, "data": payload.get("data")}+++# --- Orquestador de red: transporte GraphQL (auth OPCIONAL) -----------------------------+++def graphql(+ query: str,+ variables: dict[str, Any] | None = None,+ *,+ url: str | None = None,+ token: str | None = None,+ operation_name: str | None = None,+ timeout: int = DEFAULT_TIMEOUT_S,+) -> dict[str, Any]:+ """POST al endpoint GraphQL de Caido. Nunca lanza por un error de red/HTTP.++ Transporte puro: si se pasa ``token`` adjunta ``Authorization: Bearer``; si no, va sin+ auth (la introspección y ``loginAsGuest`` no la necesitan; las operaciones devolverán+ ``unauthenticated``). Es el passthrough genérico sobre el que se apoyan todas las tools.++ Devuelve un dict de estado uniforme (fail-closed; el bloqueo/errores prevalecen):+ - ``{'status':'ok','data':...}``+ - ``{'status':'unauthenticated',...}`` (sin token válido / 401/403 / error de auth)+ - ``{'status':'graphql_error',...}`` (200 con errores GraphQL no-auth)+ - ``{'status':'unreachable','error':...}`` (no se pudo conectar)+ - ``{'status':'failed','http_status':n,'error':...}`` (otros HTTP / respuesta no-JSON)+ """+ try:+ endpoint = graphql_endpoint(url)+ except CaidoError as exc:+ return {"status": "failed", "error": str(exc)}++ body: dict[str, Any] = {"query": query, "variables": variables or {}}+ if operation_name:+ body["operationName"] = operation_name+ headers = {"Content-Type": "application/json", "Accept": "application/json"}+ if token:+ headers["Authorization"] = f"Bearer {token}"+ try:+ req = urllib.request.Request(+ endpoint,+ data=json.dumps(body).encode("utf-8"),+ method="POST",+ headers=headers,+ )+ # El esquema sale de CAIDO_URL (operador) y `resolve_url` sólo admite http/https: no hay+ # file:// ni esquemas raros, y ninguna entrada de Hermes llega a esta URL.+ with urllib.request.urlopen( # noqa: S310 # nosec B310+ req, timeout=timeout+ ) as resp:+ raw = resp.read().decode("utf-8", errors="replace")+ except urllib.error.HTTPError as exc:+ err_body = ""+ try:+ err_body = exc.read().decode("utf-8", errors="replace")[:_MAX_ERROR_BODY]+ except Exception: # noqa: BLE001 - informativo+ pass+ if exc.code in (401, 403):+ return {+ "status": "unauthenticated",+ "error": err_body+ or f"HTTP {exc.code}: token de Caido inválido o expirado.",+ }+ return {+ "status": "failed",+ "http_status": exc.code,+ "error": err_body or str(exc),+ }+ except urllib.error.URLError as exc:+ return {+ "status": "unreachable",+ "error": f"No se pudo conectar a Caido ({endpoint}): {exc.reason}",+ }+ except (OSError, http.client.HTTPException) as exc:+ # Conexión cortada a mitad, timeout de LECTURA, respuesta truncada/basura...: Caido+ # reiniciándose o un cuerpo lento. Estado reportable, nunca una excepción de la tool.+ return {+ "status": "unreachable",+ "error": f"Fallo de transporte con Caido ({endpoint}): {type(exc).__name__}: {exc}",+ }+ except (+ ValueError+ ) as exc: # URL inválida en CAIDO_URL (InvalidURL/espacios/corchetes)+ return {+ "status": "failed",+ "error": f"URL de Caido inválida ({endpoint}): {exc}",+ }++ try:+ parsed = json.loads(raw)+ except (ValueError, json.JSONDecodeError) as exc:+ return {"status": "failed", "error": f"Respuesta no-JSON de Caido: {exc}"}+ if not isinstance(parsed, dict):+ return {+ "status": "failed",+ "error": "Respuesta GraphQL inesperada (no es objeto).",+ }+ return normalize_graphql_response(parsed)+++# --- Documentos GraphQL del flujo REAL (verificados en vivo; dependientes de versión) ---+#+# Caido avisa de que el esquema cambia en cada release. Estos documentos están VERIFICADOS+# contra una instancia real (ver docs/caido.md); si una versión los rompe, ``graphql``+# devuelve ``graphql_error`` con el error del servidor verbatim (no se finge éxito), y+# ``caido_graphql`` (passthrough) sigue alcanzando el esquema nuevo sin tocar este módulo.++_GUEST_LOGIN = (+ "mutation{ loginAsGuest{ token{ accessToken expiresAt } error{ __typename } } }"+)+_PROJECTS = "query{ projects{ id name status } }"+_SELECT_PROJECT = (+ "mutation($id:ID!){ selectProject(id:$id){ currentProject{ __typename } "+ "error{ __typename } } }"+)+_CREATE_PROJECT = (+ "mutation($i:CreateProjectInput!){ createProject(input:$i){ project{ id } "+ "error{ __typename } } }"+)+CREATE_REPLAY_SESSION = (+ "mutation($i:CreateReplaySessionInput!){ createReplaySession(input:$i){ "+ "session{ id } error{ __typename } } }"+)+START_REPLAY_TASK = "mutation($id:ID!){ startReplayTask(sessionId:$id){ task{ id } error{ __typename } } }"+REQUEST_RAW_QUERY = "query($id:ID!){ request(id:$id){ raw response{ raw } } }"+HISTORY_QUERY = (+ "query($f:HTTPQLInput,$n:Int!,$o:RequestResponseOrderInput){ "+ "requests(first:$n, filter:$f, order:$o){ count{ value } edges{ node{ "+ "id method host port path isTls length createdAt "+ "response{ id statusCode roundtripTime length createdAt } } } } }"+)+++# --- Gestión de sesión (token invitado/entorno + proyecto), cacheada y thread-safe ------++_SESSION: dict[str, Any] = {"token": None, "project_id": None}+_SESSION_LOCK = threading.Lock()+++def reset_session() -> None:+ """Limpia la sesión cacheada (token + proyecto). Para tests y re-auth tras expirar."""+ with _SESSION_LOCK:+ _SESSION["token"] = None+ _SESSION["project_id"] = None+++def _guest_login(url: str | None, timeout: int) -> dict[str, Any]:+ """loginAsGuest -> ``{'status':'ok','token':...}`` o un dict de error de ``graphql``."""+ out = graphql(_GUEST_LOGIN, url=url, timeout=timeout)+ if out["status"] != "ok":+ return out+ payload = (out.get("data") or {}).get("loginAsGuest") or {}+ tok = (payload.get("token") or {}).get("accessToken")+ if not tok:+ return {+ "status": "unauthenticated",+ "error": (+ "loginAsGuest no emitió token (%s). ¿Corre Caido con --allow-guests?"+ % (payload.get("error") or "sin detalle")+ ),+ }+ return {"status": "ok", "token": tok}+++def _ensure_project(token: str, url: str | None, timeout: int) -> dict[str, Any]:+ """Garantiza un proyecto SELECCIONADO (crea uno si no hay). Devuelve estado uniforme.++ El repositorio de datos de Caido es por-proyecto: sin proyecto seleccionado, Replay e+ historial fallan con un error interno de base de datos. Idempotente: si ya hay proyectos+ selecciona el primero READY; si no, crea ``PROJECT_NAME`` (temporary) y lo selecciona.+ """+ listing = graphql(_PROJECTS, url=url, token=token, timeout=timeout)+ if listing["status"] != "ok":+ return listing+ projects = (listing.get("data") or {}).get("projects") or []+ project_id = None+ for p in projects:+ if p.get("status") == "READY":+ project_id = p.get("id")+ break+ if project_id is None and projects:+ project_id = projects[0].get("id")+ if project_id is None:+ created = graphql(+ _CREATE_PROJECT,+ {"i": {"name": PROJECT_NAME, "temporary": True}},+ url=url,+ token=token,+ timeout=timeout,+ )+ if created["status"] != "ok":+ return created+ cp = (created.get("data") or {}).get("createProject") or {}+ if not cp.get("project"):+ return {+ "status": "failed",+ "error": "No se pudo crear proyecto en Caido: %s"+ % (cp.get("error") or "?"),+ }+ project_id = cp["project"]["id"]+ selected = graphql(+ _SELECT_PROJECT, {"id": project_id}, url=url, token=token, timeout=timeout+ )+ if selected["status"] != "ok":+ return selected+ return {"status": "ok", "project_id": project_id}+++def ensure_session(+ url: str | None = None, timeout: int = DEFAULT_TIMEOUT_S, force: bool = False+) -> dict[str, Any]:+ """Resuelve (token, project_id) listos para operar. Cacheado y thread-safe.++ Orden: token de entorno (``CAIDO_PAT``/``CAIDO_ACCESS_TOKEN``) si hay; si no y+ ``ALLOW_GUEST``, ``loginAsGuest``; en ambos casos asegura un proyecto seleccionado.+ Sin token y sin invitados -> ``unauthenticated`` (no se finge).++ Returns ``{'status':'ok','token':...,'project_id':...}`` o un dict de error uniforme.+ """+ with _SESSION_LOCK:+ if not force and _SESSION["token"] and _SESSION["project_id"]:+ return {+ "status": "ok",+ "token": _SESSION["token"],+ "project_id": _SESSION["project_id"],+ }++ token = env_token()+ if token is None:+ if not ALLOW_GUEST:+ return {+ "status": "unauthenticated",+ "error": (+ "Caido sin token y login de invitado desactivado "+ "(CAIDO_ALLOW_GUEST=0): exporta CAIDO_PAT o CAIDO_ACCESS_TOKEN."+ ),+ }+ guest = _guest_login(url, timeout)+ if guest["status"] != "ok":+ return guest+ token = guest["token"]++ proj = _ensure_project(token, url, timeout)+ if proj["status"] != "ok":+ return proj++ _SESSION["token"] = token+ _SESSION["project_id"] = proj["project_id"]+ return {"status": "ok", "token": token, "project_id": proj["project_id"]}+++# --- Builders PUROS (testables) ---------------------------------------------------------+++def split_target_url(url: str) -> dict[str, Any]:+ """Descompone una URL de objetivo en ``{host, port, is_tls, path}``. PURA.++ Deriva el esquema (``https`` -> tls y puerto 443 por defecto; ``http`` -> 80); un puerto+ explícito gana. Sin esquema se asume ``https``. ``path`` conserva la query para reproducir+ la petición tal cual. Fail-closed: una URL sin host es ``CaidoError``.+ """+ raw = (url or "").strip()+ if not raw:+ raise CaidoError("URL de objetivo vacía.")+ if "://" not in raw:+ raw = "https://" + raw+ try:+ parts = urlsplit(raw)+ host = parts.hostname+ explicit_port = (+ parts.port+ ) # lanza ValueError si es no numérico / fuera de rango+ except ValueError as exc:+ raise CaidoError(f"URL de objetivo inválida ({exc}): {url!r}") from exc+ if not host:+ raise CaidoError(f"URL sin host: {url!r}")+ host = host.rstrip(".") # `example.com.` y `example.com` son el MISMO destino+ if not host:+ raise CaidoError(f"URL sin host: {url!r}")+ # Un IPv6 "IPv4-mapped" (::ffff:a.b.c.d, o ::ffff:a9fe:a9fe) CONECTA por IPv4 pero un CIDR+ # IPv4 de `deny` no lo casaría (familias distintas en el guard): se normaliza a la IPv4+ # real, así gate y conexión ven EXACTAMENTE el mismo destino (bypass hallado en revisión).+ try:+ _ip = ipaddress.ip_address(host)+ except ValueError:+ _ip = None+ if isinstance(_ip, ipaddress.IPv6Address) and _ip.ipv4_mapped is not None:+ host = str(_ip.ipv4_mapped)+ is_tls = parts.scheme == "https"+ port = explicit_port or (443 if is_tls else 80)+ path = parts.path or "/"+ if parts.query:+ path = f"{path}?{parts.query}"+ return {"host": host, "port": port, "is_tls": is_tls, "path": path}+++def _utf8(text: str) -> bytes:+ """``text`` a bytes UTF-8; un surrogate suelto (p. ej. JSON ``"\\ud800"``) es ``CaidoError``."""+ try:+ return text.encode("utf-8")+ except UnicodeEncodeError as exc:+ raise CaidoError(+ f"texto no codificable en UTF-8 (surrogate suelto): {exc}"+ ) from exc+++_METHOD_RE = re.compile(r"^[A-Za-z]{1,32}$")+_CTL_RE = re.compile(r"[\r\n\x00]")+++def host_header_value(host: str, port: int, is_tls: bool) -> str:+ """Valor correcto de ``Host``: corchetes para IPv6 y puerto sólo si NO es el por defecto."""+ h = f"[{host}]" if ":" in host and not host.startswith("[") else host+ default = 443 if is_tls else 80+ return h if int(port) == default else f"{h}:{int(port)}"+++def scope_target(target: dict[str, Any]) -> str:+ """Destino ``esquema://host:puerto`` que se declara al scope-guard (IPv6 con corchetes). PURA.++ Es la ÚNICA fuente de verdad del destino que se valida: se construye de lo mismo que se+ usa para conectar (``split_target_url``), nunca re-parseando la URL del usuario, así el+ gate y la conexión no pueden discrepar.+ """+ scheme = "https" if target["is_tls"] else "http"+ host = target["host"]+ host = f"[{host}]" if ":" in host else host+ return f"{scheme}://{host}:{target['port']}"+++def build_raw_request(+ method: str,+ path: str,+ host: str,+ headers: dict[str, str] | None = None,+ body: str = "",+ http_version: str = "HTTP/1.1",+ host_header: str | None = None,+) -> str:+ """Construye una petición HTTP CRUDA (líneas CRLF). PURA.++ Garantiza ``Host`` (de ``host`` si no viene en ``headers``), añade ``Content-Length`` si+ hay cuerpo y no se declaró, y fuerza ``Connection: close`` si no se especifica (así el+ Replay no se queda esperando keep-alive). Lo demás, lo que se pasa y nada más (el objetivo+ ve exactamente lo pedido; DATO NO confiable transportado verbatim).+ """+ m = (method or "GET").strip().upper()+ if not _METHOD_RE.match(m):+ raise CaidoError(f"método HTTP inválido: {method!r}")+ p = (path or "/").strip() or "/"+ if not p.startswith("/"):+ p = "/" + p+ if _CTL_RE.search(p) or " " in p:+ raise CaidoError("path inválido: contiene CR/LF/NUL o espacios.")+ hdrs = {k: v for k, v in (headers or {}).items() if k and v is not None}+ # CRLF/NUL en nombre o valor de cabecera permitiría inyectar una segunda petición (request+ # smuggling/pipelining) hacia vhosts o rutas no previstas. Se rechaza, no se sanea.+ for k, v in hdrs.items():+ if _CTL_RE.search(str(k)) or _CTL_RE.search(str(v)) or ":" in str(k):+ raise CaidoError(f"cabecera inválida (CR/LF/NUL o ':' en el nombre): {k!r}")+ if not any(k.lower() == "host" for k in hdrs):+ hdrs["Host"] = host_header or host+ if body and not any(k.lower() == "content-length" for k in hdrs):+ hdrs["Content-Length"] = str(len(_utf8(body)))+ if not any(k.lower() == "connection" for k in hdrs):+ hdrs["Connection"] = "close"+ lines = [f"{m} {p} {http_version}"]+ lines.extend(f"{k}: {v}" for k, v in hdrs.items())+ return "\r\n".join(lines) + "\r\n\r\n" + (body or "")+++def build_replay_input(+ host: str, port: int, is_tls: bool, raw_request: str+) -> dict[str, Any]:+ """Arma las ``variables`` de ``CREATE_REPLAY_SESSION``. PURA (sin red).++ Codifica la petición cruda a base64 (el escalar ``Blob`` del esquema lo exige) y usa el+ nombre REAL del campo del esquema: ``isTLS`` (no ``isTls``). Valida host/puerto fail-closed.+ """+ h = (host or "").strip()+ if not h:+ raise CaidoError("host vacío: Replay necesita un destino.")+ try:+ p = int(port)+ except (TypeError, ValueError):+ raise CaidoError(f"puerto inválido: {port!r}")+ if not (1 <= p <= 65535):+ raise CaidoError(f"puerto fuera de rango (1..65535): {p}")+ blob = base64.b64encode(_utf8(raw_request or "")).decode("ascii")+ return {+ "i": {+ "kind": "HTTP",+ "requestSource": {+ "raw": {+ "connectionInfo": {"host": h, "port": p, "isTLS": bool(is_tls)},+ "raw": blob,+ }+ },+ }+ }+++def build_history_vars(httpql: str = "", limit: int = 50) -> dict[str, Any]:+ """Arma las ``variables`` de ``HISTORY_QUERY``. PURA.++ ``httpql`` es la expresión de Caido (p. ej. ``resp.code.eq:200``); vacío trae los últimos+ ``limit`` sin filtrar. El filtro va en el campo REAL del esquema ``HTTPQLInput.code``.+ Orden por id descendente (lo más reciente primero). ``limit`` se acota a 1..1000.+ """+ try:+ n = int(limit)+ except (TypeError, ValueError):+ n = 50+ n = max(1, min(n, 1000))+ expr = (httpql or "").strip()+ return {+ "f": {"code": expr} if expr else None,+ "n": n,+ "o": {"by": "ID", "ordering": "DESC"},+ }+++def decode_blob(blob: str | None) -> str:+ """Decodifica un ``Blob`` base64 de Caido a texto (best-effort). PURA.++ Los ``raw`` de request/response viajan como base64; esta ayuda los vuelve legibles para+ el OODA. Si no es base64 válido se devuelve tal cual (DATO NO confiable, no se revienta).+ """+ if not blob:+ return ""+ try:+ return base64.b64decode(blob).decode("utf-8", errors="replace")+ except Exception: # noqa: BLE001 - dato no confiable; best-effort+ return blob+++# --- Orquestadores ergonómicos (I/O): enviar por Replay / buscar historial --------------+++_STALE_RE = re.compile(+ r"connection to the database|no project|project not|not selected", re.I+)+++def _graphql_reauth(+ query: str,+ variables: dict[str, Any] | None,+ session: dict[str, Any],+ url: str | None,+ timeout: int,+) -> tuple[dict[str, Any], dict[str, Any]]:+ """``graphql`` con la sesión cacheada y UN reintento si ésta quedó obsoleta.++ Si Caido se recrea (volumen nuevo -> secretos nuevos) o el proyecto temporal desaparece,+ el token/proyecto cacheados dejan de valer y TODAS las llamadas fallarían hasta reiniciar+ kali-mcp (reproducido en vivo). Ante ``unauthenticated``/``graphql_error`` se renueva la+ sesión (``force=True``) y se repite UNA vez. Sólo se usa en etapas SIN efecto lateral sobre+ el objetivo (crear sesión de Replay, consultar historial); nunca tras enviar tráfico, para+ no reenviar. Devuelve ``(resultado, sesión_vigente)``.+ """+ out = graphql(query, variables, url=url, token=session["token"], timeout=timeout)+ # Se renueva ante rechazo de auth, o ante el error interno de "sin proyecto/BD" (proyecto+ # temporal desaparecido). Un graphql_error LEGÍTIMO (HTTPQL malo, input inválido) NO debe+ # forzar un login de invitado nuevo en cada llamada.+ stale_project = out["status"] == "graphql_error" and bool(+ _STALE_RE.search(json.dumps(out.get("errors") or []))+ )+ if out["status"] != "unauthenticated" and not stale_project:+ return out, session+ fresh = ensure_session(url=url, timeout=timeout, force=True)+ if fresh["status"] != "ok":+ return (+ out,+ session,+ ) # no se pudo renovar: devuelve el error original, informativo+ again = graphql(query, variables, url=url, token=fresh["token"], timeout=timeout)+ return again, fresh+++def _latest_request_id(token: str, url: str | None, timeout: int) -> int | None:+ """Último id de petición del historial: 0 si está vacío, ``None`` si la consulta FALLA.++ Línea base para correlacionar la respuesta de un Replay: sólo se aceptan entradas con id+ MAYOR, así una respuesta antigua de la misma URL nunca se confunde con la nueva.+ """+ out = graphql(+ HISTORY_QUERY,+ build_history_vars("", limit=1),+ url=url,+ token=token,+ timeout=timeout,+ )+ if out["status"] != "ok":+ return None+ edges = ((out.get("data") or {}).get("requests") or {}).get("edges") or []+ try:+ return max(+ (int((e.get("node") or {}).get("id") or 0) for e in edges), default=0+ )+ except (TypeError, ValueError):+ return None+++def _fetch_response_raw(+ request_id: Any, token: str, url: str | None, timeout: int, max_bytes: int+) -> tuple[str, bool]:+ """Raw (cabeceras + cuerpo) de la respuesta, decodificado y acotado a ``max_bytes``.++ Best-effort: si la consulta falla devuelve ``("", False)`` (el resto del resultado ya es+ válido). DATO NO confiable: se transporta verbatim (sólo se decodifica y se corta).+ """+ out = graphql(+ REQUEST_RAW_QUERY,+ {"id": str(request_id)},+ url=url,+ token=token,+ timeout=timeout,+ )+ if out["status"] != "ok":+ return "", False+ resp = ((out.get("data") or {}).get("request") or {}).get("response") or {}+ text = decode_blob(resp.get("raw"))+ limit = max(0, int(max_bytes))+ encoded = text.encode("utf-8")+ if len(encoded) <= limit:+ return text, False+ return encoded[:limit].decode("utf-8", errors="ignore"), True+++def send_request(+ url_target: str,+ method: str = "GET",+ headers: dict[str, str] | None = None,+ body: str = "",+ *,+ url: str | None = None,+ timeout: int = DEFAULT_TIMEOUT_S,+ max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,+) -> dict[str, Any]:+ """Envía una petición al objetivo POR el Replay de Caido y DEVUELVE su respuesta.++ Flujo REAL (verificado en vivo): ``ensure_session`` (token invitado/entorno + proyecto)+ -> ``createReplaySession`` con la petición cruda (base64) y el destino -> ``startReplayTask``+ -> SONDEA el historial hasta que aparece la respuesta correlacionada por host/puerto/path.+ El tráfico queda en el proxy de Caido (reproducible, buscable por ``search_history``).++ Returns en éxito ``{'status':'done','session_id':..,'request':{...},'response':{status_code,+ length,roundtrip_ms,raw}}``; o el dict de error de la etapa que falle+ (``unauthenticated``/``unreachable``/``graphql_error``/``failed``); o ``timeout`` si la+ respuesta no llega dentro del polling.+ """+ try:+ target = split_target_url(url_target)+ raw_request = build_raw_request(+ method,+ target["path"],+ target["host"],+ headers=headers or {},+ body=body or "",+ host_header=host_header_value(+ target["host"], target["port"], target["is_tls"]+ ),+ )+ variables = build_replay_input(+ target["host"], target["port"], target["is_tls"], raw_request+ )+ except (+ CaidoError,+ UnicodeError,+ ) as exc: # entrada inválida: fail-closed, no se envía+ return {"status": "failed", "error": str(exc)}++ session = ensure_session(url=url, timeout=timeout)+ if session["status"] != "ok":+ return session+ # Etapa SIN efecto lateral: si la sesión cacheada está obsoleta, se renueva y repite.+ created, session = _graphql_reauth(+ CREATE_REPLAY_SESSION, variables, session, url, timeout+ )+ token = session["token"]+ if created["status"] != "ok":+ return created+ baseline_id = _latest_request_id(token, url, timeout)+ if baseline_id is None:+ # Sin línea base no se puede correlacionar con seguridad (aceptaría una respuesta+ # vieja como nueva). Fail-closed ANTES de enviar tráfico.+ return {+ "status": "failed",+ "error": "No se pudo leer el historial de Caido (línea base); no se envía.",+ }+ cs = (created.get("data") or {}).get("createReplaySession") or {}+ if not cs.get("session"):+ return {+ "status": "failed",+ "error": "createReplaySession no devolvió sesión: %s"+ % (cs.get("error") or "?"),+ }+ session_id = cs["session"]["id"]++ started = graphql(+ START_REPLAY_TASK, {"id": session_id}, url=url, token=token, timeout=timeout+ )+ if started["status"] != "ok":+ return started++ # La respuesta es asíncrona: sondea el historial por host/puerto/path con respuesta.+ hv = build_history_vars("", limit=20)+ for _ in range(REPLAY_POLL_TRIES):+ time.sleep(REPLAY_POLL_INTERVAL_S)+ hist = graphql(HISTORY_QUERY, hv, url=url, token=token, timeout=timeout)+ if hist["status"] != "ok":+ return hist+ edges = ((hist.get("data") or {}).get("requests") or {}).get("edges") or []+ for e in edges:+ n = e.get("node") or {}+ resp = n.get("response")+ try:+ is_new = int(n.get("id") or 0) > baseline_id+ except (TypeError, ValueError):+ is_new = False+ if (+ resp+ and is_new+ and (n.get("method") or "").upper() == (method or "GET").strip().upper()+ and n.get("host") == target["host"]+ and int(n.get("port") or 0) == int(target["port"])+ and (n.get("path") or "").split("?")[0] == target["path"].split("?")[0]+ ):+ raw_text, truncated = _fetch_response_raw(+ n.get("id"), token, url, timeout, max_response_bytes+ )+ return {+ "status": "done",+ "session_id": session_id,+ "request": {+ "id": n.get("id"),+ "method": n.get("method"),+ "host": n.get("host"),+ "port": n.get("port"),+ "path": n.get("path"),+ "is_tls": n.get("isTls"),+ },+ "response": {+ "id": resp.get("id"),+ "status_code": resp.get("statusCode"),+ "length": resp.get("length"),+ "roundtrip_ms": resp.get("roundtripTime"),+ "raw": raw_text,+ "raw_truncated": truncated,+ },+ }+ return {+ "status": "timeout",+ "session_id": session_id,+ "error": (+ "La respuesta de Replay no apareció en el historial tras "+ f"{REPLAY_POLL_TRIES * REPLAY_POLL_INTERVAL_S:.0f}s. Consulta con caido_history."+ ),+ }+++def search_history(+ httpql: str = "",+ limit: int = 50,+ *,+ url: str | None = None,+ timeout: int = DEFAULT_TIMEOUT_S,+) -> dict[str, Any]:+ """Busca en el historial de tráfico de Caido por HTTPQL. Devuelve estado uniforme.++ ``ensure_session`` (token + proyecto) -> query ``requests`` filtrada. DATO NO confiable:+ los nodos se transportan verbatim. Returns ``{'status':'done','count':n,'entries':[...]}``+ en éxito, o el dict de error de la etapa que falle.+ """+ session = ensure_session(url=url, timeout=timeout)+ if session["status"] != "ok":+ return session+ out, session = _graphql_reauth(+ HISTORY_QUERY,+ build_history_vars(httpql=httpql, limit=limit),+ session,+ url,+ timeout,+ )+ if out["status"] != "ok":+ return out+ conn = (out.get("data") or {}).get("requests") or {}+ entries = [e.get("node") for e in (conn.get("edges") or []) if e.get("node")]+ return {+ "status": "done",+ "count": (conn.get("count") or {}).get("value"),+ "entries": entries,+ }+++# Con scope activo `caido_graphql` no puede validar el destino de una query opaca, así que+# rechaza los documentos que ENVÍAN tráfico y remite a `caido_request` (que sí pasa por el+# scope-guard). En Caido enviar tráfico es SIEMPRE una mutation (Replay/Automate/workflows/+# intercept/plugins), así que las queries de lectura nunca se tocan (sin falsos positivos por+# mencionar `connectionInfo` o `automate` en un select). Dentro de una mutation se rechaza por+# VERBOS de envío (substring, no nombres exactos), para cubrir también campos que Caido añada o+# renombre en otra release. Sigue siendo una heurística (no una prueba): falla del lado seguro+# con las mutaciones de aspecto "ejecutable" y puede dejar pasar un campo de envío con un+# nombre sin ninguno de estos verbos; está documentado en docs/caido.md.+_MUTATION_RE = re.compile(r"\bmutation\b", re.IGNORECASE)+_SENDING_RE = re.compile(+ r"start|send|run|forward|replay|automate|connect|execute|fire|trigger|invoke|test|"+ r"workflow|plugin|pipeline|intercept",+ re.IGNORECASE,+)+++def graphql_sends_traffic(query: str) -> bool:+ """¿El documento GraphQL es una mutation que parece enviar tráfico? PURA (heurística)."""+ doc = query or ""+ return bool(_MUTATION_RE.search(doc) and _SENDING_RE.search(doc))diff --git a/docker/kali/kali_mcp_server.py b/docker/kali/kali_mcp_server.pyindex ce6b051..59f7139 100644--- a/docker/kali/kali_mcp_server.py+++ b/docker/kali/kali_mcp_server.py@@ -82,6 +82,16 @@ import finding_store# (como shell_exec/finding_store) para cubrirse con tests sin el SDK.import scope_guard+# Cliente de la API GraphQL de Caido (STDLIB PURA, sin `mcp`/`requests`; HTTP por urllib):+# canal del agente hacia Caido (proxy + Replay + HTTPQL + scope + workflows). La pieza+# central es un passthrough genérico (`graphql`) que alcanza TODA la superficie del esquema+# público —robusto frente a que Caido lo cambie cada release—; encima, helpers ergonómicos+# para enviar por Replay y buscar el historial por HTTPQL. Las tools `caido_graphql`/+# `caido_request`/`caido_history` son capas finas sobre él. Vive en módulo aparte (como+# scope_guard/dnsdumpster_client) para cubrirse con tests sin el SDK. "No se finge": sin+# token o con Caido inalcanzable, devuelve un estado claro y `server_info` lo refleja.+import caido_client+# Plano de DATOS, STDLIB PURA (sin `mcp`/`anyio`): servidor HTTP que SIRVE los artefactos# staged por stream. (El staging/finalización vive en `collector_runner`/`prowler_artifact`,# que `collector_runner` importa.)@@ -184,6 +194,13 @@ DNS_RECON_TOOL_NAME = "dns_recon"# sin error). Cada binario es opcional: el que no esté se omite y se anota en `skipped`.WEBTECH_SCAN_TOOL_NAME = "webtech_scan"+# Tools de Caido (el toolkit web: proxy + Replay + HTTPQL + scope + workflows). El+# passthrough genérico da acceso a TODO el esquema público; las otras dos son ergonomía+# sobre los caminos calientes (enviar por Replay con gate de scope; buscar el historial).+CAIDO_GRAPHQL_TOOL_NAME = "caido_graphql"+CAIDO_REQUEST_TOOL_NAME = "caido_request"+CAIDO_HISTORY_TOOL_NAME = "caido_history"+# El endpoint MCP se monta en la raíz para que KALI_MCP_URL=http://kali:8900# (sin path) funcione tal cual con el cliente (streamable-HTTP del SDK oficial).mcp = FastMCP("kali-mcp", host=HOST, port=PORT, streamable_http_path="/")@@ -229,6 +246,17 @@ def server_info() -> dict[str, Any]:"webanalyze": shutil.which(webtech.WEBANALYZE_BIN) is not None,"wpscan": shutil.which(webtech.WPSCAN_BIN) is not None,}+ # Estado REAL de Caido SIN llamarlo (chequeo seguro/no intrusivo): sólo refleja la+ # configuración, no la alcanzabilidad (eso se comprueba al invocar una tool). Hay DOS+ # orígenes de credencial: un token del operador por entorno (`token_present`) o el login de+ # invitado headless (`guest_login`, activo por defecto contra un Caido con --allow-guests).+ # Con `token_present` False y `guest_login` True las tools FUNCIONAN igualmente; sin+ # ninguno de los dos devuelven `unauthenticated` (no se finge).+ caido_status = {+ "url": caido_client.resolve_url_safe(),+ "token_present": caido_client.token_present(),+ "guest_login": caido_client.ALLOW_GUEST,+ }return {"server": "kali-mcp","machine": os.uname().machine,@@ -246,6 +274,7 @@ def server_info() -> dict[str, Any]:# Plugin observability block (closed schema) read from the `load_plugins` report.# Empty and coherent if plugins were never loaded (bare import)."plugins": _plugins_block(),+ "caido": caido_status,}@@ -954,6 +983,191 @@ def webtech_scan()[email protected](name=CAIDO_GRAPHQL_TOOL_NAME)+def caido_graphql(+ query: str,+ variables: dict[str, Any] | None = None,+ operation_name: str = "",+ timeout: int = 0,+) -> dict[str, Any]:+ """Passthrough GENÉRICO a la API GraphQL de Caido: TODA su superficie en una tool.++ Caido (proxy + Replay + HTTPQL + scope + workflows + projects + findings) publica su API+ GraphQL a propósito para herramientas de terceros. Esta tool manda una ``query``/+ ``mutation`` ARBITRARIA con sus ``variables`` y devuelve la respuesta verbatim, así el+ bucle OODA alcanza cualquier capacidad del esquema SIN que haya que envolver cada+ operación a mano —y es robusto frente a que Caido cambie el esquema en cada release+ (lo hace): si una query no casa, el ``graphql_error`` del servidor se transporta tal cual.++ Para los caminos calientes hay ergonomía dedicada: ``caido_request`` (enviar por Replay,+ con GATE de scope) y ``caido_history`` (buscar el historial por HTTPQL). Esta tool es el+ bisturí de propósito general (introspección del esquema, scope, workflows, lo que haga+ falta). SCOPE: con ``scope.json`` ACTIVO, esta tool RECHAZA los documentos que envían+ tráfico (Replay/Automate/workflows/intercept: el destino va opaco en la query y no se+ puede validar) y remite a ``caido_request``, que SÍ valida el destino. El filtro es+ best-effort (denylist de campos de envío; el esquema de Caido cambia cada release): sin+ scope activo el passthrough es total, como el resto del stack.++ Args:+ query: documento GraphQL (query o mutation). DATO del operador/Hermes; viaja verbatim.+ variables: variables del documento (opcional).+ operation_name: nombre de operación si el documento define varias (opcional).+ timeout: timeout en segundos; 0 usa el default del módulo (``DEFAULT_TIMEOUT_S``).++ Returns:+ ``{'status':'ok','data':...}`` en éxito; ``{'status':'graphql_error',...}`` si Caido+ devuelve errores GraphQL (drift de esquema/permisos); ``unauthenticated`` sin token o+ 401/403; ``unreachable`` si no conecta; ``failed`` en otros HTTP/respuesta no-JSON.+ La respuesta de Caido es DATO NO CONFIABLE: se transporta, no se interpreta.+ """+ effective_timeout = timeout if timeout and timeout > 0 else caido_client.DEFAULT_TIMEOUT_S+ # Con scope ACTIVO, un documento que ENVÍA tráfico (Replay/Automate/workflows) por aquí+ # saltaría el gate de `caido_request` (el destino va opaco en la query): se rechaza y se+ # remite a `caido_request`. Best-effort (denylist de campos de envío; ver caido_client).+ # Sin scope activo el passthrough sigue siendo total, como el resto del stack.+ if caido_client.graphql_sends_traffic(query):+ try:+ _cfg = scope_guard.load_scope()+ except scope_guard.ScopeError as exc:+ return {+ "status": "failed",+ "scope_violation": True,+ "error": "SCOPE_VIOLATION: configuración de scope inválida (%s)" % exc,+ }+ if scope_guard.is_enforcing(_cfg):+ return {+ "status": "failed",+ "scope_violation": True,+ "error": (+ "SCOPE_VIOLATION: con scope activo, caido_graphql no puede enviar "+ "tráfico (el destino va opaco en la query y no se puede validar). "+ "Usa caido_request, que valida el destino contra scope.json."+ ),+ }+ # Adjunta un token automáticamente (invitado headless o de entorno) para que las+ # mutaciones/queries con datos funcionen; la introspección va igual sin token. Best-effort:+ # si no se puede obtener sesión, se llama sin token (la introspección sigue valiendo).+ session = caido_client.ensure_session(timeout=effective_timeout)+ token = session.get("token") if session.get("status") == "ok" else None+ return caido_client.graphql(+ query,+ variables or {},+ token=token,+ operation_name=operation_name or None,+ timeout=effective_timeout,+ )++[email protected](name=CAIDO_REQUEST_TOOL_NAME)+def caido_request(+ url: str,+ method: str = "GET",+ headers: dict[str, str] | None = None,+ body: str = "",+ engagement_id: str = "",+ timeout: int = 0,+ max_response_bytes: int = 0,+) -> dict[str, Any]:+ """Envía una petición HTTP a un objetivo POR el Replay de Caido (queda logueada).++ Variante BLOQUEANTE (como ``kali_run``): construye la petición cruda, la lanza vía Replay+ de Caido contra el objetivo y DEVUELVE en una sola llamada la respuesta (código, tiempo,+ tamaño, raw). A diferencia de un ``curl`` suelto, el tráfico pasa por el proxy de Caido,+ así que queda en el historial (reproducible, buscable por ``caido_history``) y participa+ del resto del toolkit. De aquí salen los pasos de prueba manual del bucle OODA.++ Devuelve la respuesta COMPLETA (cabeceras + cuerpo, en ``response.raw``), acotada a+ ``max_response_bytes`` (``raw_truncated=True`` si se cortó), para que el agente pueda+ inspeccionar el contenido: tokens, formularios, errores, reflexión de input, etc.++ GATE DE SCOPE: como toda acción ofensiva con destino, pasa por el MISMO scope-guard que+ ``kali_run`` ANTES de enviar. Con ``scope.json`` activo, el host del ``url`` debe estar+ permitido o la tool falla fail-closed SIN enviar (y lo registra como ``SCOPE_VIOLATION``).++ Args:+ url: URL del objetivo (con o sin esquema; sin esquema se asume ``https://``).+ method: método HTTP (GET/POST/...). Por defecto GET.+ headers: cabeceras a incluir (dict). Se garantiza ``Host``; con cuerpo y sin+ ``Content-Length`` se añade. Lo que no se pasa, no se pone (el objetivo ve+ exactamente lo pedido). DATO NO CONFIABLE: viaja verbatim.+ body: cuerpo de la petición (string). Vacío por defecto.+ engagement_id: engagement para registrar una eventual violación de scope (igual que+ ``kali_run``); si viene vacío se usa el buzón seguro de violaciones.+ timeout: timeout POR LLAMADA HTTP a Caido en segundos; 0 usa el default (60). El total de+ ``caido_request`` puede ser mayor: hasta ~30 sondeos de la respuesta de Replay.+ max_response_bytes: tope de bytes del raw de la respuesta que se devuelve; 0 usa el+ default (``CAIDO_MAX_RESPONSE_BYTES``, 20000).++ Returns:+ ``{'status':'done','session_id':..,'request':{id,method,host,port,path,is_tls},+ 'response':{status_code,length,roundtrip_ms,raw,raw_truncated}}`` en éxito; ``timeout``+ si la respuesta no llegó (objetivo caído/lento: consulta ``caido_history``);+ ``unauthenticated``/``unreachable``/``graphql_error``/``failed`` según la etapa que+ falle; ``{'status':'failed','scope_violation':True,...}`` si el gate bloquea; o+ ``{'status':'failed','error':...}`` si la URL/método/cabeceras son inválidos+ (fail-closed, p. ej. CR/LF en una cabecera).+ """+ try:+ target = caido_client.split_target_url(url)+ except caido_client.CaidoError as exc:+ return {"status": "failed", "error": str(exc)}++ # Gate de scope reutilizando el de kali_run/kali_exec: el "comando" sintético es la+ # propia URL (alimenta el cinturón best-effort) y el destino declarado es esquema://host:+ # puerto COMPLETO. Pasar sólo el host perdería el puerto y el guard "permite por host" un+ # target sin puerto, saltándose `ports` del scope (agujero detectado en la demo en vivo).+ declared = caido_client.scope_target(target)+ # El "comando" sintético lleva SÓLO el destino normalizado (no la URL cruda): así un IP en+ # la query string (`?next=10.9.9.9`) no dispara falsos bloqueos del cinturón best-effort.+ scope_error = _scope_gate(f"caido_request {declared}", [declared], engagement_id)+ if scope_error is not None:+ return scope_error++ effective_timeout = timeout if timeout and timeout > 0 else caido_client.DEFAULT_TIMEOUT_S+ return caido_client.send_request(+ url,+ method=method,+ headers=headers or {},+ body=body or "",+ timeout=effective_timeout,+ max_response_bytes=(+ max_response_bytes+ if max_response_bytes and max_response_bytes > 0+ else caido_client.DEFAULT_MAX_RESPONSE_BYTES+ ),+ )++[email protected](name=CAIDO_HISTORY_TOOL_NAME)+def caido_history(httpql: str = "", limit: int = 50, timeout: int = 0) -> dict[str, Any]:+ """Busca en el historial de tráfico de Caido (todo lo que pasó por el proxy) por HTTPQL.++ Operación de LECTURA (no toca objetivos; no pasa por el scope-guard): consulta el store+ de peticiones/respuestas capturadas y devuelve los nodos que casan con el filtro HTTPQL,+ con lo esencial (método, host, path, código, tiempo, tamaño, ids). Con esto el bucle OODA+ revisa lo que ya ocurrió (p. ej. todas las respuestas 500, o el tráfico hacia un host) en+ vez de reconstruirlo. El ``raw`` completo no viene por defecto (puede ser enorme); se pide+ por id con ``caido_graphql`` si hace falta.++ Args:+ httpql: expresión HTTPQL de Caido (p. ej. ``resp.code.eq:200`` o+ ``req.host.cont:"juice-shop"``). Vacío trae los últimos ``limit``. DATO NO+ CONFIABLE: viaja verbatim; Caido lo parsea.+ limit: nº máximo de entradas (1..1000; 50 por defecto).+ timeout: timeout POR LLAMADA HTTP a Caido en segundos; 0 usa el default (60). El total de+ ``caido_request`` puede ser mayor: hasta ~30 sondeos de la respuesta de Replay.++ Returns:+ ``{'status':'done','count':n,'entries':[{id,method,host,port,path,isTls,length,+ createdAt,response:{id,statusCode,roundtripTime,length,createdAt}}]}`` en éxito;+ ``unauthenticated``/``unreachable``/``graphql_error``/``failed`` según la etapa que+ falle. ``count`` es el total que casa con el filtro; ``entries`` está acotado por+ ``limit``.+ """+ effective_timeout = timeout if timeout and timeout > 0 else caido_client.DEFAULT_TIMEOUT_S+ return caido_client.search_history(httpql=httpql, limit=limit, timeout=effective_timeout)++def _start_artifacts_http() -> None:"""Arranca el servidor HTTP de artefactos (plano de DATOS) en un hilo demonio.diff --git a/docker/kali/tests/test_caido_client.py b/docker/kali/tests/test_caido_client.pynew file mode 100644index 0000000..7363792--- /dev/null+++ b/docker/kali/tests/test_caido_client.py@@ -0,0 +1,909 @@+"""Tests stdlib-only del cliente de Caido (`docker/kali/caido_client.py`).++No importan `mcp`/`anyio` ni salen a la red (sólo algún test abre un socket en loopback): cubren SÓLO las funciones PURAS (builders de+payload, normalización de respuesta, parsing de URL, resolución de endpoint/token) y la+mecánica fail-closed de `graphql` cuando falta el token (ahí no hay I/O). El patrón calca+``tests/test_scope_guard.py`` / ``tests/test_finding_store.py``.++El orquestador `graphql` con red real se valida aparte, EN VIVO, contra un Caido + Juice+Shop levantados en local (la verificación end-to-end que exige "no se finge"); aquí sólo se+cubre su rama sin-token (sin red) y la clasificación de respuestas ya parseadas.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++# El módulo bajo prueba vive en docker/kali/ (el servidor MCP NO se importa: arrastra+# `mcp`/`anyio`). Se añade el padre al path explícitamente.+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++import caido_client # noqa: E402++# --- resolve_url / resolve_url_safe ----------------------------------------------------+++def test_resolve_url_normaliza_y_quita_barra_final():+ assert caido_client.resolve_url("http://caido:8080/") == "http://caido:8080"+++def test_resolve_url_anade_esquema_por_defecto():+ assert caido_client.resolve_url("caido:8080") == "http://caido:8080"+++def test_resolve_url_vacia_lanza(monkeypatch):+ monkeypatch.setattr(caido_client, "DEFAULT_URL", "")+ with pytest.raises(caido_client.CaidoError):+ caido_client.resolve_url("")+++def test_resolve_url_safe_no_lanza(monkeypatch):+ monkeypatch.setattr(caido_client, "DEFAULT_URL", "")+ assert caido_client.resolve_url_safe("") == ""+++def test_graphql_endpoint_concatena_path():+ assert (+ caido_client.graphql_endpoint("http://caido:8080")+ == "http://caido:8080" + caido_client.GRAPHQL_PATH+ )+++# --- env_token / token_present ----------------------------------------------------------+++def test_env_token_prioriza_pat_sobre_access_token(monkeypatch):+ monkeypatch.setenv(caido_client.ALT_TOKEN_ENV, "access-tok")+ monkeypatch.setenv(caido_client.TOKEN_ENV, "pat-tok")+ assert caido_client.env_token() == "pat-tok"+++def test_env_token_cae_a_access_token(monkeypatch):+ monkeypatch.delenv(caido_client.TOKEN_ENV, raising=False)+ monkeypatch.setenv(caido_client.ALT_TOKEN_ENV, "access-tok")+ assert caido_client.env_token() == "access-tok"+++def test_token_present_falso_sin_token(monkeypatch):+ monkeypatch.delenv(caido_client.TOKEN_ENV, raising=False)+ monkeypatch.delenv(caido_client.ALT_TOKEN_ENV, raising=False)+ assert caido_client.token_present() is False+++# --- ensure_session (transporte simulado; sin red) ---------------------------------------++[email protected](autouse=True)+def _limpia_sesion():+ caido_client.reset_session()+ yield+ caido_client.reset_session()+++def _fake_graphql(responses):+ """Devuelve un sustituto de ``graphql`` que responde según el documento enviado."""+ calls = []++ def fake(query, variables=None, **kw):+ calls.append((query, variables, kw.get("token")))+ for needle, resp in responses.items():+ if needle in query:+ return resp+ raise AssertionError("query inesperada: " + query[:60])++ fake.calls = calls+ return fake+++def test_ensure_session_invitado_crea_proyecto(monkeypatch):+ monkeypatch.delenv(caido_client.TOKEN_ENV, raising=False)+ monkeypatch.delenv(caido_client.ALT_TOKEN_ENV, raising=False)+ fake = _fake_graphql(+ {+ "loginAsGuest": {+ "status": "ok",+ "data": {"loginAsGuest": {"token": {"accessToken": "tok.guest"}}},+ },+ "projects{": {"status": "ok", "data": {"projects": []}},+ "createProject": {+ "status": "ok",+ "data": {"createProject": {"project": {"id": "p1"}}},+ },+ "selectProject": {"status": "ok", "data": {"selectProject": {}}},+ }+ )+ monkeypatch.setattr(caido_client, "graphql", fake)+ out = caido_client.ensure_session()+ assert out == {"status": "ok", "token": "tok.guest", "project_id": "p1"}+++def test_ensure_session_reutiliza_proyecto_ready_y_cachea(monkeypatch):+ monkeypatch.setenv(caido_client.TOKEN_ENV, "pat")+ fake = _fake_graphql(+ {+ "projects{": {+ "status": "ok",+ "data": {"projects": [{"id": "p9", "name": "x", "status": "READY"}]},+ },+ "selectProject": {"status": "ok", "data": {"selectProject": {}}},+ }+ )+ monkeypatch.setattr(caido_client, "graphql", fake)+ first = caido_client.ensure_session()+ n_calls = len(fake.calls)+ second = caido_client.ensure_session()+ assert first["token"] == "pat" and first["project_id"] == "p9"+ assert second == first+ assert len(fake.calls) == n_calls # segunda llamada: caché, sin red+ # No crea proyecto si ya había uno.+ assert not any("createProject" in c[0] for c in fake.calls)+++def test_ensure_session_sin_token_e_invitado_desactivado(monkeypatch):+ monkeypatch.delenv(caido_client.TOKEN_ENV, raising=False)+ monkeypatch.delenv(caido_client.ALT_TOKEN_ENV, raising=False)+ monkeypatch.setattr(caido_client, "ALLOW_GUEST", False)+ out = caido_client.ensure_session()+ assert out["status"] == "unauthenticated"+++def test_ensure_session_invitado_rechazado(monkeypatch):+ monkeypatch.delenv(caido_client.TOKEN_ENV, raising=False)+ monkeypatch.delenv(caido_client.ALT_TOKEN_ENV, raising=False)+ fake = _fake_graphql(+ {+ "loginAsGuest": {+ "status": "ok",+ "data": {+ "loginAsGuest": {+ "token": None,+ "error": {"__typename": "PermissionDeniedUserError"},+ }+ },+ }+ }+ )+ monkeypatch.setattr(caido_client, "graphql", fake)+ out = caido_client.ensure_session()+ assert out["status"] == "unauthenticated"+ assert "--allow-guests" in out["error"]+++# --- normalize_graphql_response --------------------------------------------------------+++def test_normalize_ok_sin_errores():+ out = caido_client.normalize_graphql_response({"data": {"x": 1}})+ assert out == {"status": "ok", "data": {"x": 1}}+++def test_normalize_graphql_error_transporta_errores_verbatim():+ payload = {"data": None, "errors": [{"message": "Unknown field 'foo'"}]}+ out = caido_client.normalize_graphql_response(payload)+ assert out["status"] == "graphql_error"+ assert out["errors"] == payload["errors"]+ assert out["data"] is None+++def test_normalize_detecta_error_de_autorizacion():+ payload = {+ "data": None,+ "errors": [+ {+ "message": "Operation error",+ "extensions": {+ "CAIDO": {"reason": "INVALID_TOKEN", "code": "AUTHORIZATION"}+ },+ }+ ],+ }+ out = caido_client.normalize_graphql_response(payload)+ assert out["status"] == "unauthenticated"+ assert out["errors"] == payload["errors"]+++# --- split_target_url ------------------------------------------------------------------+++def test_split_url_https_por_defecto_sin_esquema():+ out = caido_client.split_target_url("juice-shop.local/rest/products")+ assert out == {+ "host": "juice-shop.local",+ "port": 443,+ "is_tls": True,+ "path": "/rest/products",+ }+++def test_split_url_http_con_puerto_explicito():+ out = caido_client.split_target_url("http://juice-shop:3000/")+ assert out["host"] == "juice-shop"+ assert out["port"] == 3000+ assert out["is_tls"] is False+ assert out["path"] == "/"+++def test_split_url_conserva_query():+ out = caido_client.split_target_url("http://h:3000/search?q=1&x=2")+ assert out["path"] == "/search?q=1&x=2"+++def test_split_url_sin_host_lanza():+ with pytest.raises(caido_client.CaidoError):+ caido_client.split_target_url("http:///solo-path")+++def test_split_url_vacia_lanza():+ with pytest.raises(caido_client.CaidoError):+ caido_client.split_target_url("")+++# --- build_raw_request -----------------------------------------------------------------+++def test_build_raw_request_get_minimo_inyecta_host_y_connection_close():+ raw = caido_client.build_raw_request("get", "/", "example.com")+ lines = raw.split("\r\n")+ assert lines[0] == "GET / HTTP/1.1"+ assert "Host: example.com" in lines+ assert "Connection: close" in lines+ assert raw.endswith("\r\n\r\n")+++def test_build_raw_request_normaliza_path_sin_barra():+ raw = caido_client.build_raw_request("GET", "rest/products", "h")+ assert raw.split("\r\n")[0] == "GET /rest/products HTTP/1.1"+++def test_build_raw_request_respeta_host_y_connection_explicitos():+ raw = caido_client.build_raw_request(+ "GET",+ "/",+ "ignorado",+ headers={"Host": "explicit.example", "connection": "keep-alive"},+ )+ assert "Host: explicit.example" in raw and "Host: ignorado" not in raw+ assert "connection: keep-alive" in raw and "Connection: close" not in raw+++def test_build_raw_request_content_length_cuenta_bytes():+ body = '{"user":"ñ"}'+ raw = caido_client.build_raw_request("POST", "/login", "h", body=body)+ assert f"Content-Length: {len(body.encode('utf-8'))}" in raw+ assert raw.endswith("\r\n\r\n" + body)+++def test_build_raw_request_respeta_content_length_explicito():+ raw = caido_client.build_raw_request(+ "POST", "/", "h", headers={"Content-Length": "0"}, body="xx"+ )+ assert raw.count("Content-Length") == 1+++# --- build_replay_input ----------------------------------------------------------------+++def test_build_replay_input_usa_isTLS_y_blob_base64():+ import base64++ raw = "GET / HTTP/1.1\r\nHost: h\r\n\r\n"+ out = caido_client.build_replay_input("h", 3000, False, raw)+ inp = out["i"]+ assert inp["kind"] == "HTTP"+ raw_src = inp["requestSource"]["raw"]+ assert raw_src["connectionInfo"] == {"host": "h", "port": 3000, "isTLS": False}+ assert base64.b64decode(raw_src["raw"]).decode() == raw+++def test_build_replay_input_host_vacio_lanza():+ with pytest.raises(caido_client.CaidoError):+ caido_client.build_replay_input("", 80, False, "x")++[email protected]("bad_port", [0, 65536, -1, "no-num"])+def test_build_replay_input_puerto_invalido_lanza(bad_port):+ with pytest.raises(caido_client.CaidoError):+ caido_client.build_replay_input("h", bad_port, False, "x")+++# --- build_history_vars ----------------------------------------------------------------+++def test_build_history_vars_con_filtro_usa_campo_code():+ out = caido_client.build_history_vars("resp.code.eq:200", limit=10)+ assert out["f"] == {"code": "resp.code.eq:200"}+ assert out["n"] == 10+ assert out["o"] == {"by": "ID", "ordering": "DESC"}+++def test_build_history_vars_sin_filtro_es_none():+ assert caido_client.build_history_vars("", limit=5)["f"] is None++[email protected]("raw_limit,expected", [(0, 1), (-5, 1), (99999, 1000)])+def test_build_history_vars_acota_limit(raw_limit, expected):+ assert caido_client.build_history_vars("", limit=raw_limit)["n"] == expected+++# --- decode_blob -----------------------------------------------------------------------+++def test_decode_blob_base64_y_tolerancia():+ import base64++ assert caido_client.decode_blob(base64.b64encode(b"hola").decode()) == "hola"+ assert caido_client.decode_blob(None) == ""+++# --- send_request (transporte simulado) ------------------------------------------------+++def test_send_request_flujo_completo_correlaciona_respuesta(monkeypatch):+ monkeypatch.setattr(caido_client, "REPLAY_POLL_INTERVAL_S", 0)+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ node = {+ "id": "7",+ "method": "GET",+ "host": "juice-shop",+ "port": 3000,+ "path": "/",+ "isTls": False,+ "response": {"id": "8", "statusCode": 200, "length": 10, "roundtripTime": 5},+ }+ fake = _fake_graphql(+ {+ "createReplaySession": {+ "status": "ok",+ "data": {"createReplaySession": {"session": {"id": "s1"}}},+ },+ "startReplayTask": {+ "status": "ok",+ "data": {"startReplayTask": {"task": {"id": "1"}}},+ },+ "requests(": {+ "status": "ok",+ "data": {"requests": {"edges": [{"node": node}]}},+ },+ "request(id": {+ "status": "ok",+ "data": {+ "request": {"response": {"raw": "SFRUUC8xLjEgMjAwIE9LDQoNCmhvbGE="}}+ },+ },+ }+ )+ # Historial realista: la consulta de línea base (1ª) lo ve vacío; el sondeo ya ve la nueva.+ history = iter(+ [+ {"status": "ok", "data": {"requests": {"edges": []}}},+ {"status": "ok", "data": {"requests": {"edges": [{"node": node}]}}},+ ]+ )+ base_fake = fake++ def fake_seq(query, variables=None, **kw):+ if "requests(" in query:+ base_fake.calls.append((query, variables, kw.get("token")))+ return next(history)+ return base_fake(query, variables, **kw)++ fake_seq.calls = base_fake.calls+ fake = fake_seq+ monkeypatch.setattr(caido_client, "graphql", fake)+ out = caido_client.send_request("http://juice-shop:3000/")+ assert out["status"] == "done"+ assert out["response"]["status_code"] == 200+ assert out["response"]["raw"].endswith("hola") # cuerpo devuelto, no sólo el código+ assert out["response"]["raw_truncated"] is False+ # El token de sesión se propaga a cada llamada.+ assert all(c[2] == "t" for c in fake.calls)+++def test_send_request_url_invalida_no_llama_a_caido(monkeypatch):+ def boom(*a, **k):+ raise AssertionError("no debe llamar a Caido")++ monkeypatch.setattr(caido_client, "graphql", boom)+ monkeypatch.setattr(caido_client, "ensure_session", boom)+ assert caido_client.send_request("")["status"] == "failed"+++def test_send_request_timeout_si_la_respuesta_no_llega(monkeypatch):+ monkeypatch.setattr(caido_client, "REPLAY_POLL_INTERVAL_S", 0)+ monkeypatch.setattr(caido_client, "REPLAY_POLL_TRIES", 2)+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ fake = _fake_graphql(+ {+ "createReplaySession": {+ "status": "ok",+ "data": {"createReplaySession": {"session": {"id": "s1"}}},+ },+ "startReplayTask": {+ "status": "ok",+ "data": {"startReplayTask": {"task": {"id": "1"}}},+ },+ "requests(": {"status": "ok", "data": {"requests": {"edges": []}}},+ }+ )+ monkeypatch.setattr(caido_client, "graphql", fake)+ assert caido_client.send_request("http://h:3000/x")["status"] == "timeout"+++def test_search_history_devuelve_entradas(monkeypatch):+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ fake = _fake_graphql(+ {+ "requests(": {+ "status": "ok",+ "data": {+ "requests": {+ "count": {"value": 1},+ "edges": [{"node": {"id": "1"}}],+ }+ },+ }+ }+ )+ monkeypatch.setattr(caido_client, "graphql", fake)+ out = caido_client.search_history("resp.code.eq:200", 5)+ assert out == {"status": "done", "count": 1, "entries": [{"id": "1"}]}+++def test_send_request_ignora_respuesta_antigua_de_la_misma_url(monkeypatch):+ """Una entrada previa (id <= línea base) con respuesta NO debe confundirse con la nueva."""+ monkeypatch.setattr(caido_client, "REPLAY_POLL_INTERVAL_S", 0)+ monkeypatch.setattr(caido_client, "REPLAY_POLL_TRIES", 3)+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ stale = {+ "id": "5",+ "method": "GET",+ "host": "h",+ "port": 80,+ "path": "/x",+ "isTls": False,+ "response": {"id": "5", "statusCode": 200, "length": 1, "roundtripTime": 1},+ }+ fake = _fake_graphql(+ {+ "createReplaySession": {+ "status": "ok",+ "data": {"createReplaySession": {"session": {"id": "s"}}},+ },+ "startReplayTask": {+ "status": "ok",+ "data": {"startReplayTask": {"task": {"id": "1"}}},+ },+ # El historial sólo contiene la entrada antigua (id 5) = la línea base.+ "requests(": {+ "status": "ok",+ "data": {"requests": {"edges": [{"node": stale}]}},+ },+ }+ )+ monkeypatch.setattr(caido_client, "graphql", fake)+ out = caido_client.send_request("http://h:80/x")+ assert out["status"] == "timeout" # nunca devuelve la respuesta obsoleta+++# --- renovación de sesión obsoleta (Caido recreado) -------------------------------------+++def _seq_graphql(monkeypatch, script):+ """``graphql`` falso que consume ``script`` (lista de (needle, respuesta)) en orden."""+ calls = []+ it = iter(script)++ def fake(query, variables=None, **kw):+ calls.append((query, kw.get("token")))+ needle, resp = next(it)+ assert needle in query, f"esperaba {needle!r}, llegó {query[:50]!r}"+ return resp++ monkeypatch.setattr(caido_client, "graphql", fake)+ return calls+++def test_search_history_renueva_sesion_obsoleta_y_reintenta_una_vez(monkeypatch):+ monkeypatch.delenv(caido_client.TOKEN_ENV, raising=False)+ monkeypatch.delenv(caido_client.ALT_TOKEN_ENV, raising=False)+ # Sesión cacheada con un token que Caido ya no reconoce.+ caido_client._SESSION.update(token="viejo", project_id="p-viejo")+ auth_err = {"status": "unauthenticated", "error": "INVALID_TOKEN"}+ calls = _seq_graphql(+ monkeypatch,+ [+ ("requests(", auth_err), # 1ª con token viejo -> rechazo+ (+ "loginAsGuest",+ {+ "status": "ok",+ "data": {"loginAsGuest": {"token": {"accessToken": "nuevo"}}},+ },+ ),+ (+ "projects{",+ {+ "status": "ok",+ "data": {"projects": [{"id": "p2", "status": "READY"}]},+ },+ ),+ ("selectProject", {"status": "ok", "data": {"selectProject": {}}}),+ (+ "requests(",+ {+ "status": "ok",+ "data": {"requests": {"count": {"value": 0}, "edges": []}},+ },+ ),+ ],+ )+ out = caido_client.search_history("")+ assert out["status"] == "done"+ assert calls[0][1] == "viejo" and calls[-1][1] == "nuevo"+++def test_send_request_no_reenvia_trafico_si_falla_tras_start(monkeypatch):+ """El reintento sólo cubre etapas sin efecto lateral: startReplayTask se llama UNA vez."""+ monkeypatch.setattr(caido_client, "REPLAY_POLL_INTERVAL_S", 0)+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ starts = []++ def fake(query, variables=None, **kw):+ if "createReplaySession" in query:+ return {+ "status": "ok",+ "data": {"createReplaySession": {"session": {"id": "s"}}},+ }+ if "startReplayTask" in query:+ starts.append(1)+ return {"status": "graphql_error", "errors": [{"message": "boom"}]}+ return {"status": "ok", "data": {"requests": {"edges": []}}}++ monkeypatch.setattr(caido_client, "graphql", fake)+ out = caido_client.send_request("http://h:80/x")+ assert out["status"] == "graphql_error"+ assert len(starts) == 1+++# --- revisión independiente: robustez y seguridad ---------------------------------------++import socket # noqa: E402+import threading # noqa: E402+++def _raw_server(payload: bytes):+ """Servidor TCP de un solo uso que responde ``payload`` crudo y cierra. -> (puerto, hilo)."""+ srv = socket.socket()+ srv.bind(("127.0.0.1", 0))+ srv.listen(1)++ def run():+ conn, _ = srv.accept()+ conn.recv(65536)+ if payload:+ conn.sendall(payload)+ conn.close()+ srv.close()++ th = threading.Thread(target=run, daemon=True)+ th.start()+ return srv.getsockname()[1], th+++ "payload",+ [+ b"",+ b"garbage not http\r\n\r\n",+ b"HTTP/1.1 200 OK\r\nContent-Length: 99\r\n\r\nshort",+ ],+)+def test_graphql_nunca_lanza_ante_respuestas_rotas(payload):+ port, _ = _raw_server(payload)+ out = caido_client.graphql("query{x}", url=f"http://127.0.0.1:{port}", timeout=3)+ assert out["status"] in ("unreachable", "failed")+++def test_graphql_nunca_lanza_con_url_invalida():+ assert caido_client.graphql("query{x}", url="http://exa mple:80")["status"] in (+ "failed",+ "unreachable",+ )+++ "bad", ["http://h:99999/", "http://h:abc/", "http://[::1/", "http://h:+80/"]+)+def test_split_url_invalida_lanza_caido_error_no_valueerror_pelado(bad):+ with pytest.raises(caido_client.CaidoError):+ caido_client.split_target_url(bad)+++def test_split_url_normaliza_punto_final_y_mayusculas():+ assert (+ caido_client.split_target_url("http://EXAMPLE.example./")["host"]+ == "example.example"+ )+++ "val,expected",+ [+ ("0", False),+ ("no", False),+ ("off", False),+ ("FALSE", False),+ ("basura", False),+ ("1", True),+ ("true", True),+ ("", True),+ ],+)+def test_allow_guest_falla_cerrado(monkeypatch, val, expected):+ import importlib++ monkeypatch.setenv("CAIDO_ALLOW_GUEST", val)+ try:+ assert importlib.reload(caido_client).ALLOW_GUEST is expected+ finally:+ monkeypatch.delenv("CAIDO_ALLOW_GUEST", raising=False)+ importlib.reload(caido_client)+++def test_env_numericos_vacios_o_basura_no_abortan_el_import(monkeypatch):+ import importlib++ monkeypatch.setenv("CAIDO_TIMEOUT", "")+ monkeypatch.setenv("CAIDO_REPLAY_POLL_TRIES", "x")+ monkeypatch.setenv("CAIDO_REPLAY_POLL_INTERVAL", "")+ try:+ mod = importlib.reload(caido_client)+ assert mod.DEFAULT_TIMEOUT_S == 60 and mod.REPLAY_POLL_TRIES == 30+ finally:+ monkeypatch.undo()+ importlib.reload(caido_client)+++ "kwargs",+ [+ {"method": "GET / HTTP/1.1\r\nHost: x\r\n\r\nPOST"},+ {"method": "GET", "headers": {"X": "a\r\n\r\nGET /x HTTP/1.1"}},+ {"method": "GET", "headers": {"X\r\nY": "a"}},+ {"method": "GET", "headers": {"Bad:Name": "a"}},+ {"method": "GET", "path": "/a\r\nHost: evil"},+ {"method": "GET", "path": "/a b"},+ ],+)+def test_build_raw_request_rechaza_inyeccion_crlf(kwargs):+ kwargs = {"path": "/", **kwargs}+ with pytest.raises(caido_client.CaidoError):+ caido_client.build_raw_request(host="h", **kwargs)+++def test_host_header_incluye_puerto_no_estandar_y_corchetes_ipv6():+ f = caido_client.host_header_value+ assert f("h", 80, False) == "h" and f("h", 443, True) == "h"+ assert f("h", 8080, False) == "h:8080"+ assert f("::1", 3000, False) == "[::1]:3000"+++def test_send_request_con_linea_base_fallida_no_envia_trafico(monkeypatch):+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ started = []++ def fake(query, variables=None, **kw):+ if "createReplaySession" in query:+ return {+ "status": "ok",+ "data": {"createReplaySession": {"session": {"id": "s"}}},+ }+ if "startReplayTask" in query:+ started.append(1)+ return {"status": "ok", "data": {}}+ return {"status": "unreachable", "error": "caído"} # la línea base falla++ monkeypatch.setattr(caido_client, "graphql", fake)+ out = caido_client.send_request("http://h:80/x")+ assert out["status"] == "failed" and not started+++def test_send_request_no_acepta_respuesta_de_otro_metodo(monkeypatch):+ monkeypatch.setattr(caido_client, "REPLAY_POLL_INTERVAL_S", 0)+ monkeypatch.setattr(caido_client, "REPLAY_POLL_TRIES", 2)+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ get_node = {+ "id": "9",+ "method": "GET",+ "host": "h",+ "port": 80,+ "path": "/x",+ "isTls": False,+ "response": {"id": "9", "statusCode": 200, "length": 1, "roundtripTime": 1},+ }+ seq = iter(+ [+ {"edges": []},+ {"edges": [{"node": get_node}]},+ {"edges": [{"node": get_node}]},+ ]+ )++ def fake(query, variables=None, **kw):+ if "createReplaySession" in query:+ return {+ "status": "ok",+ "data": {"createReplaySession": {"session": {"id": "s"}}},+ }+ if "startReplayTask" in query:+ return {"status": "ok", "data": {"startReplayTask": {"task": {"id": "1"}}}}+ return {"status": "ok", "data": {"requests": next(seq)}}++ monkeypatch.setattr(caido_client, "graphql", fake)+ assert (+ caido_client.send_request("http://h:80/x", method="POST")["status"] == "timeout"+ )+++def test_fetch_response_raw_trunca_al_tope(monkeypatch):+ import base64++ big = base64.b64encode(b"A" * 500).decode()+ monkeypatch.setattr(+ caido_client,+ "graphql",+ lambda *a, **k: {+ "status": "ok",+ "data": {"request": {"response": {"raw": big}}},+ },+ )+ text, truncated = caido_client._fetch_response_raw("1", "t", None, 5, 100)+ assert len(text) == 100 and truncated is True+++def test_reauth_no_se_dispara_con_graphql_error_legitimo(monkeypatch):+ calls = []++ def fake(query, variables=None, **kw):+ calls.append(query)+ return {+ "status": "graphql_error",+ "errors": [{"message": "HTTPQL syntax error"}],+ }++ monkeypatch.setattr(caido_client, "graphql", fake)+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: (_ for _ in ()).throw(AssertionError("no debe renovar sesión")),+ )+ out, _ = caido_client._graphql_reauth("q", {}, {"token": "t"}, None, 5)+ assert out["status"] == "graphql_error" and len(calls) == 1+++ "doc,expected",+ [+ ("mutation{ startReplayTask(sessionId:1){ task{id} } }", True),+ (+ "mutation($i:CreateReplaySessionInput!){ createReplaySession(input:$i){session{id}} }",+ True,+ ),+ ("mutation{ runActiveWorkflow(id:1){ __typename } }", True),+ ("query{ projects{ id name } }", False),+ ("query{ requests(first:1){ count{value} } }", False),+ ],+)+def test_graphql_sends_traffic(doc, expected):+ assert caido_client.graphql_sends_traffic(doc) is expected+++# --- revisión final: esquema, surrogates, IPv4-mapped, filtro de mutaciones -------------++[email protected]("bad", ["file:///etc/passwd", "ftp://caido:21", "gopher://x"])+def test_resolve_url_rechaza_esquemas_no_http(bad):+ with pytest.raises(caido_client.CaidoError):+ caido_client.resolve_url(bad)+++def test_graphql_con_caido_url_file_devuelve_failed_sin_leer_ficheros():+ out = caido_client.graphql("query{x}", url="file:///etc/passwd")+ assert out["status"] == "failed"++[email protected]("kw", [{"body": "\ud800"}, {"headers": {"X": "\ud800"}}])+def test_send_request_con_surrogate_suelto_devuelve_failed_sin_lanzar(monkeypatch, kw):+ def boom(*a, **k):+ raise AssertionError("no debe llegar a Caido")++ monkeypatch.setattr(caido_client, "graphql", boom)+ monkeypatch.setattr(caido_client, "ensure_session", boom)+ out = caido_client.send_request("http://example.com/", method="POST", **kw)+ assert out["status"] == "failed"+++ "url",+ [+ "http://[::ffff:169.254.169.254]/",+ "http://[::ffff:a9fe:a9fe]/",+ "http://[0:0:0:0:0:ffff:a9fe:a9fe]/",+ ],+)+def test_split_url_desmapea_ipv4_mapped_a_ipv4(url):+ assert caido_client.split_target_url(url)["host"] == "169.254.169.254"+++def test_split_url_ipv6_normal_se_conserva():+ assert (+ caido_client.split_target_url("http://[2001:db8::1]:8080/")["host"]+ == "2001:db8::1"+ )+++def test_caido_project_vacio_usa_el_nombre_por_defecto(monkeypatch):+ import importlib++ monkeypatch.setenv("CAIDO_PROJECT", "")+ try:+ assert importlib.reload(caido_client).PROJECT_NAME == "vulnerator"+ finally:+ monkeypatch.undo()+ importlib.reload(caido_client)+++ "doc,expected",+ [+ ("query{ requests(first:1){ count{value} } }", False),+ (+ "query{ x{ connectionInfo{ host } } }",+ False,+ ), # lectura que nombra connectionInfo+ ("query{ automateSessions{ id } }", False), # lectura: nunca se toca+ (+ "mutation{ sendRequest(x:1){ id } }",+ True,+ ), # nombre desconocido: lo cubren los verbos+ ("mutation{ runWorkflow(id:1){ ok } }", True),+ ("mutation{ testPlugin(id:1){ ok } }", True),+ ("mutation{ forwardInterceptMessage(id:1){ ok } }", True),+ ('mutation{ selectProject(id:"1"){ currentProject{ __typename } } }', False),+ ("mutation{ loginAsGuest{ token{ accessToken } } }", False),+ ('mutation{ createProject(input:{name:"x"}){ project{ id } } }', False),+ ],+)+def test_graphql_sends_traffic_solo_mutaciones_con_verbos_de_envio(doc, expected):+ assert caido_client.graphql_sends_traffic(doc) is expecteddiff --git a/docker/kali/tests/test_caido_scope.py b/docker/kali/tests/test_caido_scope.pynew file mode 100644index 0000000..741d56c--- /dev/null+++ b/docker/kali/tests/test_caido_scope.py@@ -0,0 +1,91 @@+"""Tests de la DECISIÓN de scope para el destino que declara ``caido_request`` (STDLIB PURA).++Ejercitan ``scope_guard`` con el MISMO destino que construye el servidor+(``caido_client.scope_target(split_target_url(url))``, ``esquema://host:puerto``). El+comportamiento de las tools completas (que un bloqueo no llegue a enviar tráfico) se prueba en+``test_caido_server.py``.++Regresión que fijan: una versión inicial declaraba sólo el HOST al gate; el puerto se perdía+y un target sin puerto se permitía "por host", saltándose ``ports`` del scope. Se detectó en+la verificación EN VIVO (petición a :9999 con ``ports:[3000]`` llegó a Caido).+"""++from __future__ import annotations++import sys+from pathlib import Path++_PARENT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(_PARENT))++import caido_client # noqa: E402+import scope_guard # noqa: E402++_SCOPE = {+ "enabled": True,+ "allow": [{"host": "juice-shop"}],+ "deny": [],+ "ports": [3000],+}+++def _config():+ return scope_guard.parse_scope(_SCOPE)+++def _declared(url: str) -> str:+ # La MISMA función que usa el servidor para declarar el destino al gate.+ return caido_client.scope_target(caido_client.split_target_url(url))+++def _allowed(url: str) -> bool:+ d = scope_guard.evaluate(_config(), [_declared(url)], f"caido_request {url}")+ return d.allowed+++def test_puerto_permitido_pasa():+ assert _allowed("http://juice-shop:3000/") is True+++def test_puerto_fuera_de_ports_se_bloquea():+ # La regresión: con sólo el host declarado esto pasaba.+ assert _allowed("http://juice-shop:9999/") is False+++def test_host_fuera_de_allow_se_bloquea():+ assert _allowed("http://otro-host:3000/") is False+++def test_el_host_solo_perderia_el_puerto():+ # Documenta POR QUÉ se declara esquema://host:puerto: sólo el host se permite por host.+ d = scope_guard.evaluate(_config(), ["juice-shop"], "caido_request x")+ assert d.allowed is True+++def _allowed_with(scope: dict, url: str) -> bool:+ cfg = scope_guard.parse_scope(scope)+ return scope_guard.evaluate(+ cfg, [_declared(url)], f"caido_request {_declared(url)}"+ ).allowed+++def test_ipv6_literal_dentro_de_cidr_pasa():+ scope = {"enabled": True, "allow": [{"cidr": "::1/128"}], "deny": []}+ assert _allowed_with(scope, "http://[::1]:3000/") is True+++def test_userinfo_no_engana_al_gate():+ # El destino real es attacker.example; "allowed" en el userinfo no cuenta.+ scope = {"enabled": True, "allow": [{"host": "juice-shop"}], "deny": []}+ assert _allowed_with(scope, "http://[email protected]:3000/") is False+++def test_punto_final_y_mayusculas_no_evaden_ni_bloquean():+ scope = {"enabled": True, "allow": [{"host": "juice-shop"}], "deny": []}+ assert _allowed_with(scope, "http://JUICE-SHOP.:3000/") is True+ assert _allowed_with(scope, "http://attacker.example.:3000/") is False+++def test_ip_en_query_string_no_causa_bloqueo_falso():+ scope = {"enabled": True, "allow": [{"host": "juice-shop"}], "deny": []}+ assert _allowed_with(scope, "http://juice-shop:3000/?next=10.9.9.9") is Truediff --git a/docker/kali/tests/test_caido_server.py b/docker/kali/tests/test_caido_server.pynew file mode 100644index 0000000..1b1bf29--- /dev/null+++ b/docker/kali/tests/test_caido_server.py@@ -0,0 +1,251 @@+"""Tests de COMPORTAMIENTO de las tools de Caido del servidor (sin red, sin Docker, sin `mcp`).++``kali_mcp_server`` exige el SDK ``mcp<2``; aquí se importa con un STUB mínimo de+``mcp.server.fastmcp.FastMCP`` (decorador identidad), de modo que las funciones ``caido_*`` se+ejecutan de verdad y se comprueba lo que importa: con ``scope.json`` activo ``caido_request`` NO+llega a enviar tráfico, ``caido_graphql`` rechaza mutaciones de envío, y ``server_info`` expone el+estado de Caido. ``caido_client.send_request``/``graphql`` se sustituyen por espías.+"""++from __future__ import annotations++import importlib.util+import json+import sys+import types+from pathlib import Path++import pytest++_PARENT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(_PARENT))++import caido_client # noqa: E402+++class _StubFastMCP:+ """Sustituto de FastMCP: ``@mcp.tool(...)``/``@mcp.tool()`` devuelven la función tal cual."""++ def __init__(self, *a, **k):+ self.tools = {}++ def tool(self, name=None, **k):+ def deco(fn):+ self.tools[name or fn.__name__] = fn+ return fn++ return deco++ def run(self, *a, **k): # pragma: no cover - no se arranca el servidor+ raise AssertionError("el servidor no debe arrancar en tests")+++def server(monkeypatch):+ """``kali_mcp_server`` importado con el SDK ``mcp`` sustituido por un stub (aislado)."""+ fastmcp = types.ModuleType("mcp.server.fastmcp")+ fastmcp.FastMCP = _StubFastMCP+ for name, mod in (+ ("mcp", types.ModuleType("mcp")),+ ("mcp.server", types.ModuleType("mcp.server")),+ ("mcp.server.fastmcp", fastmcp),+ ):+ monkeypatch.setitem(sys.modules, name, mod)+ spec = importlib.util.spec_from_file_location(+ "_kali_mcp_server_under_test", _PARENT / "kali_mcp_server.py"+ )+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ # Las violaciones de scope se loguean en /artifacts: se captura en vez de escribir a disco.+ violations = []+ monkeypatch.setattr(+ mod, "_log_scope_violation", lambda *a, **k: violations.append(a)+ )+ mod._violations = violations+ return mod+++def scope_on(tmp_path, monkeypatch):+ f = tmp_path / "scope.json"+ f.write_text(+ json.dumps(+ {+ "enabled": True,+ "allow": [{"host": "juice-shop"}],+ "deny": [],+ "ports": [3000],+ }+ )+ )+ monkeypatch.setenv("SCOPE_FILE", str(f))+ monkeypatch.delenv("SCOPE_ENFORCE", raising=False)+++def scope_off(tmp_path, monkeypatch):+ monkeypatch.setenv("SCOPE_FILE", str(tmp_path / "no-existe.json"))+++def spy(monkeypatch):+ calls = {"send": [], "graphql": []}++ def fake_send(url, **kw):+ calls["send"].append((url, kw))+ return {"status": "done", "response": {"status_code": 200}}++ def fake_graphql(query, variables=None, **kw):+ calls["graphql"].append(query)+ return {"status": "ok", "data": {}}++ monkeypatch.setattr(caido_client, "send_request", fake_send)+ monkeypatch.setattr(caido_client, "graphql", fake_graphql)+ monkeypatch.setattr(+ caido_client,+ "ensure_session",+ lambda **kw: {"status": "ok", "token": "t", "project_id": "p"},+ )+ return calls+++# --- caido_request ----------------------------------------------------------------------+++ "url",+ [+ "http://example.net/", # host fuera de allow+ "http://juice-shop:9999/", # puerto fuera de ports+ "http://[email protected]:3000/", # userinfo: el destino real es attacker.example+ "http://attacker.example./", # punto final+ ],+)+def test_caido_request_fuera_de_scope_no_envia_trafico(server, scope_on, spy, url):+ out = server.caido_request(url, engagement_id="e1")+ assert out["status"] == "failed" and out["scope_violation"] is True+ assert spy["send"] == [] # NUNCA se llamó a send_request+ assert server._violations, "la violación debe registrarse como evidencia"+++def test_caido_request_en_scope_envia_y_declara_el_destino_validado(+ server, scope_on, spy+):+ out = server.caido_request(+ "http://juice-shop:3000/rest/products/search?q=a", method="GET"+ )+ assert out["status"] == "done"+ assert len(spy["send"]) == 1 and spy["send"][0][0].startswith(+ "http://juice-shop:3000/"+ )+++def test_caido_request_ipv4_mapped_ipv6_no_evade_el_deny(+ server, tmp_path, monkeypatch, spy+):+ f = tmp_path / "s.json"+ f.write_text(+ json.dumps(+ {+ "enabled": True,+ "allow": [{"cidr": "0.0.0.0/0"}, {"cidr": "::/0"}],+ "deny": [{"cidr": "169.254.0.0/16"}],+ }+ )+ )+ monkeypatch.setenv("SCOPE_FILE", str(f))+ for url in (+ "http://169.254.169.254/",+ "http://[::ffff:169.254.169.254]/",+ "http://[::ffff:a9fe:a9fe]/",+ ):+ out = server.caido_request(url)+ assert out.get("scope_violation") is True, url+ assert spy["send"] == []+++def test_caido_request_url_invalida_devuelve_failed_sin_lanzar(server, scope_off, spy):+ for bad in ("http://h:99999/", "http://[::1/", ""):+ assert server.caido_request(bad)["status"] == "failed"+ assert spy["send"] == []+++def test_caido_request_sin_scope_pasa_a_send_request(server, scope_off, spy):+ assert server.caido_request("http://cualquiera.example/")["status"] == "done"+ assert len(spy["send"]) == 1+++# --- caido_graphql ----------------------------------------------------------------------++_SEND = 'mutation{ startReplayTask(sessionId:"1"){ task{id} } }'+++ "doc",+ [+ _SEND,+ "mutation{ sendRequest(x:1){id} }", # nombre desconocido: lo cubren los verbos+ "mutation{ runWorkflow(id:1){ok} }",+ "mutation($i:X!){ createReplaySession(input:$i){ session{id} } }",+ ],+)+def test_caido_graphql_rechaza_mutaciones_de_envio_con_scope_activo(+ server, scope_on, spy, doc+):+ out = server.caido_graphql(doc)+ assert out["status"] == "failed" and out["scope_violation"] is True+ assert "caido_request" in out["error"]+ assert spy["graphql"] == []+++def test_caido_graphql_permite_lecturas_y_mutaciones_inocuas_con_scope_activo(+ server, scope_on, spy+):+ for doc in (+ "query{ projects{ id name } }",+ "query{ x{ connectionInfo{ host } } }", # lectura que nombra connectionInfo+ 'mutation{ selectProject(id:"1"){ currentProject{ __typename } } }',+ ):+ assert server.caido_graphql(doc)["status"] == "ok", doc+ assert len(spy["graphql"]) == 3+++def test_caido_graphql_sin_scope_es_passthrough_total(server, scope_off, spy):+ assert server.caido_graphql(_SEND)["status"] == "ok"+ assert spy["graphql"] == [_SEND]+++def test_caido_graphql_con_scope_corrupto_falla_cerrado(+ server, tmp_path, monkeypatch, spy+):+ f = tmp_path / "roto.json"+ f.write_text("{no es json")+ monkeypatch.setenv("SCOPE_FILE", str(f))+ out = server.caido_graphql(_SEND)+ assert out["scope_violation"] is True and spy["graphql"] == []+++# --- caido_history / server_info --------------------------------------------------------+++def test_caido_history_delega_y_devuelve_la_forma_documentada(server, monkeypatch):+ seen = {}++ def fake_search(httpql="", limit=50, **kw):+ seen.update(httpql=httpql, limit=limit)+ return {"status": "done", "count": 1, "entries": [{"id": "1"}]}++ monkeypatch.setattr(caido_client, "search_history", fake_search)+ out = server.caido_history("resp.code.eq:401", 5)+ assert out == {"status": "done", "count": 1, "entries": [{"id": "1"}]}+ assert seen == {"httpql": "resp.code.eq:401", "limit": 5}+++def test_server_info_expone_estado_de_caido_y_las_tres_tools(server, monkeypatch):+ monkeypatch.delenv("CAIDO_PAT", raising=False)+ monkeypatch.delenv("CAIDO_ACCESS_TOKEN", raising=False)+ info = server.server_info()+ assert set(info["caido"]) == {"url", "token_present", "guest_login"}+ assert info["caido"]["token_present"] is False+ assert isinstance(info["caido"]["guest_login"], bool)+ assert {"caido_graphql", "caido_request", "caido_history"} <= set(server.mcp.tools)diff --git a/docs/caido.md b/docs/caido.mdnew file mode 100644index 0000000..8b52ea9--- /dev/null+++ b/docs/caido.md@@ -0,0 +1,96 @@+# Caido integration++kali-mcp can drive [Caido](https://caido.io) — a web security toolkit (intercepting proxy, Replay,+HTTPQL history search, scope, workflows, findings). The goal: **anything Caido can do, Vulnerator+can do**, without wrapping every operation by hand.++## Tools++| Tool | What it does | Scope-guard |+|---|---|---|+| `caido_graphql` | Passthrough to Caido's **entire** public GraphQL API (Replay, scope, workflows, projects, intercept, findings, schema introspection…). Version-agnostic: if a query does not match the running Caido version, the server's GraphQL error is returned verbatim. | **Partial.** With `scope.json` active, documents that *send traffic* (Replay/Automate/workflows/intercept) are rejected and redirected to `caido_request`, because the destination is opaque inside a query. This is a best-effort denylist of send-capable fields (Caido's schema changes every release), not a proof. Without an active scope the passthrough is total. |+| `caido_request` | Sends an HTTP request to a target **through Caido's Replay**, waits for and returns the response: `status_code`, `length`, `roundtrip_ms` and the full `raw` response (headers + body, capped at `max_response_bytes`, default 20000, with `raw_truncated`). Traffic is logged in Caido (reproducible, searchable). Method, path and header names/values are validated (CR/LF/NUL are rejected, never sanitized) to prevent request injection. | **Yes** — same gate as `kali_run`/`kali_exec`. The full `scheme://host:port` is validated, so `allow`, `deny` and `ports` in `scope.json` are all honored. Blocked requests send **no traffic**. |+| `caido_history` | Searches captured traffic with an [HTTPQL](https://docs.caido.io) expression (e.g. `resp.code.eq:401`, `req.host.cont:"juice-shop"`). Read-only. | No (read-only) |++### Known limitations++- **`caido_graphql` scope filter** is a heuristic over mutation verbs, not a proof: a send-capable+ field whose name has none of them would pass while a scope is active, and a harmless mutation that+ contains one is rejected. Blocked calls are not written to the findings store (the tool has no+ `engagement_id`), unlike `caido_request`.+- **Response correlation** matches the replayed request by method/host/port/path and a history-id+ baseline taken before sending. Other traffic to the *same* method+path+host going through Caido's+ proxy at the same moment (e.g. a browser pointed at it) could be mistaken for the replay's response.+- **IPv6:** IPv4-mapped IPv6 literals (`::ffff:a.b.c.d`) are normalized to the IPv4 address before the+ scope check. `scope_guard` itself compares CIDRs only within one address family, which also affects+ `kali_run`; that is outside this change.++All data returned by Caido is **untrusted**: it is transported verbatim, never interpreted.++## Deployment++The `caido` service in `docker-compose.yml` runs the official `caido/caido` image on the internal+docker network only (`http://caido:8080`, **not** published to the host), with a persistent named+volume and a one-shot `caido-init` that fixes the volume's ownership (Caido runs as uid 996).++No configuration is needed — the defaults work out of the box:++```bash+docker compose up -d --build+```++## Authentication (zero-touch by default)++Caido's API only serves schema introspection unauthenticated; every real operation needs a+`Bearer` token **and a selected project**. `caido_client` handles both:++1. **Token** — `CAIDO_PAT` / `CAIDO_ACCESS_TOKEN` if set; otherwise the `loginAsGuest` mutation+ (the service starts with `--allow-guests`), which needs no account and no GUI.+2. **Project** — selects the first `READY` project, or creates one if there is none.++The session is cached, and renewed automatically (once) if Caido is recreated and the cached+token/project go stale.++**Security trade-off.** `--allow-guests` means *anything that can reach `http://caido:8080`* can obtain+a full-privilege token (read all captured traffic, send arbitrary Replay requests). "Not published+to the host" does **not** isolate Caido from other containers on the compose network — including a+deliberately vulnerable lab target, or an SSRF in one. That is fine for a local lab and for engagements+whose targets are external. If you run untrusted workloads on the same network, or publish the Caido+port, remove `--allow-guests` from the service command, set `CAIDO_ALLOW_GUEST=0` and use a+`CAIDO_PAT` (mint it once through an SSH tunnel to the GUI). `CAIDO_ALLOW_GUEST` is fail-closed: only+`1/true/yes/on` (or empty) enable the guest login; anything else (`0`, `no`, `off`, typos) disables it.++`CAIDO_PAT` lives in the kali container's environment, so the agent can read it through `kali_exec`.++Failure modes are explicit, never faked: `unauthenticated`, `unreachable`, `graphql_error`,+`timeout`, `failed`. `server_info` reports the configured Caido URL and whether a token is set.++## Schema versions++Caido states that its GraphQL schema changes on every release. The documents used by+`caido_request` / `caido_history` were verified end-to-end against **Caido 0.59.0**, which is the+default image tag (`caido/caido:0.59.0`). Override it with `CAIDO_IMAGE` to try another release;+`caido_graphql` keeps working across versions.++## Verifying the integration++Bring up Caido plus the OWASP Juice Shop lab target (internal network only) and call the tools:++```bash+docker compose -f docker-compose.yml -f docker-compose.target.yml up -d caido juice-shop+```++> **Gotcha, already fixed in the compose file:** Caido's own anti-DNS-rebinding protection+> rejects requests whose `Host` isn't `localhost` by default (same mechanism as+> `playwright-mcp`'s `--allowed-hosts`). The `caido` service command passes+> `--ui-domain caido` so it accepts the internal DNS name kali-mcp connects with; without it+> every call fails with `unauthenticated` and Caido logs `Domain caido not allowed`.++Then, from an MCP client connected to kali-mcp: `caido_request` with `url=http://juice-shop:3000/`+(expect `status_code: 200`), a `POST` to `/rest/user/login` with bad credentials (expect `401`),+and `caido_history` with `resp.code.eq:401` (expect that login entry). With a `scope.json` that+does not allow `juice-shop`, `caido_request` must fail with `SCOPE_VIOLATION` and the history+count must not change.++Unit tests: `docker/kali/tests/test_caido_client.py` and `test_caido_scope.py` (stdlib-only; no+Caido or network needed).diff --git a/docs/security.md b/docs/security.mdindex 0e2be6f..d9eb06b 100644--- a/docs/security.md+++ b/docs/security.md@@ -7,7 +7,7 @@There are two things you *can* turn on, and it helps to know what each does and does **not** cover.-## The opt-in scope-guard (`kali_run` / `kali_exec`)+## The opt-in scope-guard (`kali_run` / `kali_exec` / `caido_request`)A deterministic (code, not prompt) gate that validates the destination of every raw-shell action**before** executing it. It lives inside the Kali MCP, in front of the two raw-shell runners. It@@ -54,6 +54,14 @@ Turn it on:parse of the command is an extra belt that can only **block**, never approve — the declared`targets` are the source of truth.+ **Caido tools:** `caido_request` goes through the same gate, but derives the destination itself+ from its `url` (it needs no `targets` argument), validating the full `scheme://host:port` — so+ `allow`, `deny` and `ports` are all honored, and a blocked request sends no traffic. `caido_history`+ is read-only and ungated. `caido_graphql` cannot validate the destination of an opaque GraphQL+ document, so with the scope active it **rejects any `mutation` that looks like it sends traffic**+ (Replay/Automate/workflows/intercept/plugins, matched by verb) and points to `caido_request`. That+ filter is a heuristic, not a proof — see [`docs/caido.md`](caido.md) for its limits.+**Kill-switch:** `SCOPE_ENFORCE=0` force-disables the guard even if the file says `enabled: true`.## The MCP inbound token (`vulnerator-mcp` over HTTP)@@ -67,7 +75,7 @@ no listener and needs no token.## What none of this is-The scope-guard gates `kali_run`/`kali_exec` by destination; the inbound token gates reachability.+The scope-guard gates `kali_run`/`kali_exec`/`caido_request` by destination; the inbound token gates reachability.Neither is consent, a human-approval workflow, or a network firewall. The `scope` argument on theMCP `start_pentest` tool is **advisory** (folded into the prompt for operator clarity), not anenforced constraint. The hard brake is the opt-in scope-guard above.diff --git a/docs/usage.md b/docs/usage.mdindex cfdf8b1..0344ed7 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -103,6 +103,16 @@ hosts feed the downstream fan-out (e.g. `webtech_scan` per live host).- **Returns:** `{status, domain, pages, surface:{hosts, ips, cidrs, txt, counts}, banners?, warnings?}`.The API response is untrusted data — it is normalized in shape, never interpreted.+## `caido_graphql` / `caido_request` / `caido_history` — drive Caido++Give the agent [Caido](https://caido.io) (intercepting proxy, Replay, HTTPQL history, scope,+workflows). `caido_request` sends one request through Caido's Replay and returns the response —+status, timing and the raw headers+body (capped, `raw_truncated` when cut) — behind the same+scope-guard as `kali_run`; `caido_history` searches captured traffic by HTTPQL+(e.g. `resp.code.eq:401`); `caido_graphql` is a passthrough to Caido's whole GraphQL API. The+`caido` service starts with the stack and needs no configuration. Full reference, auth model and+limits: [`docs/caido.md`](caido.md).+## `webtech_scan` — technology/version fingerprint by cross-referenceRuns **whatweb + webanalyze + wpscan** against a URL and **merges** what each one sees into a single