Skip to content

Autonomous OODA-loop pentesting agent. Hermes brain, Kali + Playwright tools over MCP, ATT&CK as the Orient language.

feat: servidor kali-mcp (tool kali_run bloqueante) + tests y .gitignore de artefactos

Sergio Jimenez0d63c110cc47
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..eca2ed3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+# Secretos reales y entorno local (nunca versionar).
+.env
+*.local
+
+# Artefactos de Python / pytest (ruido de build, no fuente).
+__pycache__/
+*.py[cod]
+.pytest_cache/
+.mypy_cache/
+.ruff_cache/
diff --git a/docker/kali/Dockerfile b/docker/kali/Dockerfile
new file mode 100644
index 0000000..dff912e
--- /dev/null
+++ b/docker/kali/Dockerfile
@@ -0,0 +1,146 @@
+# PentAgent Kali — runtime determinista de tools (Prowler) servidas por kali-mcp.
+#
+# Multi-arch (linux/arm64 + linux/amd64). Base: kalilinux/kali-rolling, cuyo tag
+# `latest` es un manifiesto multi-arch que resuelve a la arquitectura del host
+# (en Mac M2 -> arm64 nativo).
+#
+# Build (desde la raíz del repo):
+# docker buildx build --platform linux/arm64,linux/amd64 \
+# -f docker/kali/Dockerfile -t pentagent-kali:dev .
+#
+# -----------------------------------------------------------------------------
+# Compatibilidad arm64 (R14.2, design.md 4.4)
+# -----------------------------------------------------------------------------
+# - kali-rolling publica imágenes para amd64 y arm64; en Mac M2 corre nativamente
+# en arm64.
+# - Prowler es un paquete Python puro (PyPI) -> instalable en arm64 y amd64 sin
+# binarios específicos de arquitectura.
+# - Si alguna tool determinista NO estuviera disponible para arm64, el servicio
+# kali-mcp debe REPORTARLO explícitamente (y el smoke test de pentagent-core lo
+# refleja en /health). No se finge disponibilidad: se reporta como no disponible
+# en esta arquitectura. Ver requirements.md R3.2/R3.3 y design.md 4.4.
+#
+# Nota de versión de Python: kali-rolling trae por defecto Python 3.14, pero
+# Prowler aún exige `<3.14`. Por eso instalamos `python3.13` y creamos un
+# virtualenv dedicado (/opt/kali-mcp/venv) donde viven Prowler + el SDK `mcp`.
+# El servidor arranca con el intérprete de ese venv.
+
+# syntax=docker/dockerfile:1
+
+FROM kalilinux/kali-rolling:latest
+
+ENV DEBIAN_FRONTEND=noninteractive \
+ PIP_NO_CACHE_DIR=1 \
+ PIP_DISABLE_PIP_VERSION_CHECK=1
+
+# Dependencias de sistema mínimas para Prowler/kali-mcp. python3.13 es el
+# intérprete compatible con Prowler (kali-rolling ya empaqueta 3.13).
+# Prowler arrastra alguna dependencia con extensión C (p. ej. `zstd`) que compila
+# en arm64; por eso se incluyen toolchain + headers + libzstd/pkg-config.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends \
+ python3.13 \
+ python3.13-venv \
+ python3.13-dev \
+ build-essential \
+ pkg-config \
+ libzstd-dev \
+ ca-certificates \
+ curl \
+ git \
+ && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /opt/kali-mcp
+
+# Virtualenv dedicado con Python 3.13 (compatible con Prowler). Ponerlo primero en
+# el PATH hace que `python3`/`pip`/`prowler` del venv sean los que se usan.
+ENV VIRTUAL_ENV=/opt/kali-mcp/venv \
+ PATH=/opt/kali-mcp/venv/bin:$PATH
+RUN python3.13 -m venv "$VIRTUAL_ENV" \
+ && "$VIRTUAL_ENV/bin/pip" install --no-cache-dir --upgrade pip
+
+# Manifiesto de dependencias del VENV DEL SERVIDOR (F0.7): Prowler + el SDK `mcp` que usa
+# kali-mcp. Versiones fijadas en requirements.txt.
+COPY docker/kali/requirements.txt ./requirements.txt
+RUN "$VIRTUAL_ENV/bin/pip" install --no-cache-dir -r requirements.txt
+
+# Fuentes EN VIVO adicionales (N33/N32) AISLADAS con pipx: cada herramienta en su propio
+# venv, con su entrypoint expuesto en /usr/local/bin (en PATH). kali-mcp las invoca como
+# SUBPROCESOS (`scout`, `cloudsplaining`), no las importa, así que NO necesitan compartir el
+# venv del servidor — y NO pueden: Prowler y ScoutSuite tienen deps incompatibles
+# (python-dateutil), un conflicto que tumbaría el build en un venv único. Aislar es el
+# patrón correcto para ejecutables independientes y evita el acoplamiento artificial.
+#
+# Los instala NO-FATALMENTE (`|| true`): si una tool no es instalable en esta arquitectura /
+# Python, el build NO se rompe; kali-mcp la reporta ausente (server_info -> which) y su
+# collection falla claro (fail-closed, R3.2/4.4). No se finge disponibilidad.
+ENV PIPX_HOME=/opt/pipx \
+ PIPX_BIN_DIR=/usr/local/bin
+RUN "$VIRTUAL_ENV/bin/pip" install --no-cache-dir pipx \
+ && ( "$VIRTUAL_ENV/bin/python" -m pipx install --python python3.13 scoutsuite==5.14.0 \
+ || echo "[kali-mcp] ScoutSuite no instalable en este runtime; se reportará ausente." ) \
+ && ( "$VIRTUAL_ENV/bin/python" -m pipx install --python python3.13 cloudsplaining==0.9.1 \
+ || echo "[kali-mcp] Cloudsplaining no instalable en este runtime; se reportará ausente." )
+
+# Servidor kali-mcp (entrypoint real). Expone la tool `prowler_scan` (y
+# `server_info` para el smoke test) sobre streamable-HTTP en :8900.
+# tool_streaming.py: helper de streaming de salida de tools en vivo (ring buffer +
+# ejecucion con kill del grupo de procesos al timeout). Lo importa kali_mcp_server.
+COPY docker/kali/tool_streaming.py ./tool_streaming.py
+# Plano de DATOS (N23), STDLIB PURA: staging del crudo (artifact_store), servidor HTTP
+# que lo entrega al core por stream (artifact_http) y finalización del escaneo
+# (prowler_artifact). Los importa kali_mcp_server / collector_runner.
+COPY docker/kali/artifact_store.py ./artifact_store.py
+COPY docker/kali/artifact_http.py ./artifact_http.py
+COPY docker/kali/prowler_artifact.py ./prowler_artifact.py
+# Runner multi-herramienta genérico (N33): registro por fuente + worker/finalize únicos
+# que lanzan prowler/scoutsuite/cloudsplaining bajo el mismo contrato. Lo importa
+# kali_mcp_server; reutiliza tool_streaming/artifact_store/prowler_artifact.
+COPY docker/kali/collector_runner.py ./collector_runner.py
+# Runner AWS del foso OODA: enum IAM read-only acotado (F2, tool `iam_enum`) y simulación de
+# permisos read-only (iam:SimulatePrincipalPolicy, tool `iam_simulate`). aws_exec.py/
+# aws_simulate.py son STDLIB PURA (build/exec vía tool_streaming); aws_iam_enum.py/
+# aws_iam_simulate.py son los scripts boto3 THIN que corren en el venv del servidor. Los
+# importa/invoca kali_mcp_server.
+COPY docker/kali/aws_exec.py ./aws_exec.py
+COPY docker/kali/aws_iam_enum.py ./aws_iam_enum.py
+COPY docker/kali/aws_simulate.py ./aws_simulate.py
+COPY docker/kali/aws_iam_simulate.py ./aws_iam_simulate.py
+# Runner de SHELL CRUDA (tool `kali_exec`): ejecuta un comando arbitrario de la Kali vía
+# `sh -c` reutilizando tool_streaming (STDLIB PURA). Lo importa kali_mcp_server.
+COPY docker/kali/shell_exec.py ./shell_exec.py
+COPY docker/kali/kali_mcp_server.py ./kali_mcp_server.py
+
+# Puerto del servidor kali-mcp. Overridable por entorno (KALI_MCP_PORT) sin
+# reconstruir, pero el default del contrato es 8900 (KALI_MCP_URL=http://kali:8900).
+ENV KALI_MCP_HOST=0.0.0.0 \
+ KALI_MCP_PORT=8900
+
+# Plano de DATOS (N23): el servidor HTTP de artefactos stagea el crudo en
+# KALI_ARTIFACTS_DIR y lo sirve en KALI_ARTIFACTS_PORT (DEDICADO, distinto del MCP).
+# KALI_ARTIFACTS_TOKEN NO se fija aquí: es obligatorio y se inyecta por el entorno
+# (compose, fail-closed); sin él, el canal de datos no arranca y se usa el puente.
+ENV KALI_ARTIFACTS_HOST=0.0.0.0 \
+ KALI_ARTIFACTS_DIR=/artifacts \
+ KALI_ARTIFACTS_PORT=8901
+
+EXPOSE 8900
+# Puerto del plano de DATOS. Se EXPONE a la red interna de docker (lo consume la API
+# como KALI_ARTIFACTS_URL), pero NO se publica al host en compose: el crudo puede ser
+# sensible y no debe salir del entorno docker.
+EXPOSE 8901
+
+# Healthcheck: el servidor MCP responde en la raíz (streamable-HTTP montado en "/").
+# Un proceso vivo y escuchando responde al transporte MCP (4xx del handshake), no
+# connection-refused; eso basta como liveness del contenedor. El smoke test
+# funcional real (listar tools) lo hace pentagent-core vía /health.
+HEALTHCHECK --interval=15s --timeout=5s --start-period=25s --retries=5 \
+ CMD curl -sS -o /dev/null -w '%{http_code}' "http://127.0.0.1:${KALI_MCP_PORT}/" \
+ | grep -Eq '^(200|400|405|406)$'
+
+# kali-mcp sirve las tools deterministas (Prowler) por este puerto; es el endpoint
+# que pentagent-core consume como cliente MCP (KALI_MCP_URL). Con `docker compose
+# up` el pentester tiene un Kali operativo como runner por defecto, sin configurar
+# nada manual. Un Kali remoto/propio sigue siendo override opcional (KALI_MCP_URL).
+# El python del PATH es el del venv (Python 3.13 con Prowler + mcp).
+CMD ["python3", "kali_mcp_server.py"]
diff --git a/docker/kali/artifact_http.py b/docker/kali/artifact_http.py
new file mode 100644
index 0000000..116a82e
--- /dev/null
+++ b/docker/kali/artifact_http.py
@@ -0,0 +1,149 @@
+"""Servidor HTTP de artefactos de `kali-mcp` — el canal del plano de DATOS (N23).
+
+STDLIB PURA (``http.server``), independiente de ``mcp``/``anyio`` (vive en su propio
+módulo, testeable sin el SDK). Sirve el resultado CRUDO staged por ``artifact_store``
+al core, que lo baja por STREAM a su almacén persistente. Es el transporte que
+sustituye al evento SSE de 1 MiB: el blob grande viaja por AQUÍ (HTTP chunked por
+referencia), NUNCA por el canal de control (MCP).
+
+Frontera de seguridad (plan, architecture §4):
+ - Exige la cabecera ``X-Artifact-Token`` == ``KALI_ARTIFACTS_TOKEN`` (403 sin ella o
+ si no coincide; comparación en tiempo constante). Fail-closed: ``make_server`` NO
+ arranca sin token.
+ - Confina rutas vía ``artifact_store.resolve`` (``..``/separadores -> 400).
+ - 404 si el artefacto no existe. El crudo es DATO NO CONFIABLE: se transporta
+ verbatim, no se interpreta ni se loguea su contenido.
+ - NO se publica al host (sólo red interna docker); lo decide la orquestación.
+"""
+
+from __future__ import annotations
+
+import hmac
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import unquote, urlsplit
+
+import artifact_store
+
+# Prefijo de ruta del endpoint de datos. Espejo del que el core compone al bajar.
+_PREFIX = "/artifacts/"
+
+# Tamaño de chunk al servir (64 KiB): stream, no "todo de golpe" (N23).
+_CHUNK_SIZE = 65536
+
+# Cabecera del token compartido kali<->core.
+_TOKEN_HEADER = "X-Artifact-Token"
+
+
+class _ArtifactHandler(BaseHTTPRequestHandler):
+ """Sirve ``GET /artifacts/<execution_id>/<name>`` por stream, tras validar token."""
+
+ server_version = "kali-artifacts/1.0"
+
+ # Silencia el log por defecto: la ruta puede contener dato no confiable y no se
+ # loguea verbatim (F0.8). Si hiciera falta trazar, se haría por un canal propio.
+ def log_message(self, *args, **kwargs) -> None: # noqa: D401, ANN002, ANN003
+ return
+
+ def _deny(self, code: int, reason: str) -> None:
+ """Responde un error corto (texto plano) sin filtrar el dato pedido."""
+ body = reason.encode("utf-8")
+ self.send_response(code)
+ self.send_header("Content-Type", "text/plain; charset=utf-8")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _token_ok(self) -> bool:
+ expected = getattr(self.server, "artifact_token", "") or ""
+ provided = self.headers.get(_TOKEN_HEADER, "") or ""
+ if not provided:
+ return False
+ # Comparación en tiempo constante (evita oráculo por temporización).
+ return hmac.compare_digest(provided, expected)
+
+ def do_GET(self) -> None: # noqa: N802 - firma de BaseHTTPRequestHandler
+ path = urlsplit(self.path).path
+
+ # 1) Token primero: sin credencial no se revela nada (403).
+ if not self._token_ok():
+ self._deny(403, "forbidden: missing or invalid artifact token")
+ return
+
+ # 2) Sólo el endpoint de artefactos.
+ if not path.startswith(_PREFIX):
+ self._deny(404, "not found")
+ return
+
+ # 3) Parsear <execution_id>/<name>; un multi-segmento se reconstruye como name
+ # con '/' y lo rechaza el confinamiento de resolve (-> 400).
+ rest = path[len(_PREFIX):]
+ parts = rest.split("/")
+ if len(parts) < 2 or not parts[0]:
+ self._deny(400, "bad request: expected /artifacts/<execution_id>/<name>")
+ return
+ execution_id = unquote(parts[0])
+ name = unquote("/".join(parts[1:]))
+
+ # 4) Confinamiento (traversal/separadores/absoluta) -> 400.
+ try:
+ target = artifact_store.resolve(execution_id, name)
+ except ValueError:
+ self._deny(400, "bad request: invalid artifact path")
+ return
+
+ # 5) Existencia -> 404.
+ if not target.is_file():
+ self._deny(404, "not found")
+ return
+
+ # 6) Stream del fichero con Content-Length + sha256 (de la meta si está).
+ entry = artifact_store.stat(execution_id, name)
+ size = entry["size"] if entry and "size" in entry else target.stat().st_size
+ self.send_response(200)
+ self.send_header("Content-Type", "application/octet-stream")
+ self.send_header("Content-Length", str(size))
+ if entry and entry.get("sha256"):
+ self.send_header("X-Artifact-Sha256", str(entry["sha256"]))
+ self.end_headers()
+ with target.open("rb") as handle:
+ while True:
+ chunk = handle.read(_CHUNK_SIZE)
+ if not chunk:
+ break
+ self.wfile.write(chunk)
+
+
+def make_server(host: str, port: int, token: str) -> ThreadingHTTPServer:
+ """Crea (sin arrancar) el servidor HTTP de artefactos ligado a ``token``.
+
+ Fail-closed (R14.3): levanta ``ValueError`` si ``token`` es vacío — un endpoint de
+ datos sin token sería un canal abierto a dato potencialmente sensible. ``port=0``
+ elige un puerto efímero (útil en tests; el real se lee de ``server.server_address``).
+ """
+ if not token:
+ raise ValueError(
+ "KALI_ARTIFACTS_TOKEN vacío: el servidor de artefactos no arranca sin "
+ "token (fail-closed)."
+ )
+ server = ThreadingHTTPServer((host, port), _ArtifactHandler)
+ # El handler lee el token del servidor (no de una global): un único punto de verdad.
+ server.artifact_token = token # type: ignore[attr-defined]
+ return server
+
+
+def serve_in_thread(
+ host: str, port: int, token: str
+) -> tuple[ThreadingHTTPServer, threading.Thread]:
+ """Arranca el servidor en un hilo DEMONIO y devuelve ``(server, thread)``.
+
+ No bloquea: el proceso principal sigue a ``mcp.run(...)`` (plano de control). El
+ caller puede ``server.shutdown()`` para pararlo (tests). El hilo es daemon para no
+ impedir la salida del proceso.
+ """
+ server = make_server(host, port, token)
+ thread = threading.Thread(
+ target=server.serve_forever, name="kali-artifacts-http", daemon=True
+ )
+ thread.start()
+ return server, thread
diff --git a/docker/kali/artifact_store.py b/docker/kali/artifact_store.py
new file mode 100644
index 0000000..df0962b
--- /dev/null
+++ b/docker/kali/artifact_store.py
@@ -0,0 +1,229 @@
+"""Staging EFÍMERO de artefactos de `kali-mcp` (STDLIB PURA).
+
+El plano de DATOS en el lado del runner (architecture §4/§5). Cuando una tool
+termina, su resultado CRUDO se **stagea** aquí indexado por ``execution_id`` y se
+SIRVE por HTTP (ver ``artifact_http.py``); el core lo baja por stream a su almacén
+PERSISTENTE y autoritativo. Este staging es efímero (vive en el contenedor Kali):
+no es la fuente de verdad, sólo el punto de entrega del dato grande SIN que viaje
+por el canal de control (MCP) — la refundación del puente SSE de 1 MiB (N23).
+
+Por qué un módulo aparte, igual que ``tool_streaming.py`` (N13 + testeabilidad):
+``kali_mcp_server.py`` importa ``mcp``/``anyio`` (no están en el venv de dev). Esta
+mecánica usa SOLO la librería estándar, así se cubre con tests sin el SDK.
+
+Disciplina de seguridad (F0.8): el blob es DATO NO CONFIABLE (salida verbatim de una
+tool contra un target real). Aquí se TRANSPORTA y PERSISTE verbatim; nunca se
+interpreta. Las rutas se CONFINAN bajo la raíz (sin ``..``/separadores) para que un
+``execution_id``/``name`` manipulado no escape del directorio de staging.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import tempfile
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterable, Iterator
+
+# Raíz del staging. Configurable por entorno; default `/artifacts` (dir del contenedor
+# Kali, efímero). El core lee por HTTP, no por FS compartido.
+_DEFAULT_ROOT = "/artifacts"
+
+_META_NAME = "meta.json"
+
+# Tamaño de chunk para copiar/leer sin cargar el fichero entero en RAM.
+_CHUNK_SIZE = 65536
+
+
+def _now_iso() -> str:
+ """Timestamp ISO-8601 en UTC (sufijo 'Z') — mismo estilo que tool_streaming."""
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def root_dir() -> Path:
+ """Directorio raíz del staging (``KALI_ARTIFACTS_DIR`` o ``/artifacts``)."""
+ return Path(os.environ.get("KALI_ARTIFACTS_DIR", _DEFAULT_ROOT))
+
+
+def _safe_segment(value: str) -> str:
+ """Valida que un segmento de ruta sea confinable (sin ``..``, ``/``, ``\\``, NUL).
+
+ Frontera del plano de datos: ``execution_id`` y ``name`` se validan ANTES de
+ tocar el filesystem. Devuelve el propio valor si es seguro; si no, ``ValueError``.
+ """
+ if not value or not isinstance(value, str):
+ raise ValueError("segmento de artefacto vacío o no-string")
+ if value in (".", "..") or "/" in value or "\\" in value or "\x00" in value:
+ raise ValueError("segmento de artefacto inseguro: %r" % (value,))
+ return value
+
+
+def _execution_dir(execution_id: str) -> Path:
+ return root_dir() / _safe_segment(execution_id)
+
+
+def resolve(execution_id: str, name: str) -> Path:
+ """Resuelve la ruta de un artefacto staged CONFINADA bajo la raíz.
+
+ Valida ``execution_id``/``name`` (sin traversal ni separadores) y verifica que la
+ ruta resuelta cae bajo la raíz del staging. Levanta ``ValueError`` si algo intenta
+ escapar. NO comprueba existencia (eso es cosa del caller: 404 si no existe).
+ """
+ safe_exec = _safe_segment(execution_id)
+ safe_name = _safe_segment(name)
+ root = root_dir().resolve()
+ candidate = (root / safe_exec / safe_name).resolve()
+ if candidate != root and root not in candidate.parents:
+ raise ValueError("ruta de artefacto fuera de la raíz de staging")
+ return candidate
+
+
+# --- metadatos por ejecución (meta.json) -------------------------------------
+
+
+def _meta_path(execution_id: str) -> Path:
+ return _execution_dir(execution_id) / _META_NAME
+
+
+def read_meta(execution_id: str) -> dict[str, Any]:
+ """Devuelve el índice de artefactos staged de una ejecución (``{}`` si no hay).
+
+ Estructura: ``{"execution_id": str, "artifacts": {name: {size, sha256, staged_at,
+ meta}}}``. Un ``execution_id`` desconocido o un meta ilegible devuelven ``{}``
+ (no revienta).
+ """
+ path = _meta_path(execution_id)
+ try:
+ with path.open("r", encoding="utf-8") as handle:
+ data = json.load(handle)
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _write_meta(execution_id: str, index: dict[str, Any]) -> None:
+ """Escribe el índice de meta de la ejecución de forma atómica (tmp+replace)."""
+ exec_dir = _execution_dir(execution_id)
+ exec_dir.mkdir(parents=True, exist_ok=True)
+ path = _meta_path(execution_id)
+ fd, tmp_name = tempfile.mkstemp(dir=exec_dir, suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(index, handle, ensure_ascii=False, indent=2)
+ os.replace(tmp_name, path)
+ except BaseException:
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
+
+
+def _record_meta(
+ execution_id: str, name: str, size: int, sha256: str, meta: dict[str, Any] | None
+) -> dict[str, Any]:
+ """Añade/actualiza la entrada de un artefacto en el meta.json de la ejecución."""
+ index = read_meta(execution_id)
+ if not index:
+ index = {"execution_id": execution_id, "artifacts": {}}
+ index.setdefault("artifacts", {})
+ entry = {
+ "name": name,
+ "size": size,
+ "sha256": sha256,
+ "staged_at": _now_iso(),
+ "meta": dict(meta or {}),
+ }
+ index["artifacts"][name] = entry
+ _write_meta(execution_id, index)
+ return entry
+
+
+# --- staging (atómico, por stream) -------------------------------------------
+
+
+def _stage_stream(
+ execution_id: str, name: str, chunks: Iterable[bytes]
+) -> tuple[int, str]:
+ """Escribe un stream de chunks al destino confinado (tmp+replace) -> (size, sha256).
+
+ Calcula tamaño + sha256 sobre la marcha, sin materializar el artefacto entero en
+ RAM (clave para resultados grandes, N23).
+ """
+ dest = resolve(execution_id, name)
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ hasher = hashlib.sha256()
+ size = 0
+ fd, tmp_name = tempfile.mkstemp(dir=dest.parent, suffix=".tmp")
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ for chunk in chunks:
+ if not chunk:
+ continue
+ data = chunk.encode("utf-8") if isinstance(chunk, str) else bytes(chunk)
+ handle.write(data)
+ hasher.update(data)
+ size += len(data)
+ os.replace(tmp_name, dest)
+ except BaseException:
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+ raise
+ return size, hasher.hexdigest()
+
+
+def put_bytes(
+ execution_id: str,
+ name: str,
+ data: bytes,
+ meta: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Stagea ``data`` como artefacto ``name`` de la ejecución y registra su meta.
+
+ Devuelve la entrada de meta ``{name, size, sha256, staged_at, meta}``.
+ """
+ size, sha256 = _stage_stream(execution_id, name, (data,))
+ return _record_meta(execution_id, name, size, sha256, meta)
+
+
+def put_file(
+ execution_id: str,
+ name: str,
+ src_path: str | os.PathLike[str],
+ meta: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Stagea el fichero ``src_path`` como artefacto ``name`` (copiándolo por chunks).
+
+ Copia el contenido de ``src_path`` al destino confinado por stream (no carga el
+ fichero entero en RAM) ANTES de que el caller limpie su directorio temporal.
+ Devuelve la entrada de meta ``{name, size, sha256, staged_at, meta}``.
+ """
+ src = Path(src_path)
+
+ def _chunks() -> Iterator[bytes]:
+ with src.open("rb") as handle:
+ while True:
+ chunk = handle.read(_CHUNK_SIZE)
+ if not chunk:
+ break
+ yield chunk
+
+ size, sha256 = _stage_stream(execution_id, name, _chunks())
+ return _record_meta(execution_id, name, size, sha256, meta)
+
+
+def stat(execution_id: str, name: str) -> dict[str, Any] | None:
+ """Devuelve la entrada de meta de un artefacto staged, o ``None`` si no existe.
+
+ No revienta ante ``execution_id``/``name`` desconocidos (devuelve ``None``). Un
+ ``name`` con traversal se rechaza en ``resolve`` (``ValueError``), que el caller
+ (HTTP) traduce a 400.
+ """
+ index = read_meta(execution_id)
+ artifacts = index.get("artifacts", {}) if isinstance(index, dict) else {}
+ entry = artifacts.get(name)
+ return dict(entry) if isinstance(entry, dict) else None
diff --git a/docker/kali/aws_exec.py b/docker/kali/aws_exec.py
new file mode 100644
index 0000000..dd250e5
--- /dev/null
+++ b/docker/kali/aws_exec.py
@@ -0,0 +1,169 @@
+"""Runner AWS del foso OODA (STDLIB PURA) — construye y ejecuta el enum IAM.
+
+Rol (architecture §1/§5): es la LÓGICA testeable del runner ``iam_enum`` que expone
+``kali_mcp_server`` como ``@mcp.tool`` SÍNCRONA. Igual que ``collector_runner`` /
+``tool_streaming``, vive en un módulo aparte que usa SOLO la librería estándar (sin
+``mcp``, sin ``boto3``) para poder cubrirse con tests unitarios en el venv de dev, donde
+ni el SDK ni boto3 están instalados.
+
+Qué provee:
+ - ``build_iam_enum_cmd(account_id, params, outfile)``: construye el argv (sin shell)
+ ``[python3, aws_iam_enum.py, --account, <id>, --out, <outfile>]``. Valida ``account_id``
+ con forma de cuenta AWS (12 dígitos) y RECHAZA fail-closed lo mal formado (N-untrusted:
+ nunca se interpola entrada sin validar en un comando).
+ - ``run_iam_enum(account_id, params, execution_id, timeout)``: crea un tmpdir, construye
+ el cmd, lo ejecuta con ``tool_streaming.run_tool_streaming`` (kill de grupo/timeout/logs
+ al ring), lee el fichero de salida y devuelve ``{'status':'done',...,'output':<json-str>}``
+ o ``{'status':'failed',...,'error':<diagnóstico>}``; limpia el tmpdir en ``finally``.
+
+Es SÍNCRONO de un solo tiro (a diferencia del collector async): el enum IAM acotado es
+corto y su JSON único lo stagea el EXECUTOR del core (decisión (c) del plan). Aquí NO se
+stagea artefacto ni se duplica ``KaliMcpClient``/``finalize_scan``: se devuelve el JSON
+crudo (``output``) y el core lo deposita en el plano de DATOS.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import tempfile
+from pathlib import Path
+from typing import Any
+
+import tool_streaming
+
+# Script boto3 THIN que ejecuta el enum real. Vive junto a este módulo en la imagen
+# (COPY en el Dockerfile); se invoca como subproceso, NO se importa (boto3 no está en
+# el venv de dev).
+IAM_ENUM_SCRIPT = "aws_iam_enum.py"
+
+# Timeout por defecto del enum IAM (segundos). El enum acotado es corto; aun así se acota
+# para no colgar el servidor. Overridable por entorno.
+DEFAULT_TIMEOUT = int(os.environ.get("AWS_IAM_ENUM_TIMEOUT", "300"))
+
+# Nombre del fichero de salida dentro del tmpdir efímero.
+_OUTFILE_NAME = "iam-enum.json"
+
+# Forma de un ID de cuenta AWS: exactamente 12 dígitos (fail-closed, N-untrusted).
+_ACCOUNT_RE = re.compile(r"^\d{12}$")
+
+
+class AwsExecError(ValueError):
+ """Entrada mal formada para el runner AWS (fail-closed; no se ejecuta nada)."""
+
+
+def _validate_account_id(account_id: str) -> str:
+ """Valida ``account_id`` con forma de cuenta AWS (12 dígitos) o lanza ``AwsExecError``.
+
+ N-untrusted: el ``account_id`` llega del CONTROL (potencialmente no confiable); nunca se
+ interpola en un comando sin validar. Fail-closed: cualquier cosa que no sea 12 dígitos
+ se rechaza con un error claro, sin ejecutar el subproceso.
+ """
+ if not isinstance(account_id, str) or not _ACCOUNT_RE.match(account_id.strip()):
+ raise AwsExecError(
+ f"account_id inválido: {account_id!r} (se esperan 12 dígitos de cuenta AWS)."
+ )
+ return account_id.strip()
+
+
+def _script_path() -> str:
+ """Ruta absoluta del script de enum, resuelta junto a este módulo (robusto al cwd)."""
+ return str(Path(__file__).resolve().parent / IAM_ENUM_SCRIPT)
+
+
+def build_iam_enum_cmd(account_id: str, params: Any, outfile: str) -> list[str]:
+ """Construye el argv (sin shell) del enum IAM; valida ``account_id`` fail-closed.
+
+ ``params`` se acepta por contrato (reservado para acotaciones futuras); hoy no altera
+ el comando. Devuelve ``[python3, <ruta aws_iam_enum.py>, --account, <id>, --out, <out>]``.
+ """
+ account = _validate_account_id(account_id)
+ return [
+ "python3",
+ _script_path(),
+ "--account",
+ account,
+ "--out",
+ outfile,
+ ]
+
+
+def _ring_tail(execution_id: str, max_lines: int = 20) -> str:
+ """Últimas líneas de salida de la ejecución (dato NO confiable, verbatim)."""
+ page = tool_streaming.read(execution_id, 0)
+ lines = page.get("lines", [])
+ tail = lines[-max_lines:]
+ return "\n".join(f"[{line['stream']}] {line['text']}" for line in tail)
+
+
+def run_iam_enum(
+ account_id: str,
+ params: Any = "",
+ execution_id: str = "",
+ timeout: int = DEFAULT_TIMEOUT,
+) -> dict[str, Any]:
+ """Ejecuta el enum IAM read-only y devuelve el JSON crudo (SÍNCRONO, un solo tiro).
+
+ Flujo: valida ``account_id`` (fail-closed) -> crea un tmpdir efímero -> construye el
+ cmd -> ejecuta con ``tool_streaming.run_tool_streaming`` (kill de grupo/timeout, logs al
+ ring por ``execution_id``) -> lee el fichero de salida. Devuelve
+ ``{'status':'done','returncode':rc,'output':<json-string>}`` si hay salida legible, o
+ ``{'status':'failed','returncode':rc,'error':<diagnóstico con cola del ring>}`` en
+ timeout/sin salida. Limpia el tmpdir en ``finally``. El JSON crudo (``output``) lo
+ stagea el EXECUTOR del core (plano de DATOS); aquí NO se stagea.
+ """
+ try:
+ account = _validate_account_id(account_id)
+ except AwsExecError as exc:
+ return {"status": "failed", "returncode": -1, "error": str(exc)}
+
+ workdir = tempfile.mkdtemp(prefix="aws-iam-enum-")
+ try:
+ outfile = str(Path(workdir) / _OUTFILE_NAME)
+ cmd = build_iam_enum_cmd(account, params, outfile)
+ returncode, timed_out, cancelled = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=timeout, cwd=workdir
+ )
+ if cancelled:
+ return {"status": "cancelled", "cancelled": True, "returncode": returncode}
+ if timed_out:
+ return {
+ "status": "failed",
+ "timed_out": True,
+ "returncode": returncode,
+ "error": (
+ f"iam_enum excedió el timeout ({timeout}s). "
+ f"Últimas líneas: {_ring_tail(execution_id)}"
+ ),
+ }
+ output = _read_output(outfile)
+ if output is None:
+ return {
+ "status": "failed",
+ "returncode": returncode,
+ "error": (
+ f"iam_enum no produjo salida legible (exit={returncode}): "
+ f"{_ring_tail(execution_id)}"
+ ),
+ }
+ return {
+ "status": "done",
+ "returncode": returncode,
+ "output": output,
+ }
+ finally:
+ shutil.rmtree(workdir, ignore_errors=True)
+
+
+def _read_output(outfile: str) -> str | None:
+ """Lee el JSON de salida como texto crudo; ``None`` si no existe o está vacío.
+
+ No se interpreta el contenido (dato NO confiable): se devuelve verbatim para que el
+ executor del core lo stagee en el plano de DATOS.
+ """
+ path = Path(outfile)
+ if not path.is_file():
+ return None
+ text = path.read_text(encoding="utf-8")
+ return text if text.strip() else None
diff --git a/docker/kali/aws_iam_enum.py b/docker/kali/aws_iam_enum.py
new file mode 100644
index 0000000..47eb99c
--- /dev/null
+++ b/docker/kali/aws_iam_enum.py
@@ -0,0 +1,150 @@
+"""Script THIN de enumeración IAM read-only para el runner AWS del foso (F2).
+
+Rol (architecture §1/§5 — plano de DATOS): es el BINARIO determinista que corre en
+el venv del servidor Kali (boto3 llega vía Prowler). NO decide nada: enumera IAM de
+forma ACOTADA y SOLO-LECTURA y escribe UN único documento JSON en la ruta de ``--out``.
+El runner STDLIB (``aws_exec.py``) lo invoca como subproceso con ``tool_streaming``
+(kill de grupo/timeout, logs al ring) y stagea su salida como artefacto; el crudo viaja
+por el plano de DATOS, nunca inline por el CONTROL.
+
+Disciplina de seguridad (R3/R4, scope-notes):
+ - READ-ONLY: SOLO ``list_*``/``get_*``. NUNCA create/put/attach/delete: no cambia el
+ estado de la cuenta AWS. Las credenciales read-only vienen del entorno del contenedor
+ (igual que Prowler/ScoutSuite), el scope ya lo validó el core ANTES de invocar.
+ - ACOTADO: enumera roles/usuarios/grupos/políticas (ámbito ``Local`` = gestionadas por
+ el cliente) con nombres+ARNs y relaciones de adjunción. NO vuelca
+ ``get-account-authorization-details`` completo (eso es trabajo de Cloudsplaining):
+ aquí se busca el mapa IAM para el bucle OODA, no el dump exhaustivo de documentos.
+
+THIN a propósito (N13 KISS): sin lógica que pida test unitario; la mecánica testeable
+(construcción del comando, ejecución, lectura de salida, diagnóstico) vive en
+``aws_exec.py`` (STDLIB puro). Este fichero solo se valida con ``ast.parse`` (no se
+importa en los tests: boto3 no está en el venv de dev).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+import boto3 # provisto por el venv del servidor (Prowler lo arrastra)
+
+
+def _paginate(client, method_name: str, result_key: str, **kwargs) -> list:
+ """Recorre todas las páginas de un ``list_*`` y acumula ``result_key`` (read-only)."""
+ paginator = client.get_paginator(method_name)
+ items: list = []
+ for page in paginator.paginate(**kwargs):
+ items.extend(page.get(result_key, []))
+ return items
+
+
+def _simplify(entity: dict, keys: tuple[str, ...]) -> dict:
+ """Proyecta solo los campos solicitados de una entidad IAM (acota el volumen)."""
+ return {k: entity.get(k) for k in keys if k in entity}
+
+
+def enumerate_iam(client) -> dict:
+ """Enumera IAM ACOTADO y read-only: roles/usuarios/grupos/políticas + adjunciones.
+
+ SOLO ``list_*``/``get_*``. Para cada principal se listan las políticas gestionadas
+ adjuntas (ARNs) y los nombres de políticas inline; para los usuarios, además su
+ pertenencia a grupos. Las políticas se limitan al ámbito ``Local`` (gestionadas por
+ el cliente) para no arrastrar el catálogo entero de políticas AWS-managed.
+ """
+ roles = _paginate(client, "list_roles", "Roles")
+ users = _paginate(client, "list_users", "Users")
+ groups = _paginate(client, "list_groups", "Groups")
+ # Scope ``Local`` = políticas gestionadas por el cliente; evita arrastrar el catálogo
+ # entero de políticas AWS-managed (acotación).
+ policies = _paginate(client, "list_policies", "Policies", Scope="Local")
+
+ roles_out = []
+ for role in roles:
+ name = role["RoleName"]
+ attached = client.list_attached_role_policies(RoleName=name).get(
+ "AttachedPolicies", []
+ )
+ inline = client.list_role_policies(RoleName=name).get("PolicyNames", [])
+ roles_out.append(
+ {
+ **_simplify(role, ("RoleName", "Arn", "RoleId", "Path", "CreateDate")),
+ "attached_policies": [p.get("PolicyArn") for p in attached],
+ "inline_policies": inline,
+ }
+ )
+
+ users_out = []
+ for user in users:
+ name = user["UserName"]
+ attached = client.list_attached_user_policies(UserName=name).get(
+ "AttachedPolicies", []
+ )
+ inline = client.list_user_policies(UserName=name).get("PolicyNames", [])
+ user_groups = client.list_groups_for_user(UserName=name).get("Groups", [])
+ users_out.append(
+ {
+ **_simplify(user, ("UserName", "Arn", "UserId", "Path", "CreateDate")),
+ "attached_policies": [p.get("PolicyArn") for p in attached],
+ "inline_policies": inline,
+ "groups": [g.get("GroupName") for g in user_groups],
+ }
+ )
+
+ groups_out = []
+ for group in groups:
+ name = group["GroupName"]
+ attached = client.list_attached_group_policies(GroupName=name).get(
+ "AttachedPolicies", []
+ )
+ inline = client.list_group_policies(GroupName=name).get("PolicyNames", [])
+ groups_out.append(
+ {
+ **_simplify(group, ("GroupName", "Arn", "GroupId", "Path", "CreateDate")),
+ "attached_policies": [p.get("PolicyArn") for p in attached],
+ "inline_policies": inline,
+ }
+ )
+
+ policies_out = [
+ _simplify(
+ p,
+ ("PolicyName", "Arn", "PolicyId", "Path", "AttachmentCount", "IsAttachable"),
+ )
+ for p in policies
+ ]
+
+ return {
+ "roles": roles_out,
+ "users": users_out,
+ "groups": groups_out,
+ "policies": policies_out,
+ "counts": {
+ "roles": len(roles_out),
+ "users": len(users_out),
+ "groups": len(groups_out),
+ "policies": len(policies_out),
+ },
+ }
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Enum IAM read-only acotado (JSON a --out)")
+ parser.add_argument("--account", required=True, help="ID de la cuenta AWS autorizada")
+ parser.add_argument("--out", required=True, help="Fichero donde escribir el JSON único")
+ args = parser.parse_args(argv)
+
+ session = boto3.session.Session()
+ iam = session.client("iam")
+
+ result = enumerate_iam(iam)
+ document = {"account": args.account, "iam": result}
+
+ with open(args.out, "w", encoding="utf-8") as fh:
+ json.dump(document, fh, default=str)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/docker/kali/aws_iam_simulate.py b/docker/kali/aws_iam_simulate.py
new file mode 100644
index 0000000..e68db3f
--- /dev/null
+++ b/docker/kali/aws_iam_simulate.py
@@ -0,0 +1,110 @@
+"""Script THIN de simulación de permisos efectivos IAM (read-only) para el foso (inc4b).
+
+Rol (architecture §1/§5 — plano de DATOS): BINARIO determinista que corre en el venv del
+servidor Kali (boto3 llega vía Prowler). NO decide nada: dado UN principal IAM concreto,
+comprueba con ``iam:SimulatePrincipalPolicy`` (API AWS **READ-ONLY**: NO modifica estado)
+si ese principal PUEDE ejecutar un conjunto FIJO de acciones de privesc clásicas, y escribe
+UN único documento JSON en la ruta de ``--out``. El runner STDLIB (``aws_simulate.py``) lo
+invoca como subproceso con ``tool_streaming`` (kill de grupo/timeout, logs al ring) y stagea
+su salida como artefacto; el crudo viaja por el plano de DATOS, nunca inline por el CONTROL.
+
+Es el ANÁLOGO per-candidato de ``aws_iam_enum.py`` (que es recon account-wide): aquí se
+confirma la EXPLOTABILIDAD efectiva de un principal, más fuerte que la mera enumeración. El
+salto a ``EXPLOITED``/E4 NO lo decide este script ni el bucle: lo decide el confirmador de
+dominio AWS en el core (inc4c), que leerá estas decisiones.
+
+Disciplina de seguridad (R3/R4, scope-notes):
+ - READ-ONLY: ``SimulatePrincipalPolicy`` SIMULA la evaluación de políticas; NO ejecuta las
+ acciones ni cambia el estado de la cuenta. Las credenciales read-only vienen del entorno
+ del contenedor (igual que Prowler/ScoutSuite); el scope ya lo validó el core ANTES de invocar.
+ - FAIL-CLOSED: si el propio ``SimulatePrincipalPolicy`` devuelve ``AccessDenied`` (o cualquier
+ otro error del cliente), NO se revienta con un traceback: se escribe un JSON con un ``error``
+ claro y ``simulation`` vacío, y el runner lo surfacea como fallo (dato NO confiable, F0.8).
+
+THIN a propósito (N13 KISS): sin lógica que pida test unitario; la mecánica testeable
+(construcción del comando, ejecución, lectura de salida, diagnóstico) vive en
+``aws_simulate.py`` (STDLIB puro). Este fichero solo se valida con ``ast.parse`` (no se
+importa en los tests: boto3 no está en el venv de dev).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+import boto3 # provisto por el venv del servidor (Prowler lo arrastra)
+
+# Conjunto FIJO de acciones de PRIVESC clásicas de IAM que se simulan por principal. Son las
+# primitivas con las que un principal con permisos excesivos escala a admin (asumir roles,
+# pasar roles a servicios, crear credenciales, adjuntar/escribir políticas, versionar una
+# política gestionada, reescribir la trust policy de un rol). Es un conjunto CERRADO y
+# documentado: la técnica declara expectativas acotadas, no un barrido arbitrario.
+PRIVESC_ACTIONS: tuple[str, ...] = (
+ "sts:AssumeRole",
+ "iam:PassRole",
+ "iam:CreateAccessKey",
+ "iam:AttachUserPolicy",
+ "iam:AttachRolePolicy",
+ "iam:PutUserPolicy",
+ "iam:PutRolePolicy",
+ "iam:CreatePolicyVersion",
+ "iam:UpdateAssumeRolePolicy",
+)
+
+
+def simulate_principal(client, principal_arn: str, actions: tuple[str, ...]) -> dict:
+ """Simula ``actions`` sobre ``principal_arn`` y devuelve ``{accion: EvalDecision}``.
+
+ SOLO ``iam:SimulatePrincipalPolicy`` (read-only). ``EvalDecision`` ∈ {``allowed``,
+ ``explicitDeny``, ``implicitDeny``}. Se pagina por si la respuesta llega troceada.
+ """
+ decisions: dict = {}
+ paginator = client.get_paginator("simulate_principal_policy")
+ for page in paginator.paginate(
+ PolicySourceArn=principal_arn, ActionNames=list(actions)
+ ):
+ for result in page.get("EvaluationResults", []):
+ decisions[result.get("EvalActionName")] = result.get("EvalDecision")
+ return decisions
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Simula permisos efectivos de privesc de un principal IAM (read-only, JSON a --out)"
+ )
+ parser.add_argument("--account", required=True, help="ID de la cuenta AWS autorizada")
+ parser.add_argument(
+ "--principal-arn",
+ required=True,
+ dest="principal_arn",
+ help="ARN del principal IAM a simular (PolicySourceArn)",
+ )
+ parser.add_argument("--out", required=True, help="Fichero donde escribir el JSON único")
+ args = parser.parse_args(argv)
+
+ session = boto3.session.Session()
+ iam = session.client("iam")
+
+ document: dict = {
+ "account": args.account,
+ "principal_arn": args.principal_arn,
+ "actions": list(PRIVESC_ACTIONS),
+ }
+ try:
+ document["simulation"] = simulate_principal(iam, args.principal_arn, PRIVESC_ACTIONS)
+ except Exception as exc: # noqa: BLE001 - AccessDenied u otro: fail-closed, NO revienta
+ # El propio Simulate puede estar denegado para la credencial read-only. Se deja
+ # constancia clara (al ring por stderr y en el JSON) sin tumbar el proceso; el runner
+ # lo surfacea como 'failed' leyendo este 'error'.
+ document["error"] = f"SimulatePrincipalPolicy no disponible: {exc}"
+ document["simulation"] = {}
+ print(document["error"], file=sys.stderr, flush=True)
+
+ with open(args.out, "w", encoding="utf-8") as fh:
+ json.dump(document, fh, default=str)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/docker/kali/aws_simulate.py b/docker/kali/aws_simulate.py
new file mode 100644
index 0000000..fc0c73e
--- /dev/null
+++ b/docker/kali/aws_simulate.py
@@ -0,0 +1,229 @@
+"""Runner AWS del foso OODA (STDLIB PURA) — construye y ejecuta el simulate IAM (inc4b).
+
+Rol (architecture §1/§5): es la LÓGICA testeable del runner ``iam_simulate`` que expone
+``kali_mcp_server`` como ``@mcp.tool`` ASÍNCRONA. Espejo de ``aws_exec.py`` (el runner del
+``iam_enum``): vive en un módulo aparte que usa SOLO la librería estándar (sin ``mcp``, sin
+``boto3``) para poder cubrirse con tests unitarios en el venv de dev, donde ni el SDK ni
+boto3 están instalados. REUTILIZA ``tool_streaming`` (igual que ``aws_exec``); no duplica
+mecánica de ejecución/logs/kill.
+
+Qué provee:
+ - ``build_iam_simulate_cmd(account_id, principal_arn, outfile)``: construye el argv (sin
+ shell) ``[python3, aws_iam_simulate.py, --account, <id>, --principal-arn, <arn>, --out,
+ <outfile>]``. Valida ``account_id`` (12 dígitos) Y ``principal_arn`` (forma
+ ``arn:aws:iam::<acct>:...``) y RECHAZA fail-closed lo mal formado (N-untrusted: nunca se
+ interpola entrada sin validar en un comando).
+ - ``run_iam_simulate(account_id, principal_arn, execution_id, timeout)``: crea un tmpdir,
+ construye el cmd, lo ejecuta con ``tool_streaming.run_tool_streaming`` (kill de
+ grupo/timeout/logs al ring), lee el fichero de salida y devuelve
+ ``{'status':'done',...,'output':<json-str>}`` o ``{'status':'failed',...,'error':...}``;
+ limpia el tmpdir en ``finally``.
+
+Es SÍNCRONO de un solo tiro (como ``aws_exec``): el simulate acotado es corto y su JSON único
+lo stagea el EXECUTOR del core. A diferencia del enum, el simulate PUEDE fallar de forma
+ESTRUCTURADA: si la credencial read-only no puede ni llamar a ``SimulatePrincipalPolicy``, el
+script THIN escribe un JSON con un ``error`` claro (no revienta); este runner lo detecta y
+devuelve ``failed`` (fail-closed), propagando ese ``error`` VERBATIM (dato NO confiable, F0.8).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import tempfile
+from pathlib import Path
+from typing import Any
+
+import tool_streaming
+
+# Script boto3 THIN que ejecuta el simulate real. Vive junto a este módulo en la imagen
+# (COPY en el Dockerfile); se invoca como subproceso, NO se importa (boto3 no está en el
+# venv de dev).
+IAM_SIMULATE_SCRIPT = "aws_iam_simulate.py"
+
+# Timeout por defecto del simulate IAM (segundos). El simulate acotado (9 acciones sobre un
+# principal) es CORTO; se acota igualmente para no colgar el servidor. Overridable por entorno.
+DEFAULT_TIMEOUT = int(os.environ.get("AWS_IAM_SIMULATE_TIMEOUT", "120"))
+
+# Nombre del fichero de salida dentro del tmpdir efímero.
+_OUTFILE_NAME = "iam-simulate.json"
+
+# Forma de un ID de cuenta AWS: exactamente 12 dígitos (fail-closed, N-untrusted).
+_ACCOUNT_RE = re.compile(r"^\d{12}$")
+
+# Forma de un ARN de principal IAM: ``arn:aws:iam::<12 dígitos>:<recurso>`` (role/user/group).
+# El conjunto de caracteres del recurso excluye metacaracteres de shell (defensa N-untrusted,
+# aunque el argv va sin shell). El grupo de cuenta se compara luego con ``account_id``.
+_PRINCIPAL_ARN_RE = re.compile(r"^arn:aws:iam::(\d{12}):[A-Za-z0-9+=,.@/_-]+$")
+
+
+class AwsSimulateError(ValueError):
+ """Entrada mal formada para el runner AWS (fail-closed; no se ejecuta nada)."""
+
+
+def _validate_account_id(account_id: str) -> str:
+ """Valida ``account_id`` con forma de cuenta AWS (12 dígitos) o lanza ``AwsSimulateError``."""
+ if not isinstance(account_id, str) or not _ACCOUNT_RE.match(account_id.strip()):
+ raise AwsSimulateError(
+ f"account_id inválido: {account_id!r} (se esperan 12 dígitos de cuenta AWS)."
+ )
+ return account_id.strip()
+
+
+def _validate_principal_arn(principal_arn: str, account_id: str) -> str:
+ """Valida ``principal_arn`` (forma IAM) y que su cuenta coincida con ``account_id``.
+
+ N-untrusted: el ARN llega del CONTROL (derivado de un candidato del grafo, dato NO
+ confiable); nunca se interpola en un comando sin validar. Fail-closed: cualquier cosa que
+ no sea un ARN IAM de ESTA cuenta se rechaza con un error claro, sin ejecutar el subproceso.
+ """
+ if not isinstance(principal_arn, str):
+ raise AwsSimulateError(f"principal_arn inválido: {principal_arn!r} (se esperaba un ARN IAM).")
+ match = _PRINCIPAL_ARN_RE.match(principal_arn.strip())
+ if not match:
+ raise AwsSimulateError(
+ f"principal_arn inválido: {principal_arn!r} "
+ "(se esperaba 'arn:aws:iam::<cuenta>:<recurso>')."
+ )
+ if match.group(1) != account_id.strip():
+ raise AwsSimulateError(
+ f"principal_arn fuera de la cuenta autorizada: {principal_arn!r} "
+ f"(cuenta del scope: {account_id!r})."
+ )
+ return principal_arn.strip()
+
+
+def _script_path() -> str:
+ """Ruta absoluta del script de simulate, resuelta junto a este módulo (robusto al cwd)."""
+ return str(Path(__file__).resolve().parent / IAM_SIMULATE_SCRIPT)
+
+
+def build_iam_simulate_cmd(account_id: str, principal_arn: str, outfile: str) -> list[str]:
+ """Construye el argv (sin shell) del simulate IAM; valida entradas fail-closed.
+
+ Devuelve ``[python3, <ruta aws_iam_simulate.py>, --account, <id>, --principal-arn, <arn>,
+ --out, <out>]``.
+ """
+ account = _validate_account_id(account_id)
+ principal = _validate_principal_arn(principal_arn, account)
+ return [
+ "python3",
+ _script_path(),
+ "--account",
+ account,
+ "--principal-arn",
+ principal,
+ "--out",
+ outfile,
+ ]
+
+
+def _ring_tail(execution_id: str, max_lines: int = 20) -> str:
+ """Últimas líneas de salida de la ejecución (dato NO confiable, verbatim)."""
+ page = tool_streaming.read(execution_id, 0)
+ lines = page.get("lines", [])
+ tail = lines[-max_lines:]
+ return "\n".join(f"[{line['stream']}] {line['text']}" for line in tail)
+
+
+def run_iam_simulate(
+ account_id: str,
+ principal_arn: str,
+ execution_id: str = "",
+ timeout: int = DEFAULT_TIMEOUT,
+) -> dict[str, Any]:
+ """Ejecuta el simulate IAM read-only y devuelve el JSON crudo (SÍNCRONO, un solo tiro).
+
+ Flujo: valida ``account_id`` + ``principal_arn`` (fail-closed) -> crea un tmpdir efímero ->
+ construye el cmd -> ejecuta con ``tool_streaming.run_tool_streaming`` (kill de
+ grupo/timeout, logs al ring por ``execution_id``) -> lee el fichero de salida. Devuelve
+ ``{'status':'done','returncode':rc,'output':<json-string>}`` si hay salida legible SIN un
+ ``error`` estructurado; ``{'status':'failed',...,'error':...}`` en timeout, sin salida, o si
+ el JSON trae un ``error`` (p. ej. ``AccessDenied`` del propio Simulate). Limpia el tmpdir en
+ ``finally``. El JSON crudo (``output``) lo stagea el EXECUTOR del core (plano de DATOS).
+ """
+ try:
+ account = _validate_account_id(account_id)
+ principal = _validate_principal_arn(principal_arn, account)
+ except AwsSimulateError as exc:
+ return {"status": "failed", "returncode": -1, "error": str(exc)}
+
+ workdir = tempfile.mkdtemp(prefix="aws-iam-simulate-")
+ try:
+ outfile = str(Path(workdir) / _OUTFILE_NAME)
+ cmd = build_iam_simulate_cmd(account, principal, outfile)
+ returncode, timed_out, cancelled = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=timeout, cwd=workdir
+ )
+ if cancelled:
+ return {"status": "cancelled", "cancelled": True, "returncode": returncode}
+ if timed_out:
+ return {
+ "status": "failed",
+ "timed_out": True,
+ "returncode": returncode,
+ "error": (
+ f"iam_simulate excedió el timeout ({timeout}s). "
+ f"Últimas líneas: {_ring_tail(execution_id)}"
+ ),
+ }
+ output = _read_output(outfile)
+ if output is None:
+ return {
+ "status": "failed",
+ "returncode": returncode,
+ "error": (
+ f"iam_simulate no produjo salida legible (exit={returncode}): "
+ f"{_ring_tail(execution_id)}"
+ ),
+ }
+ error = _structured_error(output)
+ if error:
+ # Fallo ESTRUCTURADO del simulate (p. ej. AccessDenied del propio Simulate): el
+ # script THIN lo escribió como ``error`` en el JSON. Se propaga VERBATIM (F0.8:
+ # dato NO confiable; se lee el estado, no se interpreta como instrucción).
+ return {
+ "status": "failed",
+ "returncode": returncode,
+ "error": f"iam_simulate: {error}",
+ }
+ return {
+ "status": "done",
+ "returncode": returncode,
+ "output": output,
+ }
+ finally:
+ shutil.rmtree(workdir, ignore_errors=True)
+
+
+def _read_output(outfile: str) -> str | None:
+ """Lee el JSON de salida como texto crudo; ``None`` si no existe o está vacío.
+
+ No se interpreta el contenido (dato NO confiable): se devuelve verbatim para que el
+ executor del core lo stagee en el plano de DATOS.
+ """
+ path = Path(outfile)
+ if not path.is_file():
+ return None
+ text = path.read_text(encoding="utf-8")
+ return text if text.strip() else None
+
+
+def _structured_error(output: str) -> str | None:
+ """Devuelve el ``error`` de nivel superior del JSON de salida, o ``None`` si no hay.
+
+ Lectura de ESTADO del plano de control (no interpretación de instrucciones, F0.8): el
+ script THIN escribe ``{"error": "..."}`` cuando el propio Simulate falla fail-closed. Si el
+ output no es un JSON-objeto o no trae ``error``, se trata como éxito (``None``).
+ """
+ try:
+ doc = json.loads(output)
+ except (ValueError, TypeError):
+ return None
+ if isinstance(doc, dict):
+ err = doc.get("error")
+ if err:
+ return str(err)
+ return None
diff --git a/docker/kali/collector_runner.py b/docker/kali/collector_runner.py
new file mode 100644
index 0000000..6161690
--- /dev/null
+++ b/docker/kali/collector_runner.py
@@ -0,0 +1,395 @@
+"""Runner multi-herramienta genérico de `kali-mcp` (STDLIB PURA) — N33.
+
+Generaliza el patrón de collection EN VIVO (hasta ahora específico de Prowler) a varias
+tools (Prowler/ScoutSuite/Cloudsplaining) bajo UN contrato único: un **registro** por
+fuente aporta (a) el binario a comprobar con ``shutil.which``, (b) el/los comando(s) a
+ejecutar y dónde escriben su salida, (c) cómo localizar el fichero crudo (NO el HTML) y su
+nombre canónico de artefacto, y (d) la finalización (stagear el crudo como artefacto y
+construir el ``done`` con la REFERENCIA, nunca la carga). NO es una ruta nueva por
+herramienta: es un worker/finalize genérico + registro.
+
+Por qué un módulo aparte (igual que ``tool_streaming``/``artifact_store``/``prowler_artifact``):
+``kali_mcp_server.py`` importa ``mcp``/``anyio`` (no están en el venv de dev). Toda la
+mecánica del runner vive aquí con SOLO la librería estándar, así se cubre con tests sin el
+SDK. Reutiliza ``tool_streaming`` (streaming + kill de grupo + cancelación) y
+``artifact_store`` (staging del crudo) ya existentes; Prowler delega en ``prowler_artifact``
+(mismo finalize + puente SSE de compat) — cero duplicación (N13).
+
+Separación de planos (architecture §1/§5): el crudo de CUALQUIER tool viaja por el plano de
+DATOS (artefactos); el ``done`` del CONTROL sólo lleva la referencia. Para fuentes no-Prowler
+NO se popula el puente SSE ``set_findings`` (D6): su salida es un documento JSON único que
+el core baja por el plano de datos. Disciplina arm64 (R3.2/4.4): si el binario no está, se
+reporta (no se finge).
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import tempfile
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable
+
+import artifact_store
+import prowler_artifact
+import tool_streaming
+
+# Timeout por defecto de una collection (segundos); el server puede pasar el suyo.
+DEFAULT_TIMEOUT = int(os.environ.get("COLLECTION_TIMEOUT", os.environ.get("PROWLER_TIMEOUT", "900")))
+
+# Nombres canónicos del artefacto crudo por fuente (deben casar con el fallback del core).
+PROWLER_ARTIFACT_NAME = prowler_artifact.PROWLER_ARTIFACT_NAME # "prowler.ocsf.json"
+SCOUTSUITE_ARTIFACT_NAME = "scoutsuite.results.json"
+CLOUDSPLAINING_ARTIFACT_NAME = "cloudsplaining.results.json"
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _ring_tail(execution_id: str, max_lines: int = 20) -> str:
+ """Últimas líneas de salida de una ejecución (dato NO confiable, verbatim)."""
+ page = tool_streaming.read(execution_id, 0)
+ lines = page.get("lines", [])
+ tail = lines[-max_lines:]
+ return "\n".join(f"[{line['stream']}] {line['text']}" for line in tail)
+
+
+# --------------------------------------------------------------- comandos por fuente
+
+
+def _prowler_binary() -> str | None:
+ return shutil.which("prowler")
+
+
+def _build_prowler_cmd(outdir: str) -> list[str]:
+ """Args del comando Prowler (sin shell) escribiendo en ``outdir`` (igual que antes).
+
+ Reúne la configuración por entorno del MVP (status/regiones/servicios/verbose). Asume
+ que Prowler está disponible (el runner lo valida con ``shutil.which``).
+ """
+ cmd = [
+ _prowler_binary() or "prowler",
+ "aws",
+ "--output-formats",
+ "json-ocsf",
+ "--output-directory",
+ outdir,
+ "--status",
+ *os.environ.get("PROWLER_STATUS", "FAIL").split(),
+ ]
+ _regions = os.environ.get("PROWLER_REGIONS", os.environ.get("AWS_REGION", "")).strip()
+ if _regions:
+ cmd += ["--region", *_regions.split()]
+ _services = os.environ.get("PROWLER_SERVICES", "").strip()
+ if _services:
+ cmd += ["--service", *_services.split()]
+ cmd += ["--verbose", "--log-level", "INFO"]
+ return cmd
+
+
+def _prowler_commands(account_id: str, workdir: str, outdir: str, params: dict) -> list[list[str]]:
+ return [_build_prowler_cmd(outdir)]
+
+
+def _scoutsuite_commands(account_id: str, workdir: str, outdir: str, params: dict) -> list[list[str]]:
+ """ScoutSuite AWS, read-only, salida JSON en ``outdir/scoutsuite-results/*.js``.
+
+ ``--no-browser`` evita abrir el navegador; las credenciales AWS read-only se toman del
+ entorno del contenedor (igual que Prowler).
+ """
+ return [
+ [
+ "scout",
+ "aws",
+ "--no-browser",
+ "--result-format",
+ "json",
+ "--report-dir",
+ outdir,
+ "--report-name",
+ "pentagent",
+ ]
+ ]
+
+
+def _cloudsplaining_commands(account_id: str, workdir: str, outdir: str, params: dict) -> list[list[str]]:
+ """Cloudsplaining en dos pasos: descargar los detalles IAM y escanearlos.
+
+ 1. ``cloudsplaining download --output <dir>`` baja el account-authorization-details. OJO:
+ su ``--output`` es un DIRECTORIO EXISTENTE (``click.Path(exists=True)``, default el cwd),
+ NO un fichero; escribe ``<profile>.json`` dentro (sin ``--profile`` -> ``default.json``).
+ Las credenciales AWS vienen del entorno (sin ``--profile``), así que el crudo descargado
+ es ``<workdir>/default.json``.
+ 2. ``cloudsplaining scan --input-file <workdir>/default.json`` lo analiza y escribe el JSON
+ de resultados (``iam-results-*.json`` / ``iam-findings-*.json``) en ``outdir``
+ (``--skip-open-report`` evita abrir el navegador). El JSON es lo que se stagea; el HTML
+ (presentación) se ignora. ``download`` escribe en ``workdir`` (FUERA de ``outdir``), así
+ que el localizador ``*.json`` de ``outdir`` solo ve la salida del scan, no el crudo IAM.
+ """
+ authfile = str(Path(workdir) / "default.json")
+ return [
+ ["cloudsplaining", "download", "--output", workdir],
+ [
+ "cloudsplaining",
+ "scan",
+ "--input-file",
+ authfile,
+ "--output",
+ outdir,
+ "--skip-open-report",
+ ],
+ ]
+
+
+# --------------------------------------------------------------- localizadores de crudo
+
+
+def _locate_newest(outdir: Path, patterns: tuple[str, ...]) -> Path | None:
+ """Fichero más reciente y legible que casa alguno de los ``patterns`` (rglob)."""
+ candidates: list[Path] = []
+ for pattern in patterns:
+ candidates.extend(p for p in outdir.rglob(pattern) if p.is_file())
+ if not candidates:
+ return None
+ candidates.sort(key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True)
+ return candidates[0]
+
+
+def _scoutsuite_locate(outdir: Path) -> Path | None:
+ # ScoutSuite escribe el crudo en ``scoutsuite-results/scoutsuite_results_*.js`` (o .json
+ # con --result-format json). El envoltorio ``.js`` lo tolera el normalizador del core.
+ return _locate_newest(
+ outdir, ("scoutsuite_results_*.js", "scoutsuite_results_*.json")
+ )
+
+
+def _cloudsplaining_locate(outdir: Path) -> Path | None:
+ # El scan de Cloudsplaining escribe DOS JSON en ``outdir`` (ambos serializados desde
+ # ``authorization_details.results`` en la versión pinada 0.9.1): ``iam-results-<name>.json``
+ # y ``iam-findings-<name>.json``. Los dos llevan la forma de secciones de políticas
+ # (``customer_managed_policies``/``inline_policies``/``aws_managed_policies``) que el
+ # normalizador (``CloudsplainingImportCollector``) sabe parsear. Se fija el prefijo de
+ # forma DETERMINISTA —primero ``iam-results-*``, con ``iam-findings-*`` como respaldo— en
+ # vez de "el ``*.json`` más reciente" (que, con dos ficheros, elige por mtime a ciegas y
+ # puede quedarse con el crudo equivocado -> 0 findings). NUNCA el ``*.html`` (presentación)
+ # ni el ``default.json`` de descarga (input del scan, FUERA de ``outdir``).
+ return _locate_newest(outdir, ("iam-results-*.json",)) or _locate_newest(
+ outdir, ("iam-findings-*.json",)
+ )
+
+
+# --------------------------------------------------------------- finalización por fuente
+
+
+def _finalize_artifact(
+ execution_id: str,
+ outdir: Path,
+ returncode: int,
+ params: dict,
+ *,
+ source: str,
+ artifact_name: str,
+ locate: Callable[[Path], Path | None],
+) -> dict[str, Any] | None:
+ """Finaliza una collection NO-Prowler: stagea el crudo y construye el ``done`` (D6).
+
+ NO popula el puente SSE ``set_findings`` (la salida es un documento JSON único que el
+ core baja por el plano de datos). Si no hay salida legible, devuelve ``None`` (el caller
+ publica ``failed`` con diagnóstico).
+ """
+ path = locate(outdir)
+ if path is None:
+ return None
+ meta = {
+ "tool": source,
+ "phase": "collection",
+ "params": dict(params),
+ "ts": _now_iso(),
+ "returncode": returncode,
+ "status": "done",
+ }
+ entry = artifact_store.put_file(execution_id, artifact_name, path, meta)
+ return {
+ "status": "done",
+ "returncode": returncode,
+ "timed_out": False,
+ "artifact": {
+ "execution_id": execution_id,
+ "name": artifact_name,
+ "size": entry["size"],
+ "sha256": entry["sha256"],
+ },
+ }
+
+
+def _prowler_finalize(
+ execution_id: str, outdir: Path, returncode: int, params: dict
+) -> dict[str, Any] | None:
+ """Finaliza Prowler reutilizando ``prowler_artifact`` (stage + puente SSE + ``done``)."""
+ return prowler_artifact.finalize_scan(execution_id, outdir, returncode, dict(params))
+
+
+# --------------------------------------------------------------- registro de fuentes
+
+
+@dataclass(frozen=True)
+class CollectorSpec:
+ """Contrato de un collector EN VIVO (una entrada del registro, N33)."""
+
+ source: str
+ binary: str
+ artifact_name: str
+ build_commands: Callable[[str, str, str, dict], list[list[str]]]
+ finalize: Callable[[str, Path, int, dict], "dict[str, Any] | None"]
+
+
+def _non_bridged_finalize(
+ source: str, artifact_name: str, locate: Callable[[Path], Path | None]
+) -> Callable[[str, Path, int, dict], "dict[str, Any] | None"]:
+ def _f(execution_id: str, outdir: Path, returncode: int, params: dict) -> "dict[str, Any] | None":
+ return _finalize_artifact(
+ execution_id,
+ outdir,
+ returncode,
+ params,
+ source=source,
+ artifact_name=artifact_name,
+ locate=locate,
+ )
+
+ return _f
+
+
+REGISTRY: dict[str, CollectorSpec] = {
+ "prowler": CollectorSpec(
+ source="prowler",
+ binary="prowler",
+ artifact_name=PROWLER_ARTIFACT_NAME,
+ build_commands=_prowler_commands,
+ finalize=_prowler_finalize,
+ ),
+ "scoutsuite": CollectorSpec(
+ source="scoutsuite",
+ binary="scout",
+ artifact_name=SCOUTSUITE_ARTIFACT_NAME,
+ build_commands=_scoutsuite_commands,
+ finalize=_non_bridged_finalize(
+ "scoutsuite", SCOUTSUITE_ARTIFACT_NAME, _scoutsuite_locate
+ ),
+ ),
+ "cloudsplaining": CollectorSpec(
+ source="cloudsplaining",
+ binary="cloudsplaining",
+ artifact_name=CLOUDSPLAINING_ARTIFACT_NAME,
+ build_commands=_cloudsplaining_commands,
+ finalize=_non_bridged_finalize(
+ "cloudsplaining", CLOUDSPLAINING_ARTIFACT_NAME, _cloudsplaining_locate
+ ),
+ ),
+}
+
+
+def available_collectors() -> dict[str, bool]:
+ """Disponibilidad REAL de cada collector (``shutil.which`` del binario), sin fingir."""
+ return {src: shutil.which(spec.binary) is not None for src, spec in REGISTRY.items()}
+
+
+def finalize(
+ source: str, execution_id: str, outdir: str | os.PathLike[str], returncode: int, params: dict | None = None
+) -> dict[str, Any] | None:
+ """Finaliza una collection ya ejecutada: stagea el crudo y construye el ``done``.
+
+ Punto único reutilizable (lo usa ``run_collection`` y el gate funcional del core, que
+ stagea un crudo de fixture por fuente). Despacha al ``finalize`` de la fuente.
+ """
+ spec = REGISTRY.get(source)
+ if spec is None:
+ raise ValueError(f"fuente de collection desconocida: {source!r}")
+ return spec.finalize(execution_id, Path(outdir), returncode, dict(params or {}))
+
+
+def run_collection(
+ source: str,
+ account_id: str,
+ execution_id: str,
+ params: str = "",
+ timeout: int = DEFAULT_TIMEOUT,
+) -> dict[str, Any]:
+ """Worker genérico: lanza la tool de ``source`` y devuelve el ``done``/``failed``.
+
+ Corre en el hilo de ``tool_streaming.start_background`` (indexado por ``execution_id``).
+ Flujo (architecture §5): valida binario -> ejecuta el/los comando(s) con streaming de
+ logs en vivo y kill de grupo al timeout/cancelación -> localiza el crudo -> stagea como
+ artefacto -> construye el ``done`` con la REFERENCIA (no la carga). Reporta ``failed`` con
+ diagnóstico si no hay binario o salida legible; ``cancelled`` si el usuario cancela.
+ """
+ spec = REGISTRY.get(source)
+ if spec is None:
+ raise RuntimeError(f"fuente de collection desconocida: {source!r}")
+ if shutil.which(spec.binary) is None:
+ # arm64 u otra arquitectura sin la tool: se reporta, no se finge (R3.2/4.4).
+ raise RuntimeError(
+ f"La tool {spec.binary!r} (fuente {source!r}) no está disponible en este "
+ f"runtime ({os.uname().machine}); no se finge la collection."
+ )
+
+ workdir = tempfile.mkdtemp(prefix=f"{source}-")
+ try:
+ outdir = Path(workdir) / "out"
+ outdir.mkdir(parents=True, exist_ok=True)
+ commands = spec.build_commands(account_id, workdir, str(outdir), _parse_params(params))
+
+ returncode = 0
+ for cmd in commands:
+ returncode, timed_out, cancelled = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=timeout, cwd=workdir
+ )
+ if cancelled:
+ return {"status": "cancelled", "cancelled": True, "returncode": returncode}
+ if timed_out:
+ return {
+ "status": "failed",
+ "timed_out": True,
+ "returncode": returncode,
+ "error": (
+ f"{source} excedió el timeout ({timeout}s). "
+ f"Últimas líneas: {_ring_tail(execution_id)}"
+ ),
+ }
+
+ done = spec.finalize(
+ execution_id,
+ outdir,
+ returncode,
+ {"account_id": account_id, "source": source},
+ )
+ if done is None:
+ return {
+ "status": "failed",
+ "returncode": returncode,
+ "error": (
+ f"{source} no produjo salida legible (exit={returncode}): "
+ f"{_ring_tail(execution_id)}"
+ ),
+ }
+ return done
+ finally:
+ shutil.rmtree(workdir, ignore_errors=True)
+
+
+def _parse_params(params: Any) -> dict:
+ """Parse tolerante de los params del start_collection (string JSON opcional)."""
+ if isinstance(params, dict):
+ return params
+ if isinstance(params, str) and params.strip():
+ try:
+ import json
+
+ parsed = json.loads(params)
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception: # noqa: BLE001 - params libre, no fatal
+ return {}
+ return {}
diff --git a/docker/kali/kali_mcp_server.py b/docker/kali/kali_mcp_server.py
new file mode 100644
index 0000000..2210f69
--- /dev/null
+++ b/docker/kali/kali_mcp_server.py
@@ -0,0 +1,597 @@
+"""Servidor `kali-mcp` de PentAgent — runtime determinista de tools en Kali.
+
+Rol MCP (design.md "Doble rol MCP"):
+ - Este proceso es el SERVIDOR `kali-mcp` que corre DENTRO del contenedor Kali.
+ PentAgent (pentagent-core) lo consume como CLIENTE MCP vía `KALI_MCP_URL`.
+ - NO es el servidor MCP que PentAgent *expone* a asistentes externos (ese vive
+ en la API). No confundir.
+
+Decisión de implementación (documentada — N12.4):
+ Los servidores `kali-mcp` open-source existentes son puentes genéricos de
+ "ejecuta cualquier comando en una terminal". Eso choca con la disciplina del
+ MVP (R3/R4, scope-notes N2): la recolección v1 es *read-only*, determinista y
+ acotada a Prowler; NO se expone ejecución de comandos arbitrarios. Por eso se
+ implementa aquí un servidor MCP MÍNIMO sobre el SDK oficial `mcp` (FastMCP,
+ transporte streamable-HTTP) que expone EXACTAMENTE la tool que el cliente de
+ pentagent-core espera (`prowler_scan`) y una tool de información segura para el
+ smoke test. Esto mantiene la frontera y encaja 1:1 con `KaliMcpClient` sin tocar
+ los contratos.
+
+Transporte: streamable-HTTP en `0.0.0.0:$KALI_MCP_PORT` (8900 por defecto), con el
+endpoint MCP montado en la raíz (`/`) para que el cliente alcance el servidor por
+`KALI_MCP_URL=http://kali:8900` sin configurar un path.
+
+Disciplina arm64 (R3.2/R3.3, design.md 4.4): si Prowler no está disponible en esta
+arquitectura, la tool `prowler_scan` NO finge: devuelve un error claro. El smoke
+test (listar tools + `server_info`) refleja el estado real; la ausencia de una tool
+esperada la detecta el cliente (`EXPECTED_TOOLS`).
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import uuid
+from typing import Any
+
+# tool_streaming: primitivas de streaming en STDLIB PURA (ring buffer por
+# execution_id + run_tool_streaming con muerte del grupo al expirar el timeout).
+# Vive en módulo aparte a propósito: NO importa `mcp`/`anyio`, así su lógica se
+# cubre con tests unitarios sin el SDK (ver docker/kali/tests/).
+import tool_streaming
+
+# Runner multi-herramienta genérico (N33), STDLIB PURA: registro por fuente
+# (prowler/scoutsuite/cloudsplaining) + worker/finalize únicos. `prowler_scan` y
+# `start_collection` delegan aquí (una ruta, no una copia por tool). A su vez reutiliza
+# `prowler_artifact` (stage + puente SSE) para la fuente Prowler y `artifact_store`.
+import collector_runner
+
+# Runner AWS del foso OODA (F2), STDLIB PURA (sin `mcp`/`boto3`): construye y ejecuta el
+# enum IAM read-only acotado (build_iam_enum_cmd + run_iam_enum) reutilizando
+# `tool_streaming`. La tool `iam_enum` lanza este worker EN BACKGROUND (igual que las
+# colecciones) y el cliente sondea con `get_scan_status`; su JSON crudo lo stagea el
+# executor del core (plano de DATOS), por eso aquí NO se stagea.
+import aws_exec
+
+# Runner AWS del foso OODA (inc4b), STDLIB PURA (sin `mcp`/`boto3`): construye y ejecuta el
+# simulate IAM read-only per-principal (build_iam_simulate_cmd + run_iam_simulate) reutilizando
+# `tool_streaming`. Espejo de `aws_exec` para la tool `iam_simulate` (misma mecánica async).
+import aws_simulate
+
+# Runner de SHELL CRUDA (STDLIB PURA, sin `mcp`): ejecuta un comando arbitrario de la
+# Kali vía `sh -c` reutilizando `tool_streaming` (kill de grupo/timeout/logs al ring).
+# La tool `kali_exec` lanza este worker EN BACKGROUND (igual que iam_enum) y el cliente
+# sondea con `get_scan_status` + `read_tool_logs`. Da al bucle OODA una Kali completa
+# (encadenar, pipes, scripts propios, cualquier tool instalada). La AUTORIZACIÓN (scope/
+# consentimiento/audit) la aplica el CORE ANTES de invocar; aquí solo se EJECUTA.
+import shell_exec
+
+# Plano de DATOS (N23), STDLIB PURA (sin `mcp`/`anyio`): servidor HTTP que SIRVE los
+# artefactos staged al core por stream. (El staging/finalización vive en
+# `collector_runner`/`prowler_artifact`, que `collector_runner` importa.)
+import artifact_http
+
+# SDK `mcp`: la imagen Kali fija `mcp<2` (1.x `FastMCP`, ver
+# docker/kali/requirements.txt) a propósito, para hablar la MISMA era de protocolo
+# que el cliente de pentagent-core. Este servidor usa la API 1.x `FastMCP`.
+from mcp.server.fastmcp import FastMCP
+
+# --- Configuración por entorno (overridable; defaults seguros) ---------------
+HOST = os.environ.get("KALI_MCP_HOST", "0.0.0.0")
+PORT = int(os.environ.get("KALI_MCP_PORT", "8900"))
+# Timeout de un escaneo Prowler (segundos). Evita colgar el servidor indefinidamente.
+PROWLER_TIMEOUT = int(os.environ.get("PROWLER_TIMEOUT", "900"))
+
+# Plano de DATOS (N23): el servidor HTTP de artefactos escucha en su propio puerto
+# (DEDICADO, distinto del MCP 8900), sólo en la red interna docker (NO publicado al
+# host). El token compartido es OBLIGATORIO (fail-closed): sin él no se arranca el
+# canal de datos y el core cae al puente `read_scan_findings`.
+ARTIFACTS_HOST = os.environ.get("KALI_ARTIFACTS_HOST", "0.0.0.0")
+ARTIFACTS_PORT = int(os.environ.get("KALI_ARTIFACTS_PORT", "8901"))
+ARTIFACTS_TOKEN = os.environ.get("KALI_ARTIFACTS_TOKEN", "")
+
+# Nombre de la tool que el cliente de pentagent-core espera (PROWLER_TOOL_NAME).
+# Si cambia aquí, cambia en packages/.../tools/kali_mcp.py (único punto de acople).
+PROWLER_TOOL_NAME = "prowler_scan"
+
+# Tool multi-herramienta (N33): lanza en vivo prowler/scoutsuite/cloudsplaining bajo el
+# MISMO contrato no-bloqueante. `prowler_scan` queda como alias de delegación (compat).
+# Si cambia aquí, cambia en packages/.../tools/kali_mcp.py (único punto de acople).
+START_COLLECTION_TOOL_NAME = "start_collection"
+
+# Tool genérica de lectura incremental de logs de cualquier ejecución (verbose en
+# vivo). La consume FEAT-002 (API/UI) para mostrar la salida de Kali en directo.
+READ_LOGS_TOOL_NAME = "read_tool_logs"
+
+# Tool de sondeo del estado de un escaneo lanzado en background por `prowler_scan`.
+# La consume FEAT-002 para resolver el flujo no-bloqueante (started -> running ->
+# done/failed) por execution_id.
+SCAN_STATUS_TOOL_NAME = "get_scan_status"
+
+# Tool de lectura PAGINADA de los findings de un escaneo terminado. Existe para no
+# superar el límite de 1 MiB de un único evento SSE del transporte streamable-http:
+# `get_scan_status` al `done` ya NO lleva los findings inline (sólo `findings_count`)
+# y el cliente los recupera por páginas con esta tool (mismo patrón cursor que los
+# logs). La consume el core (kali<->core); no se expone en el servidor MCP público.
+READ_FINDINGS_TOOL_NAME = "read_scan_findings"
+
+# Tool interna kali<->core que CANCELA un escaneo en curso (N22.2): mata el grupo de
+# proceso por execution_id reutilizando el kill existente de tool_streaming. La invoca
+# el core (CoreServices.cancel_phase); NO se expone en el servidor MCP público.
+CANCEL_SCAN_TOOL_NAME = "cancel_scan"
+
+# Tool del runner AWS del foso OODA (F2): enum IAM read-only acotado, NO BLOQUEANTE (igual
+# que las colecciones): lanza el enum en background por `execution_id` y devuelve en <2s
+# con `{'execution_id','status':'started'}`; el cliente sondea con `get_scan_status` y lee
+# la salida en vivo con `read_tool_logs`. Así el enum (p. ej. 153 roles) NO retiene el hilo
+# de petición ni tumba el healthcheck del servidor. Al `done`, el JSON crudo del enum viaja
+# inline en `output` (puente F2 ya registrado; stage-on-kali es F4) y lo stagea el executor
+# del core (plano de DATOS). ACTIVE_SAFE: el gate de intrusividad del bucle OODA la autoriza
+# (registro 'aws-exec' en config/mcp-servers.yaml).
+IAM_ENUM_TOOL_NAME = "iam_enum"
+
+# Tool del runner AWS del foso OODA (inc4b): simulate IAM read-only PER-PRINCIPAL. Dado el ARN
+# de un principal de un candidato alcanzable, usa `iam:SimulatePrincipalPolicy` (API AWS
+# READ-ONLY: NO modifica estado) para comprobar si ese principal PUEDE ejecutar un conjunto fijo
+# de acciones de privesc clásicas. NO BLOQUEANTE EXACTAMENTE como `iam_enum`: lanza el worker en
+# background por `execution_id` y devuelve en <2s con `{'execution_id','status':'started'}`; el
+# cliente sondea con `get_scan_status` y lee la salida en vivo con `read_tool_logs`. Al `done`,
+# el JSON crudo del simulate viaja inline en `output` (mismo puente que el enum) y lo stagea el
+# executor del core (plano de DATOS). ACTIVE_SAFE: read-only pero acción activa contra AWS, mismo
+# nivel que `iam_enum` (registro 'aws-exec' en config/mcp-servers.yaml).
+IAM_SIMULATE_TOOL_NAME = "iam_simulate"
+
+# Tool de SHELL CRUDA de la Kali (decisión del operador): ejecuta un comando arbitrario
+# vía `sh -c` en el contenedor Kali. A diferencia de los runners deterministas/acotados
+# (iam_enum/iam_simulate/prowler), NO restringe el comando: da al bucle OODA una Kali
+# completa (herramientas instaladas, pipes, scripts propios). NO BLOQUEANTE como los
+# demás runners (background + poll). INTRUSIVE: la ejecución de comandos arbitrarios es
+# potencialmente intrusiva/destructiva, así que su registro MCP (config/mcp-servers.yaml)
+# va a un nivel que el gate de intrusividad del core gobierna; el scope/consentimiento/
+# audit los aplica el CORE ANTES de invocar, no esta tool.
+KALI_EXEC_TOOL_NAME = "kali_exec"
+
+# Variante BLOQUEANTE de la shell cruda para el OODA conducido por LLM: a diferencia de
+# `kali_exec` (no bloqueante + poll), `kali_run` ejecuta el comando SINCRONAMENTE y
+# DEVUELVE la salida completa en UNA sola llamada (con timeout). Pensada para que Hermes
+# la use como una tool normal sin tener que orquestar el patrón started->poll->read.
+# Comparte el MISMO runner (`shell_exec.run_shell`): NO duplica lógica, solo cambia la
+# forma de entrega (bloqueante vs background). ADVERTENCIA HONESTA: este producto NO tiene
+# core; NO hay gates de scope/consentimiento/audit antes de ejecutar.
+KALI_RUN_TOOL_NAME = "kali_run"
+
+# 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="/")
+
+
+def _prowler_binary() -> str | None:
+ """Devuelve la ruta del binario `prowler` si está disponible, o None.
+
+ No se finge disponibilidad (design.md 4.4): si no está, quien llame lo reporta.
+ """
+ return shutil.which("prowler")
+
+
+def server_info() -> dict[str, Any]:
+ """Operación SEGURA y NO intrusiva para el smoke test (R3.2).
+
+ No toca AWS ni ejecuta herramientas: solo informa del estado del runtime
+ (arquitectura, si Prowler está presente y su versión). El cliente usa el
+ *listado de tools* como smoke test principal; esta tool añade un chequeo
+ seguro adicional si se quiere invocar.
+ """
+ prowler_path = _prowler_binary()
+ version = None
+ if prowler_path:
+ try:
+ proc = subprocess.run( # noqa: S603 - binario fijo, sin input de usuario
+ [prowler_path, "--version"],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ version = (proc.stdout or proc.stderr).strip() or None
+ except Exception: # noqa: BLE001 - informativo, no fatal
+ version = None
+ # Disponibilidad REAL por collector (which de prowler/scout/cloudsplaining); no se
+ # finge en arm64 (R3.2/4.4): lo que no esté se reporta ausente y su collection falla
+ # claro en el core.
+ collectors = collector_runner.available_collectors()
+ return {
+ "server": "kali-mcp",
+ "machine": os.uname().machine,
+ "prowler_available": prowler_path is not None,
+ "prowler_version": version,
+ "collectors": collectors,
+ "tools": [
+ PROWLER_TOOL_NAME,
+ START_COLLECTION_TOOL_NAME,
+ SCAN_STATUS_TOOL_NAME,
+ READ_LOGS_TOOL_NAME,
+ READ_FINDINGS_TOOL_NAME,
+ CANCEL_SCAN_TOOL_NAME,
+ IAM_ENUM_TOOL_NAME,
+ IAM_SIMULATE_TOOL_NAME,
+ KALI_EXEC_TOOL_NAME,
+ KALI_RUN_TOOL_NAME,
+ "server_info",
+ ],
+ }
+
+
[email protected](name=READ_LOGS_TOOL_NAME)
+def read_tool_logs(execution_id: str, cursor: int = 0) -> dict[str, Any]:
+ """Lee incrementalmente la salida (stdout/stderr) de una ejecución de tool.
+
+ Pensada para verbose en vivo: el cliente llama repetidamente avanzando
+ `cursor` (el `next_cursor` de la respuesta anterior) y recibe sólo las líneas
+ nuevas. La salida es DATO NO CONFIABLE: se transporta verbatim, nunca se
+ interpreta.
+
+ Args:
+ execution_id: id de la ejecución (el pasado/devuelto por `prowler_scan`).
+ cursor: último `seq` ya consumido; 0 para leer desde el principio.
+
+ Returns:
+ {"lines": [{seq, ts, stream, text}, ...], "next_cursor": int, "done": bool}.
+ Un `execution_id` desconocido devuelve página vacía con done=False.
+ """
+ return tool_streaming.read(execution_id, cursor)
+
+
[email protected](name=READ_FINDINGS_TOOL_NAME)
+def read_scan_findings(
+ execution_id: str, cursor: int = 0, limit: int | None = None
+) -> dict[str, Any]:
+ """Lee PAGINADOS los findings de un escaneo terminado por `prowler_scan`.
+
+ Existe para no superar el límite de 1 MiB de un único evento SSE del transporte
+ streamable-http: con datos reales (iam+s3) la lista completa de findings OCSF
+ supera ese tope si se entrega inline. El cliente llama repetidamente avanzando
+ `cursor` (el `next_cursor` de la respuesta anterior) hasta `done=True` y
+ reconstruye la lista completa. Cada página va MUY por debajo de 1 MiB.
+
+ Los findings son DATO NO CONFIABLE: se transportan verbatim, nunca se interpretan.
+
+ Args:
+ execution_id: id de la ejecución (el devuelto por `prowler_scan`).
+ cursor: índice 0-based del primer finding a devolver; 0 desde el principio.
+ limit: tope opcional de findings por página (el servidor aplica además un
+ tope de bytes prudente; manda el menor).
+
+ Returns:
+ {"findings": [...página...], "next_cursor": int, "done": bool}. Un
+ `execution_id` desconocido o un `cursor` en/más allá del final devuelve
+ página vacía con done=True.
+ """
+ return tool_streaming.read_findings(execution_id, cursor, limit)
+
+
+def _start_collection_background(
+ source: str, account_id: str, params: str, execution_id: str
+) -> dict[str, Any]:
+ """Arranca una collection EN VIVO en background y devuelve de inmediato (N33).
+
+ Lógica compartida por ``start_collection`` y el alias ``prowler_scan``: genera un
+ ``execution_id`` si falta, lanza el worker genérico del ``collector_runner`` en un hilo
+ demonio (``tool_streaming.start_background``) y retorna ``{execution_id, status:'started'}``
+ en <2s. El worker (``collector_runner.run_collection``) valida el binario (no finge en
+ arm64), ejecuta con streaming de logs, stagea el crudo como artefacto y construye el
+ ``done`` con la REFERENCIA. Las excepciones del worker (tool ausente) las convierte
+ ``start_background`` en ``{'status':'failed','error':...}``.
+ """
+ execution_id = execution_id or uuid.uuid4().hex
+ # Prowler conserva su timeout histórico; las demás usan el de collection genérico.
+ timeout = PROWLER_TIMEOUT if source == "prowler" else collector_runner.DEFAULT_TIMEOUT
+ tool_streaming.start_background(
+ execution_id,
+ lambda: collector_runner.run_collection(
+ source, account_id, execution_id, params, timeout
+ ),
+ )
+ return {"execution_id": execution_id, "status": "started"}
+
+
[email protected](name=START_COLLECTION_TOOL_NAME)
+def start_collection(
+ source: str = "prowler",
+ account_id: str = "",
+ params: str = "",
+ execution_id: str = "",
+) -> dict[str, Any]:
+ """Arranca una collection EN VIVO con la tool elegida (read-only) y DEVUELVE ya (N33).
+
+ Multi-herramienta bajo el MISMO contrato no-bloqueante que ``prowler_scan``: ``source``
+ ∈ {prowler, scoutsuite, cloudsplaining}. Determinista (corre el binario real, NO el
+ LLM); credenciales AWS read-only del entorno del contenedor; el scope ya lo valida
+ PentAgent (scope-guard fail-closed) ANTES de llamar. El escaneo corre en background
+ (``execution_id``); el cliente sondea con ``get_scan_status`` y lee logs con
+ ``read_tool_logs``. El crudo se deposita en la capa de artefactos (plano de DATOS); el
+ ``done`` sólo lleva la REFERENCIA. Si la tool no está disponible en esta arquitectura,
+ la ejecución termina en ``failed`` con el motivo (no se finge).
+
+ Args:
+ source: tool a lanzar (``prowler`` por defecto, compat).
+ account_id: cuenta AWS autorizada (target).
+ params: parámetros extra opcionales (JSON string); reservado.
+ execution_id: id para seguir salida/estado en vivo; si falta se genera.
+
+ Returns:
+ {'execution_id': str, 'status': 'started'} de inmediato (<2s).
+ """
+ return _start_collection_background(source, account_id, params, execution_id)
+
+
[email protected](name=PROWLER_TOOL_NAME)
+def prowler_scan(
+ account_id: str, output_format: str = "json-ocsf", execution_id: str = ""
+) -> dict[str, Any]:
+ """Alias de ``start_collection(source='prowler')`` (compat con clientes existentes).
+
+ Arranca un escaneo Prowler (read-only) en segundo plano y devuelve en <2s con
+ ``{'execution_id','status':'started'}``. Es DELEGACIÓN, no una copia: usa el mismo
+ worker/finalize genérico (``collector_runner``) y, para Prowler, el mismo
+ ``prowler_artifact`` (stage + puente SSE de compat). ``output_format`` se acepta por
+ contrato; el formato efectivo es OCSF.
+ """
+ # output_format se acepta por contrato pero no afecta (Prowler siempre OCSF); params
+ # vacío (el builder de Prowler no usa params).
+ return _start_collection_background("prowler", account_id, "", execution_id)
+
+
[email protected](name=SCAN_STATUS_TOOL_NAME)
+def get_scan_status(execution_id: str) -> dict[str, Any]:
+ """Sondea el estado de un escaneo lanzado por `prowler_scan`.
+
+ Returns el dict de estado por `execution_id`:
+ - {'status':'running'} mientras el worker corre.
+ - {'status':'done','returncode':int,'timed_out':False,'findings_count':int,
+ 'artifact':{execution_id,name,size,sha256,findings_count}} al OK. Los findings
+ NO viajan inline (reventaría el límite de 1 MiB del evento SSE con datos
+ reales): el core baja el artefacto CRUDO por el plano de DATOS (HTTP chunked)
+ usando la REFERENCIA `artifact`. Puente de compat (N21): si no hay `artifact`
+ (staging falló o kali antigua) se recuperan paginados con `read_scan_findings`.
+ - {'status':'failed','returncode'?:int,'timed_out'?:bool,'error':str} si falla
+ el worker o hay timeout.
+ - {'status':'unknown'} si el execution_id no existe (no revienta).
+
+ `error` es DATO NO CONFIABLE: se transporta verbatim.
+ """
+ return tool_streaming.get_status(execution_id)
+
+
[email protected](name=CANCEL_SCAN_TOOL_NAME)
+def cancel_scan(execution_id: str) -> dict[str, Any]:
+ """Cancela un escaneo en curso lanzado por `prowler_scan` (N22.2).
+
+ Mata el GRUPO de procesos del escaneo por `execution_id` (reutiliza el kill
+ SIGTERM->SIGKILL ya existente, sin huérfanos — N18.3) y marca la cancelación. Es
+ una tool interna kali<->core: la invoca el core (CoreServices.cancel_phase) cuando
+ el usuario para una fase; NO ejecuta nada contra AWS.
+
+ Returns:
+ {'execution_id': str, 'status': 'cancelling'|'not_running'}. 'cancelling' si
+ había un proceso vivo al que se le pidió el kill; 'not_running' si no (ya
+ terminó o nunca arrancó). El worker publicará el estado terminal 'cancelled'
+ vía `get_scan_status` cuando el proceso muera.
+ """
+ killed = tool_streaming.request_cancel(execution_id)
+ return {
+ "execution_id": execution_id,
+ "status": "cancelling" if killed else "not_running",
+ }
+
+
[email protected](name=IAM_ENUM_TOOL_NAME)
+def iam_enum(
+ account_id: str, params: str = "", execution_id: str = ""
+) -> dict[str, Any]:
+ """Enum IAM read-only ACOTADO de la cuenta AWS autorizada (runner del foso, F2).
+
+ Tool del bucle OODA (ACTIVE_SAFE; el gate de intrusividad del core la autoriza, no se
+ autoriza a sí misma): el scope ya lo validó PentAgent ANTES de llamar. Es NO BLOQUEANTE,
+ EXACTAMENTE como ``start_collection``: lanza ``aws_exec.run_iam_enum`` en un hilo demonio
+ con ``tool_streaming.start_background`` y DEVUELVE en <2s con
+ ``{'execution_id','status':'started'}``; así el enum (p. ej. 153 roles) NO retiene el
+ hilo de petición del servidor ni impide responder el healthcheck. El cliente sondea con
+ ``get_scan_status`` (devuelve el dict terminal del worker) y lee la salida en vivo con
+ ``read_tool_logs`` (ambas por ``execution_id``). El worker valida ``account_id``
+ fail-closed, ejecuta ``aws_iam_enum.py`` con streaming de logs y kill de grupo/timeout
+ (``tool_streaming``) y lee la salida de FICHERO; su documento único (el JSON crudo del
+ enum, inline en ``output``) lo stagea el EXECUTOR del core en el plano de DATOS, por eso
+ aquí NO se stagea artefacto.
+
+ READ-ONLY: ``aws_iam_enum.py`` solo usa ``list_*``/``get_*``; NUNCA cambia estado AWS.
+
+ Args:
+ account_id: cuenta AWS autorizada (12 dígitos); se valida fail-closed (en el worker).
+ params: parámetros extra opcionales (JSON string); reservado.
+ execution_id: id para sondear estado (``get_scan_status``) y seguir la salida en vivo
+ (``read_tool_logs``); si falta se genera.
+
+ Returns:
+ {'execution_id': str, 'status': 'started'} de inmediato (<2s). El veredicto terminal
+ del worker ({'status':'done','returncode':int,'output':<json-string crudo del enum>}
+ o {'status':'failed','returncode':int,'error':str} o {'status':'cancelled',...}) se
+ obtiene por ``get_scan_status``. ``output`` y ``error`` son DATO NO CONFIABLE (se
+ transportan verbatim).
+ """
+ execution_id = execution_id or uuid.uuid4().hex
+ tool_streaming.start_background(
+ execution_id,
+ lambda: aws_exec.run_iam_enum(
+ account_id, params, execution_id, aws_exec.DEFAULT_TIMEOUT
+ ),
+ )
+ return {"execution_id": execution_id, "status": "started"}
+
+
[email protected](name=IAM_SIMULATE_TOOL_NAME)
+def iam_simulate(
+ account_id: str, principal_arn: str, execution_id: str = ""
+) -> dict[str, Any]:
+ """Simula permisos efectivos de privesc de un principal IAM (runner del foso, inc4b).
+
+ Tool del bucle OODA (ACTIVE_SAFE; el gate de intrusividad del core la autoriza, no se
+ autoriza a sí misma): el scope ya lo validó PentAgent ANTES de llamar. Dado el ARN de un
+ principal de un candidato alcanzable, usa ``iam:SimulatePrincipalPolicy`` (API AWS
+ READ-ONLY: NO modifica estado) para comprobar si ese principal PUEDE ejecutar un conjunto
+ FIJO de acciones de privesc clásicas. Es NO BLOQUEANTE, EXACTAMENTE como ``iam_enum``: lanza
+ ``aws_simulate.run_iam_simulate`` en un hilo demonio con ``tool_streaming.start_background``
+ y DEVUELVE en <2s con ``{'execution_id','status':'started'}``; así no retiene el hilo de
+ petición del servidor ni impide responder el healthcheck. El cliente sondea con
+ ``get_scan_status`` (devuelve el dict terminal del worker) y lee la salida en vivo con
+ ``read_tool_logs`` (ambas por ``execution_id``). El worker valida ``account_id`` Y
+ ``principal_arn`` fail-closed, ejecuta ``aws_iam_simulate.py`` con streaming de logs y kill
+ de grupo/timeout (``tool_streaming``) y lee la salida de FICHERO; su documento único (el JSON
+ crudo del simulate, inline en ``output``) lo stagea el EXECUTOR del core en el plano de
+ DATOS, por eso aquí NO se stagea artefacto.
+
+ READ-ONLY: ``SimulatePrincipalPolicy`` SIMULA la evaluación; NUNCA cambia estado AWS.
+
+ Args:
+ account_id: cuenta AWS autorizada (12 dígitos); se valida fail-closed (en el worker).
+ principal_arn: ARN del principal IAM a simular (PolicySourceArn); se valida fail-closed.
+ execution_id: id para sondear estado (``get_scan_status``) y seguir la salida en vivo
+ (``read_tool_logs``); si falta se genera.
+
+ Returns:
+ {'execution_id': str, 'status': 'started'} de inmediato (<2s). El veredicto terminal del
+ worker ({'status':'done','returncode':int,'output':<json-string crudo del simulate>} o
+ {'status':'failed','returncode':int,'error':str} o {'status':'cancelled',...}) se obtiene
+ por ``get_scan_status``. ``output`` y ``error`` son DATO NO CONFIABLE (verbatim).
+ """
+ execution_id = execution_id or uuid.uuid4().hex
+ tool_streaming.start_background(
+ execution_id,
+ lambda: aws_simulate.run_iam_simulate(
+ account_id, principal_arn, execution_id, aws_simulate.DEFAULT_TIMEOUT
+ ),
+ )
+ return {"execution_id": execution_id, "status": "started"}
+
+
[email protected](name=KALI_EXEC_TOOL_NAME)
+def kali_exec(
+ command: str, execution_id: str = "", timeout: int = 0
+) -> dict[str, Any]:
+ """Ejecuta un comando ARBITRARIO de SHELL en la Kali (shell cruda completa).
+
+ A diferencia de los runners deterministas y acotados (``iam_enum``/``iam_simulate``/
+ ``prowler_scan``), esta tool da al bucle OODA una Kali COMPLETA: corre ``command`` tal
+ cual vía ``sh -c``, de modo que el conductor pueda encadenar con pipes/redirecciones,
+ escribir y ejecutar sus propios scripts, e invocar cualquier herramienta instalada en
+ la imagen Kali. NO restringe el contenido del comando (es shell cruda por decisión del
+ operador).
+
+ AUTORIZACIÓN: NO vive aquí. El scope, el consentimiento y la auditoría los aplica el
+ CORE de PentAgent ANTES de invocar esta tool (el bucle OODA llega por ``execute_step``
+ -> executor del core -> ``McpToolExecutor.invoke`` bajo scope-guard + gate de
+ intrusividad + audit). Esta tool solo EJECUTA lo que el core ya autorizó. En
+ ``config/mcp-servers.yaml`` su registro declara el nivel de intrusividad que el gate
+ del core gobierna.
+
+ NO BLOQUEANTE, EXACTAMENTE como los demás runners: lanza ``shell_exec.run_shell`` en un
+ hilo demonio con ``tool_streaming.start_background`` y DEVUELVE en <2s con
+ ``{'execution_id','status':'started'}``; así un comando largo (p. ej. un escaneo nmap)
+ NO retiene el hilo de petición del servidor ni impide responder el healthcheck. El
+ cliente sondea con ``get_scan_status`` (dict terminal del worker) y lee la salida en
+ vivo con ``read_tool_logs`` (ambas por ``execution_id``). El comando corre en un tmpdir
+ de trabajo efímero (aislado, se limpia al terminar).
+
+ Args:
+ command: comando de shell a ejecutar (string no vacío; se valida fail-closed en el
+ worker). Dato NO confiable: se transporta/ejecuta verbatim.
+ execution_id: id para sondear estado (``get_scan_status``) y seguir la salida en vivo
+ (``read_tool_logs``); si falta se genera.
+ timeout: timeout en segundos; 0 (o ausente) usa el default del runner
+ (``shell_exec.DEFAULT_TIMEOUT``, overridable por ``KALI_EXEC_TIMEOUT``).
+
+ Returns:
+ {'execution_id': str, 'status': 'started'} de inmediato (<2s). El veredicto terminal
+ del worker ({'status':'done','returncode':int,'output':<stdout+stderr verbatim>} o
+ {'status':'failed',...} o {'status':'cancelled',...}) se obtiene por
+ ``get_scan_status``. Un ``returncode`` != 0 es resultado legítimo del comando (no un
+ fallo del runner). ``output`` y ``error`` son DATO NO CONFIABLE (verbatim).
+ """
+ execution_id = execution_id or uuid.uuid4().hex
+ effective_timeout = timeout if timeout and timeout > 0 else shell_exec.DEFAULT_TIMEOUT
+ tool_streaming.start_background(
+ execution_id,
+ lambda: shell_exec.run_shell(command, execution_id, effective_timeout),
+ )
+ return {"execution_id": execution_id, "status": "started"}
+
+
[email protected](name=KALI_RUN_TOOL_NAME)
+def kali_run(command: str, timeout: int = 0) -> dict[str, Any]:
+ """Ejecuta un comando ARBITRARIO de shell en la Kali y DEVUELVE su salida completa.
+
+ Variante BLOQUEANTE de ``kali_exec``: en lugar de lanzar en background y obligar al
+ conductor a sondear (``started`` -> ``get_scan_status`` -> ``read_tool_logs``), esta
+ tool corre ``command`` vía ``sh -c`` y espera a que termine, DEVOLVIENDO la salida
+ completa en UNA sola llamada (acotada por ``timeout``). Así Hermes la usa como una tool
+ normal (petición -> respuesta) sin orquestar el patrón de polling.
+
+ Reutiliza el MISMO runner que ``kali_exec`` (``shell_exec.run_shell``): NO duplica
+ lógica ni usa ``tool_streaming.start_background``; solo cambia la forma de entrega
+ (bloqueante). No revalida ``command`` aquí (``run_shell`` ya lo hace fail-closed).
+
+ ADVERTENCIA HONESTA: este producto NO tiene core. NO hay gates de scope,
+ consentimiento ni auditoría ANTES de ejecutar. El comando corre tal cual contra la
+ Kali. ``command`` y su salida son DATO NO CONFIABLE: se transportan/ejecutan verbatim,
+ nunca se interpretan. Un ``returncode`` != 0 es resultado LEGÍTIMO del comando (p. ej.
+ nmap sin hallazgos, grep sin match), no un fallo del runner.
+
+ Args:
+ command: comando de shell a ejecutar (string no vacío; se valida fail-closed en el
+ worker). Dato NO confiable: se ejecuta verbatim.
+ timeout: timeout en segundos; 0 (o ausente) usa el default del runner
+ (``shell_exec.DEFAULT_TIMEOUT``, overridable por ``KALI_EXEC_TIMEOUT``).
+
+ Returns:
+ El dict TERMINAL del runner en la misma llamada:
+ {'status':'done','returncode':int,'output':<stdout+stderr verbatim>} si terminó;
+ {'status':'failed','timed_out':True,...} en timeout;
+ {'status':'cancelled',...} si se canceló;
+ {'status':'failed','returncode':-1,'error':...} si ``command`` es inválido.
+ """
+ execution_id = uuid.uuid4().hex
+ effective_timeout = timeout if timeout and timeout > 0 else shell_exec.DEFAULT_TIMEOUT
+ return shell_exec.run_shell(command, execution_id, effective_timeout)
+
+
+def _start_artifacts_http() -> None:
+ """Arranca el servidor HTTP de artefactos (plano de DATOS) en un hilo demonio.
+
+ Fail-closed (R14.3): sin ``KALI_ARTIFACTS_TOKEN`` NO se arranca el canal de datos
+ (evita un endpoint abierto a dato potencialmente sensible); el core cae entonces
+ al puente ``read_scan_findings``. Es best-effort respecto al proceso principal:
+ cualquier fallo al abrir el socket se reporta por stdout y NO impide servir MCP.
+ """
+ if not ARTIFACTS_TOKEN:
+ print(
+ "[kali-mcp] KALI_ARTIFACTS_TOKEN vacío: servidor de artefactos NO "
+ "arrancado (fail-closed); el core usará el puente read_scan_findings.",
+ flush=True,
+ )
+ return
+ try:
+ artifact_http.serve_in_thread(ARTIFACTS_HOST, ARTIFACTS_PORT, ARTIFACTS_TOKEN)
+ print(
+ f"[kali-mcp] servidor de artefactos (plano de datos) en "
+ f"{ARTIFACTS_HOST}:{ARTIFACTS_PORT}",
+ flush=True,
+ )
+ except Exception as exc: # noqa: BLE001 - no debe impedir arrancar MCP
+ print(f"[kali-mcp] no se pudo arrancar el servidor de artefactos: {exc}", flush=True)
+
+
+if __name__ == "__main__":
+ # Plano de DATOS primero (hilo demonio, no bloquea), luego el plano de CONTROL.
+ _start_artifacts_http()
+ # Transporte streamable-HTTP (el que consume KaliMcpClient por defecto).
+ mcp.run(transport="streamable-http")
diff --git a/docker/kali/prowler_artifact.py b/docker/kali/prowler_artifact.py
new file mode 100644
index 0000000..057ccdf
--- /dev/null
+++ b/docker/kali/prowler_artifact.py
@@ -0,0 +1,131 @@
+"""Finalización del escaneo Prowler: salida cruda -> artefacto + puente (STDLIB PURA).
+
+Vive aparte de ``kali_mcp_server.py`` (que importa ``mcp``/``anyio``, no instalados en
+el venv de dev) para poder cubrir con tests el camino post-escaneo SIN el SDK, igual
+que ``tool_streaming.py``/``artifact_store.py``.
+
+Qué hace al terminar un escaneo (architecture §5, pasos 5-6):
+ 1. Localiza y lee el fichero OCSF/JSON crudo que Prowler escribió en ``outdir``.
+ 2. **Puente de compat (N21):** guarda los findings paginables con
+ ``tool_streaming.set_findings`` para que ``read_scan_findings`` siga sirviéndolos
+ si el core es antiguo o no tiene configurado el plano de datos.
+ 3. **Plano de DATOS (N23):** stagea el fichero CRUDO como artefacto
+ (``artifact_store.put_file``) y construye el ``done`` del control con una
+ **referencia** (``artifact``) pequeña — NUNCA los findings inline.
+
+El crudo es DATO NO CONFIABLE: se transporta verbatim, no se interpreta más allá de
+contar los findings para el resumen de control.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+import artifact_store
+import tool_streaming
+
+# Nombre canónico del artefacto crudo de Prowler dentro del staging/almacén.
+PROWLER_ARTIFACT_NAME = "prowler.ocsf.json"
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def read_prowler_output(outdir: Path) -> tuple[Path | None, list[dict] | None]:
+ """Devuelve ``(path, findings)`` del fichero OCSF/JSON más reciente y legible.
+
+ Un solo parse por candidato (eficiente con ficheros grandes): en cuanto uno
+ parsea, se devuelve su ruta y la lista de findings extraída. Si ninguno es
+ legible, ``(None, None)`` (el caller lo trata como escaneo sin salida válida).
+ """
+ candidates = sorted(
+ [*outdir.rglob("*.ocsf.json"), *outdir.rglob("*.json")],
+ key=lambda p: p.stat().st_mtime if p.exists() else 0,
+ reverse=True,
+ )
+ for path in candidates:
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ if isinstance(data, list):
+ return path, data
+ if isinstance(data, dict):
+ for key in ("findings", "results", "data"):
+ if isinstance(data.get(key), list):
+ return path, data[key]
+ return path, [data]
+ return None, None
+
+
+def _stage_artifact(
+ execution_id: str,
+ path: Path,
+ returncode: int,
+ params: dict[str, Any],
+ findings_count: int,
+) -> dict[str, Any] | None:
+ """Stagea el fichero crudo como artefacto y devuelve la ref para el ``done``.
+
+ Best-effort: si el staging falla (p. ej. FS no escribible), devuelve ``None`` y el
+ worker publica el ``done`` sin ``artifact`` ref — el core cae entonces al puente
+ ``read_scan_findings`` (compat). El plano de datos no debe tumbar el escaneo.
+ """
+ meta = {
+ "tool": "prowler",
+ "phase": "collection",
+ "params": dict(params),
+ "ts": _now_iso(),
+ "returncode": returncode,
+ "status": "done",
+ }
+ try:
+ entry = artifact_store.put_file(
+ execution_id, PROWLER_ARTIFACT_NAME, path, meta
+ )
+ except Exception: # noqa: BLE001 - staging best-effort; el puente cubre el fallo
+ return None
+ return {
+ "execution_id": execution_id,
+ "name": PROWLER_ARTIFACT_NAME,
+ "size": entry["size"],
+ "sha256": entry["sha256"],
+ "findings_count": findings_count,
+ }
+
+
+def finalize_scan(
+ execution_id: str,
+ outdir: Path,
+ returncode: int,
+ params: dict[str, Any],
+) -> dict[str, Any] | None:
+ """Construye el estado ``done`` del escaneo: puente + artefacto por referencia.
+
+ Devuelve el dict ``done`` que ``get_scan_status`` publicará:
+ ``{status:'done', returncode, timed_out:False, findings_count, artifact?}``.
+ El canal de CONTROL lleva SÓLO ese resumen + la ref ``artifact`` (pequeña); los
+ findings NO viajan inline. Si no hay salida legible, devuelve ``None`` (el caller
+ publica ``failed`` con diagnóstico).
+ """
+ path, findings = read_prowler_output(outdir)
+ if findings is None or path is None:
+ return None
+
+ # Puente de compat (N21): findings paginables disponibles ANTES de publicar done.
+ tool_streaming.set_findings(execution_id, findings)
+
+ done: dict[str, Any] = {
+ "status": "done",
+ "returncode": returncode,
+ "timed_out": False,
+ "findings_count": len(findings),
+ }
+ artifact = _stage_artifact(execution_id, path, returncode, params, len(findings))
+ if artifact is not None:
+ done["artifact"] = artifact
+ return done
diff --git a/docker/kali/requirements.txt b/docker/kali/requirements.txt
new file mode 100644
index 0000000..034404a
--- /dev/null
+++ b/docker/kali/requirements.txt
@@ -0,0 +1,34 @@
+# Manifiesto de dependencias de la imagen Kali de PentAgent (F0.7 — un manifiesto
+# por paquete, sincronizado). Este archivo es la fuente de verdad de lo que se
+# instala con pip en la imagen docker/kali/Dockerfile.
+#
+# Prowler: runtime determinista de recolección de postura AWS (read-only).
+# Paquete Python puro -> compatible arm64 y amd64. Requiere Python >=3.10,<3.14
+# (por eso la imagen usa un venv de Python 3.13; ver Dockerfile).
+# Versión fijada para reproducibilidad del runtime determinista.
+prowler==5.44.0
+
+# SDK oficial de MCP (modelcontextprotocol/python-sdk). Lo usa el SERVIDOR
+# kali-mcp (docker/kali/kali_mcp_server.py: FastMCP + transporte streamable-HTTP)
+# que corre dentro del contenedor y que pentagent-core consume como cliente.
+#
+# Se fija a la línea 1.x (<2) a propósito: el cliente de pentagent-core usa la
+# API 1.x (`mcp.client.streamable_http.streamablehttp_client`, `ClientSession`),
+# que v2 renombra/elimina. Mantener ambos lados en la misma era de protocolo
+# evita un desajuste cliente/servidor. Ver pentagent_core/tools/kali_mcp.py.
+mcp>=1.28,<2
+
+# anyio: dependencia del transporte asíncrono del SDK mcp (streamable-HTTP).
+anyio>=4
+
+# ScoutSuite y Cloudsplaining (fuentes de collection EN VIVO adicionales, N33/N32) NO van
+# aquí: se instalan AISLADAS con pipx (venv propio por herramienta) en el Dockerfile.
+#
+# Motivo (causa raíz, verificada): kali-mcp invoca estas tools como SUBPROCESOS (argv), NO
+# las importa como librerías; meterlas en el MISMO venv que Prowler rompe la resolución de
+# dependencias — p. ej. prowler fija `python-dateutil==2.9.0.post0` y ScoutSuite exige
+# `python-dateutil<2.8.1`, conflicto irreconciliable que tumbaría el build entero. Aislar
+# cada tool (patrón correcto para ejecutables independientes) elimina el acoplamiento
+# artificial "todas en un venv" (architecture-first: límites que escalan, no se fuerzan).
+# La disciplina fail-closed se mantiene: si una tool no instala/arranca, server_info la
+# reporta ausente y su collection falla claro (R3.2/4.4). Ver docker/kali/Dockerfile.
diff --git a/docker/kali/shell_exec.py b/docker/kali/shell_exec.py
new file mode 100644
index 0000000..b05ec06
--- /dev/null
+++ b/docker/kali/shell_exec.py
@@ -0,0 +1,141 @@
+"""Runner de SHELL CRUDA de la Kali (STDLIB PURA) — ejecuta un comando arbitrario.
+
+Rol (architecture §1/§5): es la LÓGICA testeable del runner ``kali_exec`` que expone
+``kali_mcp_server`` como ``@mcp.tool`` NO BLOQUEANTE. Igual que ``aws_exec`` /
+``collector_runner`` / ``tool_streaming``, vive en un módulo aparte que usa SOLO la
+librería estándar (sin ``mcp``) para poder cubrirse con tests unitarios en el venv de
+dev, donde el SDK no está instalado.
+
+Qué es (decisión del operador): a diferencia de los runners deterministas y acotados
+(``iam_enum``/``iam_simulate``/``prowler``), ``kali_exec`` da al bucle OODA una SHELL
+CRUDA COMPLETA de la Kali: ejecuta el comando TAL CUAL vía ``sh -c``, de modo que el
+conductor pueda encadenar con pipes, redirecciones, escribir y correr sus propios
+scripts, invocar cualquier herramienta instalada en la imagen Kali, etc. NO valida ni
+restringe el comando: es intencionadamente genérico (shell cruda).
+
+Guardarraíles que NO desaparecen (importante): la autorización NO vive aquí. El scope,
+el consentimiento y la auditoría los sigue aplicando el CORE de PentAgent ANTES de que
+esta tool se invoque (el bucle OODA llega por ``execute_step`` -> executor del core ->
+``McpToolExecutor.invoke`` bajo scope-guard + gate de intrusividad + audit). Este módulo
+solo EJECUTA lo que el core ya autorizó. El comando y su salida son DATO NO CONFIABLE
+(F0.8): se transportan verbatim, nunca se interpreta la salida.
+
+Flujo (igual que ``aws_exec``, patrón no-bloqueante del servidor): ``run_shell`` crea un
+tmpdir de trabajo efímero, ejecuta ``sh -c <command>`` con
+``tool_streaming.run_tool_streaming`` (kill de grupo/timeout, logs al ring por
+``execution_id``) y devuelve ``{'status':'done','returncode':rc,'output':<stdout+stderr
+del ring>}`` o ``{'status':'failed'...}``/``{'status':'cancelled'...}``. El cliente lanza
+en background con ``start_background`` y sondea con ``get_scan_status`` / ``read_tool_logs``.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import tempfile
+from typing import Any
+
+import tool_streaming
+
+# Timeout por defecto de un comando de shell (segundos). Un comando interactivo o
+# colgado no debe retener el runner indefinidamente; se acota y se puede subir por
+# entorno o por el parámetro ``timeout`` de la tool.
+DEFAULT_TIMEOUT = int(os.environ.get("KALI_EXEC_TIMEOUT", "600"))
+
+
+class ShellExecError(ValueError):
+ """Entrada inválida para el runner de shell (fail-closed; no se ejecuta nada)."""
+
+
+def _validate_command(command: Any) -> str:
+ """Valida que ``command`` sea un string no vacío, o lanza ``ShellExecError``.
+
+ NO restringe el CONTENIDO del comando (es shell cruda por decisión del operador):
+ solo rechaza fail-closed lo que no es un comando ejecutable (no-string o vacío),
+ para no lanzar un ``sh -c`` sin sentido.
+ """
+ if not isinstance(command, str) or not command.strip():
+ raise ShellExecError(
+ "command inválido: se espera una cadena de shell no vacía."
+ )
+ return command
+
+
+def _ring_tail(execution_id: str, max_lines: int = 50) -> str:
+ """Últimas líneas de salida de la ejecución (dato NO confiable, verbatim)."""
+ page = tool_streaming.read(execution_id, 0)
+ lines = page.get("lines", [])
+ tail = lines[-max_lines:]
+ return "\n".join(f"[{line['stream']}] {line['text']}" for line in tail)
+
+
+def _ring_output(execution_id: str) -> str:
+ """Salida COMPLETA acumulada en el ring (stdout+stderr), verbatim.
+
+ A diferencia de ``aws_exec`` (que lee un fichero de salida estructurado), la shell
+ cruda no produce un documento fijo: su resultado ES su stdout/stderr. Se devuelve el
+ contenido del ring como ``output`` para que el executor del core lo stagee en el
+ plano de DATOS. Dato NO confiable: verbatim, nunca interpretado.
+ """
+ page = tool_streaming.read(execution_id, 0)
+ lines = page.get("lines", [])
+ return "\n".join(f"[{line['stream']}] {line['text']}" for line in lines)
+
+
+def run_shell(
+ command: str,
+ execution_id: str = "",
+ timeout: int = DEFAULT_TIMEOUT,
+) -> dict[str, Any]:
+ """Ejecuta ``command`` como SHELL CRUDA (``sh -c``) y devuelve su salida.
+
+ Flujo: valida ``command`` (string no vacío, fail-closed) -> crea un tmpdir efímero de
+ trabajo -> ejecuta ``["sh", "-c", command]`` con ``tool_streaming.run_tool_streaming``
+ (kill de grupo/timeout, logs al ring por ``execution_id``) -> devuelve el estado
+ terminal. ``cwd`` es el tmpdir, así que los ficheros/scripts que el comando cree
+ quedan aislados y se limpian en ``finally``.
+
+ Returns:
+ - ``{'status':'done','returncode':rc,'output':<salida verbatim del ring>}`` si el
+ comando terminó (``rc`` puede ser != 0: un comando que falla NO es un error del
+ runner; su returncode y salida son información válida para el bucle OODA).
+ - ``{'status':'failed','timed_out':True,'returncode':rc,'error':...}`` en timeout.
+ - ``{'status':'cancelled','cancelled':True,'returncode':rc}`` si se canceló.
+ - ``{'status':'failed','returncode':-1,'error':...}`` si ``command`` es inválido.
+
+ ``output`` y ``error`` son DATO NO CONFIABLE (verbatim). El JSON/salida crudos los
+ stagea el EXECUTOR del core en el plano de DATOS; aquí NO se stagea artefacto.
+ """
+ try:
+ cmd_str = _validate_command(command)
+ except ShellExecError as exc:
+ return {"status": "failed", "returncode": -1, "error": str(exc)}
+
+ workdir = tempfile.mkdtemp(prefix="kali-exec-")
+ try:
+ cmd = ["sh", "-c", cmd_str]
+ returncode, timed_out, cancelled = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=timeout, cwd=workdir
+ )
+ if cancelled:
+ return {"status": "cancelled", "cancelled": True, "returncode": returncode}
+ if timed_out:
+ return {
+ "status": "failed",
+ "timed_out": True,
+ "returncode": returncode,
+ "error": (
+ f"kali_exec excedió el timeout ({timeout}s). "
+ f"Últimas líneas: {_ring_tail(execution_id)}"
+ ),
+ }
+ # Un returncode != 0 NO es fallo del runner: es resultado legítimo del comando
+ # (p. ej. nmap sin hallazgos, grep sin match). Se devuelve 'done' con la salida
+ # y el returncode para que el bucle OODA razone sobre él.
+ return {
+ "status": "done",
+ "returncode": returncode,
+ "output": _ring_output(execution_id),
+ }
+ finally:
+ shutil.rmtree(workdir, ignore_errors=True)
diff --git a/docker/kali/tests/__init__.py b/docker/kali/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/docker/kali/tests/test_artifact_http.py b/docker/kali/tests/test_artifact_http.py
new file mode 100644
index 0000000..e00bb35
--- /dev/null
+++ b/docker/kali/tests/test_artifact_http.py
@@ -0,0 +1,135 @@
+"""Tests stdlib-only del servidor HTTP de artefactos (`docker/kali/artifact_http.py`).
+
+Arranca el server en un puerto efímero en un hilo y lo ejercita con `urllib.request`
+(stdlib). Verifica: GET con token -> 200 + bytes idénticos (incl. un blob > 1 MiB por
+el stream chunked), 403 sin token, 400 ante traversal, 404 si no existe, y fail-closed
+si se intenta arrancar sin token.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import sys
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+import pytest
+
+# Los módulos bajo prueba viven en docker/kali/ (no importan `mcp`/`anyio`).
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import artifact_http # noqa: E402
+import artifact_store # noqa: E402
+
+_TOKEN = "test-shared-token"
+
+
+def server(tmp_path, monkeypatch):
+ """Staging en tmp + servidor HTTP en puerto efímero; se cierra al terminar."""
+ monkeypatch.setenv("KALI_ARTIFACTS_DIR", str(tmp_path))
+ srv, _thread = artifact_http.serve_in_thread("127.0.0.1", 0, _TOKEN)
+ yield srv
+ srv.shutdown()
+
+
+def _base_url(srv) -> str:
+ host, port = srv.server_address
+ return f"http://{host}:{port}"
+
+
+def _get(url: str, token: str | None = _TOKEN) -> tuple[int, bytes, dict]:
+ headers = {}
+ if token is not None:
+ headers["X-Artifact-Token"] = token
+ req = urllib.request.Request(url, headers=headers)
+ try:
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ return resp.status, resp.read(), dict(resp.headers)
+ except urllib.error.HTTPError as exc:
+ return exc.code, exc.read(), dict(exc.headers)
+
+
+# ------------------------------------------------------------------- 200 OK
+
+
+def test_get_with_token_returns_bytes(server):
+ data = b'{"findings": [1, 2, 3]}'
+ artifact_store.put_bytes("exec-1", "prowler.ocsf.json", data, {"tool": "prowler"})
+
+ status, body, headers = _get(f"{_base_url(server)}/artifacts/exec-1/prowler.ocsf.json")
+
+ assert status == 200
+ assert body == data
+ assert int(headers["Content-Length"]) == len(data)
+ assert headers["X-Artifact-Sha256"] == hashlib.sha256(data).hexdigest()
+
+
+def test_get_large_blob_over_1mib_streams_chunked(server):
+ """GATE N23: un blob > 1 MiB se sirve por stream chunked, idéntico byte a byte.
+
+ Es justo lo que el evento SSE único (tope 1 048 576 B) no podía entregar.
+ """
+ size = 3 * 1024 * 1024 # 3 MiB, muy por encima del viejo tope SSE
+ payload = (b"B" * size)
+ artifact_store.put_bytes("exec-big", "big.json", payload, {"tool": "prowler"})
+
+ status, body, headers = _get(f"{_base_url(server)}/artifacts/exec-big/big.json")
+
+ assert status == 200
+ assert len(body) == size
+ assert hashlib.sha256(body).hexdigest() == hashlib.sha256(payload).hexdigest()
+ assert headers["X-Artifact-Sha256"] == hashlib.sha256(payload).hexdigest()
+
+
+# --------------------------------------------------------------------- 403
+
+
+def test_get_without_token_is_forbidden(server):
+ artifact_store.put_bytes("exec-1", "a.json", b"x")
+ status, _body, _headers = _get(f"{_base_url(server)}/artifacts/exec-1/a.json", token=None)
+ assert status == 403
+
+
+def test_get_with_wrong_token_is_forbidden(server):
+ artifact_store.put_bytes("exec-1", "a.json", b"x")
+ status, _body, _headers = _get(
+ f"{_base_url(server)}/artifacts/exec-1/a.json", token="nope"
+ )
+ assert status == 403
+
+
+# --------------------------------------------------------------------- 400
+
+
+def test_get_traversal_path_is_bad_request(server):
+ # `%2e%2e` -> `..` tras unquote: el confinamiento de resolve lo rechaza (400).
+ status, _body, _headers = _get(f"{_base_url(server)}/artifacts/exec-1/%2e%2e%2fsecret")
+ assert status == 400
+
+
+def test_get_multisegment_name_is_bad_request(server):
+ status, _body, _headers = _get(f"{_base_url(server)}/artifacts/exec-1/a/b.json")
+ assert status == 400
+
+
+# --------------------------------------------------------------------- 404
+
+
+def test_get_missing_artifact_is_not_found(server):
+ status, _body, _headers = _get(f"{_base_url(server)}/artifacts/exec-1/missing.json")
+ assert status == 404
+
+
+def test_get_non_artifact_path_is_not_found(server):
+ status, _body, _headers = _get(f"{_base_url(server)}/health")
+ assert status == 404
+
+
+# ----------------------------------------------------------- fail-closed
+
+
+def test_make_server_requires_token():
+ with pytest.raises(ValueError):
+ artifact_http.make_server("127.0.0.1", 0, "")
diff --git a/docker/kali/tests/test_artifact_store.py b/docker/kali/tests/test_artifact_store.py
new file mode 100644
index 0000000..5128ba9
--- /dev/null
+++ b/docker/kali/tests/test_artifact_store.py
@@ -0,0 +1,136 @@
+"""Tests stdlib-only del staging de artefactos de kali (`docker/kali/artifact_store.py`).
+
+No importan `mcp`/`anyio`: sólo librería estándar + pytest. Verifican put (bytes/
+fichero) con sha256/size correctos, lectura de meta, confinamiento de rutas
+(traversal/absoluta rechazadas) y tolerancia a ids/nombres desconocidos.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import sys
+from pathlib import Path
+
+import pytest
+
+# El módulo bajo prueba vive en docker/kali/ (junto al servidor MCP, que NO se
+# importa aquí porque arrastra `mcp`/`anyio`). Lo añadimos al path explícitamente.
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import artifact_store # noqa: E402
+
+
+def staging(tmp_path, monkeypatch):
+ """Apunta la raíz del staging a un tmp dir por test (env leído en caliente)."""
+ monkeypatch.setenv("KALI_ARTIFACTS_DIR", str(tmp_path))
+ return tmp_path
+
+
+# ------------------------------------------------------------------ put_bytes
+
+
+def test_put_bytes_stages_file_with_sha256_and_size(staging):
+ data = b'{"findings": [1,2,3]}'
+ entry = artifact_store.put_bytes("exec-1", "prowler.ocsf.json", data, {"tool": "prowler"})
+
+ assert entry["size"] == len(data)
+ assert entry["sha256"] == hashlib.sha256(data).hexdigest()
+ assert entry["name"] == "prowler.ocsf.json"
+ assert entry["meta"]["tool"] == "prowler"
+
+ # El fichero quedó staged con el contenido verbatim.
+ staged = artifact_store.resolve("exec-1", "prowler.ocsf.json")
+ assert staged.read_bytes() == data
+
+
+# ------------------------------------------------------------------- put_file
+
+
+def test_put_file_copies_source_with_correct_digest(staging, tmp_path):
+ src = tmp_path / "src.json"
+ payload = b'{"ocsf": true}' * 100
+ src.write_bytes(payload)
+
+ entry = artifact_store.put_file(
+ "exec-2", "prowler.ocsf.json", src, {"tool": "prowler", "phase": "collection"}
+ )
+
+ assert entry["size"] == len(payload)
+ assert entry["sha256"] == hashlib.sha256(payload).hexdigest()
+ staged = artifact_store.resolve("exec-2", "prowler.ocsf.json")
+ assert staged.read_bytes() == payload
+
+
+def test_put_file_survives_source_cleanup(staging, tmp_path):
+ """El artefacto staged sobrevive aunque el fichero fuente se borre después.
+
+ Es el caso real: Prowler escribe en un TemporaryDirectory que se limpia al salir
+ del worker; el staging debe tener ya una COPIA independiente.
+ """
+ src = tmp_path / "ephemeral.json"
+ src.write_bytes(b"ephemeral")
+ artifact_store.put_file("exec-3", "out.json", src)
+ src.unlink()
+
+ staged = artifact_store.resolve("exec-3", "out.json")
+ assert staged.read_bytes() == b"ephemeral"
+
+
+# ----------------------------------------------------------------- read_meta
+
+
+def test_read_meta_returns_index_of_staged_artifacts(staging):
+ artifact_store.put_bytes("exec-4", "a.json", b"aaa", {"tool": "prowler"})
+ artifact_store.put_bytes("exec-4", "b.json", b"bb", {"tool": "nmap"})
+
+ index = artifact_store.read_meta("exec-4")
+ assert index["execution_id"] == "exec-4"
+ assert set(index["artifacts"]) == {"a.json", "b.json"}
+ assert index["artifacts"]["a.json"]["size"] == 3
+
+
+def test_stat_returns_entry_or_none(staging):
+ artifact_store.put_bytes("exec-5", "only.json", b"data")
+ entry = artifact_store.stat("exec-5", "only.json")
+ assert entry is not None
+ assert entry["sha256"] == hashlib.sha256(b"data").hexdigest()
+
+ # Nombre desconocido -> None (no revienta).
+ assert artifact_store.stat("exec-5", "missing.json") is None
+
+
+# --------------------------------------------------- unknown ids no revientan
+
+
+def test_read_meta_unknown_execution_is_empty(staging):
+ assert artifact_store.read_meta("never") == {}
+
+
+def test_stat_unknown_execution_is_none(staging):
+ assert artifact_store.stat("never", "whatever.json") is None
+
+
+# ------------------------------------------------------------- confinamiento
+
+
+ "execution_id,name",
+ [
+ ("exec-1", "../escape.json"),
+ ("../../etc", "passwd"),
+ ("exec-1", "/etc/passwd"),
+ ("exec-1", "a/b.json"),
+ ("exec-1", ".."),
+ ("", "x.json"),
+ ],
+)
+def test_resolve_rejects_traversal_and_separators(staging, execution_id, name):
+ with pytest.raises(ValueError):
+ artifact_store.resolve(execution_id, name)
+
+
+def test_resolve_confines_under_root(staging):
+ """Un nombre válido resuelve bajo la raíz del staging."""
+ path = artifact_store.resolve("exec-1", "prowler.ocsf.json")
+ assert str(path).startswith(str(Path(staging).resolve()))
diff --git a/docker/kali/tests/test_aws_exec.py b/docker/kali/tests/test_aws_exec.py
new file mode 100644
index 0000000..6b7eeba
--- /dev/null
+++ b/docker/kali/tests/test_aws_exec.py
@@ -0,0 +1,128 @@
+"""Tests stdlib-only del runner AWS del foso (`aws_exec.py`, F2 FEAT-002).
+
+Ejercitan la LÓGICA del runner SIN boto3 ni el script real (``aws_iam_enum.py`` no se
+importa: boto3 no está en el venv de dev). Fijan que:
+ - ``build_iam_enum_cmd`` produce el argv esperado (sin shell) y RECHAZA fail-closed un
+ ``account_id`` mal formado;
+ - ``run_iam_enum`` con un ``run_tool_streaming`` de FIXTURE (escribe un JSON en outfile)
+ devuelve ``done`` con ``output`` legible (el JSON crudo);
+ - sin salida legible -> ``failed`` con diagnóstico; account_id inválido -> ``failed`` sin
+ ejecutar nada; timeout -> ``failed``.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import aws_exec # noqa: E402
+
+
+# --------------------------------------------------------------- build_iam_enum_cmd
+
+
+def test_build_iam_enum_cmd_shape_no_shell():
+ cmd = aws_exec.build_iam_enum_cmd("123456789012", "", "/tmp/out.json")
+ assert cmd[0] == "python3"
+ assert cmd[1].endswith("aws_iam_enum.py")
+ assert cmd[cmd.index("--account") + 1] == "123456789012"
+ assert cmd[cmd.index("--out") + 1] == "/tmp/out.json"
+ # Sin shell: argv como lista, cada token separado (no una cadena interpolada).
+ assert all(isinstance(tok, str) for tok in cmd)
+
+
+ "bad",
+ ["", "123", "12345678901", "1234567890123", "12345678901a", "../etc", "1; rm -rf /"],
+)
+def test_build_iam_enum_cmd_rejects_malformed_account(bad):
+ with pytest.raises(aws_exec.AwsExecError):
+ aws_exec.build_iam_enum_cmd(bad, "", "/tmp/out.json")
+
+
+def test_build_iam_enum_cmd_trims_account():
+ cmd = aws_exec.build_iam_enum_cmd(" 123456789012 ", "", "/tmp/out.json")
+ assert cmd[cmd.index("--account") + 1] == "123456789012"
+
+
+# --------------------------------------------------------------- run_iam_enum
+
+
+def _fake_runner(write_output):
+ """Fake de ``run_tool_streaming``: escribe la salida de fixture y devuelve éxito."""
+
+ def _run(cmd, execution_id, timeout=0, env=None, cwd=None):
+ write_output(cmd)
+ return (0, False, False)
+
+ return _run
+
+
+def test_run_iam_enum_done_with_readable_output(monkeypatch):
+ document = {"account": "123456789012", "iam": {"roles": [], "counts": {"roles": 0}}}
+
+ def _write(cmd):
+ outfile = cmd[cmd.index("--out") + 1]
+ Path(outfile).write_text(json.dumps(document), encoding="utf-8")
+
+ monkeypatch.setattr(
+ aws_exec.tool_streaming, "run_tool_streaming", _fake_runner(_write)
+ )
+
+ result = aws_exec.run_iam_enum("123456789012", "", "exec-ok")
+ assert result["status"] == "done"
+ assert result["returncode"] == 0
+ # El 'output' es el JSON crudo verbatim (lo stagea el executor del core, no aquí).
+ assert json.loads(result["output"]) == document
+
+
+def test_run_iam_enum_failed_when_no_output(monkeypatch):
+ # Runner que NO escribe nada en outfile -> no hay salida legible.
+ monkeypatch.setattr(
+ aws_exec.tool_streaming,
+ "run_tool_streaming",
+ _fake_runner(lambda cmd: None),
+ )
+ result = aws_exec.run_iam_enum("123456789012", "", "exec-nooutput")
+ assert result["status"] == "failed"
+ assert "no produjo salida legible" in result["error"]
+
+
+def test_run_iam_enum_rejects_bad_account_without_running(monkeypatch):
+ called = {"ran": False}
+
+ def _should_not_run(*args, **kwargs):
+ called["ran"] = True
+ return (0, False, False)
+
+ monkeypatch.setattr(aws_exec.tool_streaming, "run_tool_streaming", _should_not_run)
+ result = aws_exec.run_iam_enum("not-an-account", "", "exec-bad")
+ assert result["status"] == "failed"
+ assert called["ran"] is False # fail-closed: no se ejecutó el subproceso
+ assert "account_id inválido" in result["error"]
+
+
+def test_run_iam_enum_timeout_reports_failed(monkeypatch):
+ def _timeout(cmd, execution_id, timeout=0, env=None, cwd=None):
+ return (-1, True, False) # timed_out=True
+
+ monkeypatch.setattr(aws_exec.tool_streaming, "run_tool_streaming", _timeout)
+ result = aws_exec.run_iam_enum("123456789012", "", "exec-timeout")
+ assert result["status"] == "failed"
+ assert result["timed_out"] is True
+ assert "timeout" in result["error"].lower()
+
+
+def test_run_iam_enum_cancelled(monkeypatch):
+ def _cancelled(cmd, execution_id, timeout=0, env=None, cwd=None):
+ return (-1, False, True) # cancelled=True
+
+ monkeypatch.setattr(aws_exec.tool_streaming, "run_tool_streaming", _cancelled)
+ result = aws_exec.run_iam_enum("123456789012", "", "exec-cancel")
+ assert result["status"] == "cancelled"
+ assert result["cancelled"] is True
diff --git a/docker/kali/tests/test_aws_simulate.py b/docker/kali/tests/test_aws_simulate.py
new file mode 100644
index 0000000..1e26cbc
--- /dev/null
+++ b/docker/kali/tests/test_aws_simulate.py
@@ -0,0 +1,209 @@
+"""Tests stdlib-only del runner AWS del simulate (`aws_simulate.py`, inc4b).
+
+Espejo de ``test_aws_exec``: ejercitan la LÓGICA del runner SIN boto3 ni el script real
+(``aws_iam_simulate.py`` no se importa: boto3 no está en el venv de dev; se valida con
+``ast.parse``). Fijan que:
+ - ``build_iam_simulate_cmd`` produce el argv esperado (sin shell) y RECHAZA fail-closed un
+ ``account_id`` o un ``principal_arn`` mal formados (incluido un ARN de OTRA cuenta);
+ - ``run_iam_simulate`` con un ``run_tool_streaming`` de FIXTURE (escribe un JSON de simulate)
+ devuelve ``done`` con ``output`` legible;
+ - sin salida legible -> ``failed``; account/arn inválidos -> ``failed`` sin ejecutar nada;
+ timeout -> ``failed``; cancelación -> ``cancelled``; AccessDenied ESTRUCTURADO (``error`` en
+ el JSON) -> ``failed`` claro con el error verbatim.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import aws_simulate # noqa: E402
+
+ACCOUNT = "123456789012"
+PRINCIPAL = f"arn:aws:iam::{ACCOUNT}:role/app-role"
+
+
+# --------------------------------------------------------------- build_iam_simulate_cmd
+
+
+def test_build_iam_simulate_cmd_shape_no_shell():
+ cmd = aws_simulate.build_iam_simulate_cmd(ACCOUNT, PRINCIPAL, "/tmp/out.json")
+ assert cmd[0] == "python3"
+ assert cmd[1].endswith("aws_iam_simulate.py")
+ assert cmd[cmd.index("--account") + 1] == ACCOUNT
+ assert cmd[cmd.index("--principal-arn") + 1] == PRINCIPAL
+ assert cmd[cmd.index("--out") + 1] == "/tmp/out.json"
+ # Sin shell: argv como lista, cada token separado (no una cadena interpolada).
+ assert all(isinstance(tok, str) for tok in cmd)
+
+
+ "bad",
+ ["", "123", "12345678901", "1234567890123", "12345678901a", "../etc", "1; rm -rf /"],
+)
+def test_build_iam_simulate_cmd_rejects_malformed_account(bad):
+ with pytest.raises(aws_simulate.AwsSimulateError):
+ aws_simulate.build_iam_simulate_cmd(bad, PRINCIPAL, "/tmp/out.json")
+
+
+ "bad_arn",
+ [
+ "",
+ "not-an-arn",
+ "arn:aws:s3:::bucket",
+ "arn:aws:iam::123:role/x", # cuenta no de 12 dígitos
+ "arn:aws:iam::123456789012:role/x;rm -rf /", # metacaracteres de shell
+ ],
+)
+def test_build_iam_simulate_cmd_rejects_malformed_arn(bad_arn):
+ with pytest.raises(aws_simulate.AwsSimulateError):
+ aws_simulate.build_iam_simulate_cmd(ACCOUNT, bad_arn, "/tmp/out.json")
+
+
+def test_build_iam_simulate_cmd_rejects_cross_account_arn():
+ # ARN bien formado pero de OTRA cuenta: fuera de la cuenta autorizada (N-untrusted).
+ foreign = "arn:aws:iam::999999999999:role/app-role"
+ with pytest.raises(aws_simulate.AwsSimulateError):
+ aws_simulate.build_iam_simulate_cmd(ACCOUNT, foreign, "/tmp/out.json")
+
+
+def test_build_iam_simulate_cmd_trims_inputs():
+ cmd = aws_simulate.build_iam_simulate_cmd(f" {ACCOUNT} ", f" {PRINCIPAL} ", "/tmp/out.json")
+ assert cmd[cmd.index("--account") + 1] == ACCOUNT
+ assert cmd[cmd.index("--principal-arn") + 1] == PRINCIPAL
+
+
+# --------------------------------------------------------------- run_iam_simulate
+
+
+def _fake_runner(write_output):
+ """Fake de ``run_tool_streaming``: escribe la salida de fixture y devuelve éxito."""
+
+ def _run(cmd, execution_id, timeout=0, env=None, cwd=None):
+ write_output(cmd)
+ return (0, False, False)
+
+ return _run
+
+
+def test_run_iam_simulate_done_with_readable_output(monkeypatch):
+ document = {
+ "account": ACCOUNT,
+ "principal_arn": PRINCIPAL,
+ "actions": ["sts:AssumeRole", "iam:PassRole"],
+ "simulation": {"iam:PassRole": "allowed", "sts:AssumeRole": "implicitDeny"},
+ }
+
+ def _write(cmd):
+ outfile = cmd[cmd.index("--out") + 1]
+ Path(outfile).write_text(json.dumps(document), encoding="utf-8")
+
+ monkeypatch.setattr(
+ aws_simulate.tool_streaming, "run_tool_streaming", _fake_runner(_write)
+ )
+
+ result = aws_simulate.run_iam_simulate(ACCOUNT, PRINCIPAL, "exec-ok")
+ assert result["status"] == "done"
+ assert result["returncode"] == 0
+ # El 'output' es el JSON crudo verbatim (lo stagea el executor del core, no aquí).
+ assert json.loads(result["output"]) == document
+
+
+def test_run_iam_simulate_failed_when_no_output(monkeypatch):
+ # Runner que NO escribe nada en outfile -> no hay salida legible.
+ monkeypatch.setattr(
+ aws_simulate.tool_streaming,
+ "run_tool_streaming",
+ _fake_runner(lambda cmd: None),
+ )
+ result = aws_simulate.run_iam_simulate(ACCOUNT, PRINCIPAL, "exec-nooutput")
+ assert result["status"] == "failed"
+ assert "no produjo salida legible" in result["error"]
+
+
+def test_run_iam_simulate_access_denied_structured_error_is_failed(monkeypatch):
+ # El script THIN escribe un JSON con 'error' (AccessDenied del propio Simulate, fail-closed).
+ document = {
+ "account": ACCOUNT,
+ "principal_arn": PRINCIPAL,
+ "error": "SimulatePrincipalPolicy no disponible: AccessDenied",
+ "simulation": {},
+ }
+
+ def _write(cmd):
+ outfile = cmd[cmd.index("--out") + 1]
+ Path(outfile).write_text(json.dumps(document), encoding="utf-8")
+
+ monkeypatch.setattr(
+ aws_simulate.tool_streaming, "run_tool_streaming", _fake_runner(_write)
+ )
+ result = aws_simulate.run_iam_simulate(ACCOUNT, PRINCIPAL, "exec-denied")
+ assert result["status"] == "failed"
+ # El error del simulate se propaga VERBATIM (dato NO confiable, F0.8).
+ assert "AccessDenied" in result["error"]
+
+
+def test_run_iam_simulate_rejects_bad_account_without_running(monkeypatch):
+ called = {"ran": False}
+
+ def _should_not_run(*args, **kwargs):
+ called["ran"] = True
+ return (0, False, False)
+
+ monkeypatch.setattr(aws_simulate.tool_streaming, "run_tool_streaming", _should_not_run)
+ result = aws_simulate.run_iam_simulate("not-an-account", PRINCIPAL, "exec-bad")
+ assert result["status"] == "failed"
+ assert called["ran"] is False # fail-closed: no se ejecutó el subproceso
+ assert "account_id inválido" in result["error"]
+
+
+def test_run_iam_simulate_rejects_bad_arn_without_running(monkeypatch):
+ called = {"ran": False}
+
+ def _should_not_run(*args, **kwargs):
+ called["ran"] = True
+ return (0, False, False)
+
+ monkeypatch.setattr(aws_simulate.tool_streaming, "run_tool_streaming", _should_not_run)
+ result = aws_simulate.run_iam_simulate(ACCOUNT, "not-an-arn", "exec-badarn")
+ assert result["status"] == "failed"
+ assert called["ran"] is False # fail-closed: no se ejecutó el subproceso
+ assert "principal_arn inválido" in result["error"]
+
+
+def test_run_iam_simulate_timeout_reports_failed(monkeypatch):
+ def _timeout(cmd, execution_id, timeout=0, env=None, cwd=None):
+ return (-1, True, False) # timed_out=True
+
+ monkeypatch.setattr(aws_simulate.tool_streaming, "run_tool_streaming", _timeout)
+ result = aws_simulate.run_iam_simulate(ACCOUNT, PRINCIPAL, "exec-timeout")
+ assert result["status"] == "failed"
+ assert result["timed_out"] is True
+ assert "timeout" in result["error"].lower()
+
+
+def test_run_iam_simulate_cancelled(monkeypatch):
+ def _cancelled(cmd, execution_id, timeout=0, env=None, cwd=None):
+ return (-1, False, True) # cancelled=True
+
+ monkeypatch.setattr(aws_simulate.tool_streaming, "run_tool_streaming", _cancelled)
+ result = aws_simulate.run_iam_simulate(ACCOUNT, PRINCIPAL, "exec-cancel")
+ assert result["status"] == "cancelled"
+ assert result["cancelled"] is True
+
+
+# --------------------------------------------------------------- thin script (ast.parse)
+
+
+def test_thin_simulate_script_parses():
+ """``aws_iam_simulate.py`` es THIN (no se importa: boto3 ausente); se valida con ast.parse."""
+ script = Path(aws_simulate._script_path())
+ assert script.is_file()
+ ast.parse(script.read_text(encoding="utf-8"))
diff --git a/docker/kali/tests/test_collector_runner.py b/docker/kali/tests/test_collector_runner.py
new file mode 100644
index 0000000..b2e86ff
--- /dev/null
+++ b/docker/kali/tests/test_collector_runner.py
@@ -0,0 +1,276 @@
+"""Tests stdlib-only del runner multi-herramienta genérico (`collector_runner.py`, N33).
+
+Ejercitan la LÓGICA del runner SIN los binarios reales (prowler/scout/cloudsplaining):
+ - los command builders producen el argv esperado por fuente;
+ - los localizadores eligen el crudo correcto (JSON de ScoutSuite/Cloudsplaining, NUNCA
+ el HTML);
+ - la finalización stagea el crudo como artefacto y construye el `done` con la REFERENCIA
+ (sha256/size correctos); las fuentes no-Prowler NO populan el puente SSE (D6);
+ - Prowler sigue produciendo el mismo `done` que hoy (delegando en prowler_artifact);
+ - ``run_collection`` orquesta end-to-end con un runner de subproceso simulado.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import artifact_store # noqa: E402
+import collector_runner # noqa: E402
+import tool_streaming # noqa: E402
+
+
+def staging(tmp_path, monkeypatch):
+ monkeypatch.setenv("KALI_ARTIFACTS_DIR", str(tmp_path / "artifacts"))
+ return tmp_path
+
+
+# --------------------------------------------------------------- command builders
+
+
+def test_scoutsuite_command_is_readonly_json_to_report_dir():
+ cmd = collector_runner._scoutsuite_commands("123456789012", "/work", "/work/out", {})[0]
+ assert cmd[0] == "scout" and cmd[1] == "aws"
+ assert "--no-browser" in cmd
+ assert cmd[cmd.index("--result-format") + 1] == "json"
+ assert cmd[cmd.index("--report-dir") + 1] == "/work/out"
+
+
+def test_cloudsplaining_commands_download_then_scan_json_output():
+ cmds = collector_runner._cloudsplaining_commands("123456789012", "/work", "/work/out", {})
+ assert len(cmds) == 2
+ download, scan = cmds
+ assert download[:2] == ["cloudsplaining", "download"]
+ assert scan[:2] == ["cloudsplaining", "scan"]
+ assert scan[scan.index("--output") + 1] == "/work/out"
+ assert "--skip-open-report" in scan # no abre navegador
+ # ``download --output`` es un DIRECTORIO existente (no un fichero): cloudsplaining escribe
+ # ``default.json`` dentro de workdir y el scan lee ese fichero.
+ assert download[download.index("--output") + 1] == "/work"
+ assert scan[scan.index("--input-file") + 1] == "/work/default.json"
+
+
+def test_prowler_command_matches_mvp_shape(monkeypatch):
+ monkeypatch.setenv("PROWLER_SERVICES", "iam s3")
+ monkeypatch.setenv("PROWLER_REGIONS", "us-east-1")
+ cmd = collector_runner._build_prowler_cmd("/out")
+ assert cmd[1] == "aws"
+ assert cmd[cmd.index("--output-directory") + 1] == "/out"
+ assert "json-ocsf" in cmd
+ assert cmd[cmd.index("--service") + 1] == "iam"
+ assert cmd[cmd.index("--region") + 1] == "us-east-1"
+
+
+# --------------------------------------------------------------- localizadores
+
+
+def test_scoutsuite_locate_picks_results_js(tmp_path):
+ outdir = tmp_path / "out"
+ results = outdir / "scoutsuite-results"
+ results.mkdir(parents=True)
+ (results / "scoutsuite_results_aws-pentagent.js").write_text("scoutsuite_results = {}", encoding="utf-8")
+ (outdir / "report.html").write_text("<html></html>", encoding="utf-8") # NO debe elegirse
+ found = collector_runner._scoutsuite_locate(outdir)
+ assert found is not None and found.suffix == ".js"
+
+
+def test_cloudsplaining_locate_prefers_iam_results_over_findings_and_html(tmp_path):
+ # Layout REAL del binario 0.9.1: escribe el HTML + ``iam-findings-*.json`` +
+ # ``iam-results-*.json`` en ``outdir``. Se le da a ``iam-findings-*.json`` el mtime MÁS
+ # reciente para que un localizador ingenuo de "``*.json`` más reciente" eligiera el
+ # equivocado; el localizador debe fijar el prefijo y devolver el ``iam-results-*.json``.
+ import os
+ import time
+
+ outdir = tmp_path / "out"
+ outdir.mkdir()
+ (outdir / "iam-report-default.html").write_text("<html></html>", encoding="utf-8")
+ results = outdir / "iam-results-default.json"
+ results.write_text("{}", encoding="utf-8")
+ findings = outdir / "iam-findings-default.json"
+ findings.write_text("{}", encoding="utf-8")
+ newer = time.time() + 10
+ os.utime(findings, (newer, newer)) # findings es el MÁS reciente
+
+ found = collector_runner._cloudsplaining_locate(outdir)
+ assert found == results # pinned por prefijo, no por mtime
+
+
+def test_cloudsplaining_locate_falls_back_to_findings_never_html(tmp_path):
+ # Sin ``iam-results-*.json`` (solo findings + HTML), cae al ``iam-findings-*.json`` y
+ # NUNCA al HTML de presentación.
+ outdir = tmp_path / "out"
+ outdir.mkdir()
+ (outdir / "iam-report-default.html").write_text("<html></html>", encoding="utf-8")
+ findings = outdir / "iam-findings-default.json"
+ findings.write_text("{}", encoding="utf-8")
+
+ found = collector_runner._cloudsplaining_locate(outdir)
+ assert found == findings
+
+
+def test_locate_returns_none_when_no_output(tmp_path):
+ outdir = tmp_path / "empty"
+ outdir.mkdir()
+ assert collector_runner._scoutsuite_locate(outdir) is None
+ assert collector_runner._cloudsplaining_locate(outdir) is None
+
+
+# --------------------------------------------------------------- finalize (no-bridge)
+
+
+def test_finalize_scoutsuite_stages_artifact_and_done_ref_no_bridge(staging):
+ outdir = staging / "out" / "scoutsuite-results"
+ outdir.mkdir(parents=True)
+ raw = b"scoutsuite_results =\n" + json.dumps({"services": {}}).encode("utf-8") + b";"
+ (outdir / "scoutsuite_results_aws-pentagent.js").write_bytes(raw)
+
+ done = collector_runner.finalize(
+ "scoutsuite", "exec-ss", staging / "out", 0, {"source": "scoutsuite"}
+ )
+
+ assert done["status"] == "done"
+ assert "findings" not in done # el control nunca lleva la carga
+ artifact = done["artifact"]
+ assert artifact["name"] == collector_runner.SCOUTSUITE_ARTIFACT_NAME
+ assert artifact["size"] == len(raw)
+ assert artifact["sha256"] == hashlib.sha256(raw).hexdigest()
+ # El crudo (``.js`` verbatim) quedó staged con el nombre canónico.
+ staged = artifact_store.resolve("exec-ss", collector_runner.SCOUTSUITE_ARTIFACT_NAME)
+ assert staged.read_bytes() == raw
+ # D6: una fuente no-Prowler NO popula el puente SSE.
+ assert tool_streaming.read_findings("exec-ss", 0)["findings"] == []
+
+
+def test_finalize_cloudsplaining_stages_json_not_html(staging):
+ outdir = staging / "out"
+ outdir.mkdir(parents=True)
+ (outdir / "iam-results-default.html").write_text("<html></html>", encoding="utf-8")
+ raw = json.dumps({"customer_managed_policies": {}}).encode("utf-8")
+ (outdir / "iam-results-default.json").write_bytes(raw)
+
+ done = collector_runner.finalize(
+ "cloudsplaining", "exec-cs", outdir, 0, {"source": "cloudsplaining"}
+ )
+ assert done["artifact"]["name"] == collector_runner.CLOUDSPLAINING_ARTIFACT_NAME
+ assert done["artifact"]["sha256"] == hashlib.sha256(raw).hexdigest()
+ staged = artifact_store.resolve("exec-cs", collector_runner.CLOUDSPLAINING_ARTIFACT_NAME)
+ assert staged.read_bytes() == raw # el JSON, no el HTML
+
+
+def test_finalize_returns_none_when_no_output(staging):
+ outdir = staging / "out"
+ outdir.mkdir(parents=True)
+ assert collector_runner.finalize("scoutsuite", "exec-x", outdir, 1, {"source": "scoutsuite"}) is None
+
+
+# --------------------------------------------------------------- finalize prowler (bridge)
+
+
+def test_finalize_prowler_matches_today_with_bridge(staging):
+ outdir = staging / "out"
+ outdir.mkdir(parents=True)
+ findings = [{"check_id": f"c{i}", "severity": "high"} for i in range(3)]
+ (outdir / "prowler-output.ocsf.json").write_bytes(json.dumps(findings).encode("utf-8"))
+
+ done = collector_runner.finalize("prowler", "exec-pw", outdir, 0, {"source": "prowler"})
+
+ assert done["status"] == "done"
+ assert done["findings_count"] == 3
+ assert done["artifact"]["name"] == collector_runner.PROWLER_ARTIFACT_NAME
+ assert "findings" not in done # findings por referencia, no inline
+ # Prowler SÍ mantiene el puente SSE (compat N21).
+ page = tool_streaming.read_findings("exec-pw", 0)
+ assert [f["check_id"] for f in page["findings"]] == ["c0", "c1", "c2"]
+
+
+# --------------------------------------------------------------- disponibilidad
+
+
+def test_available_collectors_reports_bool_per_source():
+ avail = collector_runner.available_collectors()
+ assert set(avail) == {"prowler", "scoutsuite", "cloudsplaining"}
+ assert all(isinstance(v, bool) for v in avail.values())
+
+
+# --------------------------------------------------------------- run_collection e2e
+
+
+def _fake_runner(write_output):
+ """Fake de ``run_tool_streaming``: escribe la salida de fixture y devuelve éxito."""
+
+ def _run(cmd, execution_id, timeout=0, env=None, cwd=None):
+ write_output(cmd)
+ return (0, False, False)
+
+ return _run
+
+
+def test_run_collection_scoutsuite_e2e(staging, monkeypatch):
+ monkeypatch.setattr(collector_runner.shutil, "which", lambda b: f"/usr/bin/{b}")
+ raw = b"scoutsuite_results = " + json.dumps({"services": {}}).encode("utf-8") + b";"
+
+ def _write(cmd):
+ outdir = Path(cmd[cmd.index("--report-dir") + 1]) / "scoutsuite-results"
+ outdir.mkdir(parents=True, exist_ok=True)
+ (outdir / "scoutsuite_results_aws-pentagent.js").write_bytes(raw)
+
+ monkeypatch.setattr(
+ collector_runner.tool_streaming, "run_tool_streaming", _fake_runner(_write)
+ )
+
+ done = collector_runner.run_collection("scoutsuite", "123456789012", "exec-run-ss")
+ assert done["status"] == "done"
+ assert done["artifact"]["name"] == collector_runner.SCOUTSUITE_ARTIFACT_NAME
+ assert done["artifact"]["sha256"] == hashlib.sha256(raw).hexdigest()
+ assert tool_streaming.read_findings("exec-run-ss", 0)["findings"] == [] # sin puente
+
+
+def test_run_collection_cloudsplaining_e2e(staging, monkeypatch):
+ monkeypatch.setattr(collector_runner.shutil, "which", lambda b: f"/usr/bin/{b}")
+ raw = json.dumps({"customer_managed_policies": {}}).encode("utf-8")
+
+ def _write(cmd):
+ if cmd[1] == "download":
+ # ``download --output`` es un DIRECTORIO existente; cloudsplaining escribe
+ # ``default.json`` dentro (como el binario real), no en la ruta tal cual.
+ Path(cmd[cmd.index("--output") + 1], "default.json").write_text(
+ "{}", encoding="utf-8"
+ )
+ elif cmd[1] == "scan":
+ # El scan exige que su ``--input-file`` (el default.json del paso 1) exista.
+ assert Path(cmd[cmd.index("--input-file") + 1]).is_file()
+ outdir = Path(cmd[cmd.index("--output") + 1])
+ outdir.mkdir(parents=True, exist_ok=True)
+ # Layout real del binario (0.9.1): HTML de presentación + los dos JSON de scan.
+ (outdir / "iam-report-default.html").write_text("<html></html>", encoding="utf-8")
+ (outdir / "iam-findings-default.json").write_bytes(raw)
+ (outdir / "iam-results-default.json").write_bytes(raw)
+
+ monkeypatch.setattr(
+ collector_runner.tool_streaming, "run_tool_streaming", _fake_runner(_write)
+ )
+
+ done = collector_runner.run_collection("cloudsplaining", "123456789012", "exec-run-cs")
+ assert done["status"] == "done"
+ assert done["artifact"]["name"] == collector_runner.CLOUDSPLAINING_ARTIFACT_NAME
+ assert done["artifact"]["sha256"] == hashlib.sha256(raw).hexdigest()
+
+
+def test_run_collection_missing_binary_fails_honestly(monkeypatch):
+ monkeypatch.setattr(collector_runner.shutil, "which", lambda b: None)
+ with pytest.raises(RuntimeError) as exc:
+ collector_runner.run_collection("scoutsuite", "1", "exec-nobinary")
+ assert "no está disponible" in str(exc.value)
+
+
+def test_run_collection_unknown_source_raises():
+ with pytest.raises(RuntimeError):
+ collector_runner.run_collection("nessus", "1", "exec-unknown")
diff --git a/docker/kali/tests/test_kali_run.py b/docker/kali/tests/test_kali_run.py
new file mode 100644
index 0000000..5368c36
--- /dev/null
+++ b/docker/kali/tests/test_kali_run.py
@@ -0,0 +1,102 @@
+"""Tests de la tool BLOQUEANTE ``kali_run`` (STDLIB PURA, SIN importar el servidor).
+
+Restricción dura del entorno: en el venv local hay ``mcp`` 2.x pero
+``kali_mcp_server.py`` exige ``mcp<2`` (FastMCP 1.x), así que ``import kali_mcp_server``
+FALLA. Por eso estos tests NO importan el servidor: validan (a) la LÓGICA bloqueante vía
+``shell_exec.run_shell`` (que es lo que ``kali_run`` llama SINCRONAMENTE) y (b) la forma
+del servidor leyendo su TEXTO fuente (open().read() + aserciones), nunca importándolo.
+
+Siguen el patrón de ``tests/test_shell_exec.py``: ``sys.path.insert`` del padre, import de
+``shell_exec``/``tool_streaming`` y monkeypatch de ``run_tool_streaming`` con un fake que
+vuelca líneas al ring.
+"""
+
+from __future__ import annotations
+
+import sys
+import uuid
+from pathlib import Path
+
+import pytest
+
+_PARENT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(_PARENT))
+
+import shell_exec # noqa: E402
+import tool_streaming # noqa: E402
+
+# Ruta del servidor cuyo TEXTO (no import) se inspecciona en los tests de forma.
+_SERVER_PATH = _PARENT / "kali_mcp_server.py"
+
+
+def _fake_runner(returncode=0, timed_out=False, cancelled=False, lines=None):
+ """Fake de ``run_tool_streaming``: vuelca ``lines`` al ring y retorna el estado.
+
+ ``lines`` es una lista de (stream, text) que se escribe al ring del ``execution_id``
+ para que ``run_shell`` las recoja como salida del comando.
+ """
+
+ def _run(cmd, execution_id, timeout=0, env=None, cwd=None):
+ for stream, text in lines or []:
+ tool_streaming.append(execution_id, stream, text)
+ return (returncode, timed_out, cancelled)
+
+ return _run
+
+
+def test_blocking_call_returns_full_output_in_one_call(monkeypatch):
+ # kali_run es BLOQUEANTE: llama run_shell SINCRONAMENTE (con un execution_id uuid) y
+ # obtiene el dict terminal con la salida completa del ring en UNA sola llamada.
+ runner = _fake_runner(returncode=0, lines=[("stdout", "line-1"), ("stdout", "line-2")])
+ monkeypatch.setattr(shell_exec.tool_streaming, "run_tool_streaming", runner)
+
+ result = shell_exec.run_shell("nmap -sV localhost", uuid.uuid4().hex, 600)
+ assert result["status"] == "done"
+ assert result["returncode"] == 0
+ assert "line-1" in result["output"]
+ assert "line-2" in result["output"]
+
+
[email protected]("bad", ["", " ", None, 123])
+def test_invalid_command_fails_without_running(monkeypatch, bad):
+ called = {"ran": False}
+
+ def _should_not_run(*args, **kwargs):
+ called["ran"] = True
+ return (0, False, False)
+
+ monkeypatch.setattr(shell_exec.tool_streaming, "run_tool_streaming", _should_not_run)
+ result = shell_exec.run_shell(bad, uuid.uuid4().hex, 600)
+ assert result["status"] == "failed"
+ assert result["returncode"] == -1
+ assert called["ran"] is False # fail-closed: no se ejecutó nada
+
+
+def test_server_text_declares_kali_run_blocking_and_keeps_all_tools():
+ # Se valida la FORMA del servidor por su TEXTO (NO import: mcp<2 no está en el venv).
+ source = _SERVER_PATH.read_text(encoding="utf-8")
+
+ # (1) kali_run existe y referencia el runner compartido run_shell.
+ assert "def kali_run" in source
+ assert "shell_exec.run_shell" in source
+
+ # (2) kali_run aparece listada entre las tools de server_info.
+ assert "KALI_RUN_TOOL_NAME" in source
+ assert 'KALI_RUN_TOOL_NAME = "kali_run"' in source
+
+ # (3) El cuerpo de kali_run es BLOQUEANTE: NO LLAMA a start_background (la mención
+ # en el docstring explica justo que NO lo usa, por eso se busca la LLAMADA concreta).
+ body_start = source.index("def kali_run")
+ body = source[body_start : source.index("def _start_artifacts_http")]
+ assert "tool_streaming.start_background(" not in body
+ assert "shell_exec.run_shell" in body
+
+ # (4) server_info SIGUE listando las tools existentes (no se quitó ninguna).
+ for name in (
+ "PROWLER_TOOL_NAME",
+ "START_COLLECTION_TOOL_NAME",
+ "IAM_ENUM_TOOL_NAME",
+ "IAM_SIMULATE_TOOL_NAME",
+ "KALI_EXEC_TOOL_NAME",
+ ):
+ assert name in source
diff --git a/docker/kali/tests/test_prowler_artifact.py b/docker/kali/tests/test_prowler_artifact.py
new file mode 100644
index 0000000..9dfca05
--- /dev/null
+++ b/docker/kali/tests/test_prowler_artifact.py
@@ -0,0 +1,125 @@
+"""Tests stdlib-only de la finalización del escaneo (`docker/kali/prowler_artifact.py`).
+
+Ejercitan el camino post-escaneo del worker SIN `mcp`/`prowler`: con un OCSF de
+fixture, el `done` trae la REFERENCIA `artifact` (sha256/size correctos) y NO los
+findings inline; el puente `read_scan_findings` (vía tool_streaming) sigue sirviendo
+las páginas; una salida ilegible produce `None` (el caller publica failed).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+# Módulos bajo prueba en docker/kali/ (stdlib puro; no importan `mcp`/`anyio`).
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import artifact_store # noqa: E402
+import prowler_artifact # noqa: E402
+import tool_streaming # noqa: E402
+
+
+def _ocsf(n: int) -> list[dict]:
+ return [{"check_id": f"c{i}", "severity": "high"} for i in range(n)]
+
+
+def staging(tmp_path, monkeypatch):
+ monkeypatch.setenv("KALI_ARTIFACTS_DIR", str(tmp_path / "artifacts"))
+ return tmp_path
+
+
+def _write_ocsf(outdir: Path, findings: list[dict]) -> bytes:
+ outdir.mkdir(parents=True, exist_ok=True)
+ raw = json.dumps(findings).encode("utf-8")
+ (outdir / "prowler-output.ocsf.json").write_bytes(raw)
+ return raw
+
+
+# --------------------------------------------------------- done con artifact ref
+
+
+def test_finalize_scan_stages_artifact_and_done_has_ref_not_inline(staging):
+ outdir = staging / "scan-out"
+ raw = _write_ocsf(outdir, _ocsf(5))
+
+ done = prowler_artifact.finalize_scan("exec-1", outdir, 0, {"account_id": "123456789012"})
+
+ assert done["status"] == "done"
+ assert done["findings_count"] == 5
+ # Clave de la oleada: NADA de findings inline en el canal de control.
+ assert "findings" not in done
+ # La referencia pequeña del plano de datos, con sha256/size del CRUDO.
+ artifact = done["artifact"]
+ assert artifact["execution_id"] == "exec-1"
+ assert artifact["name"] == prowler_artifact.PROWLER_ARTIFACT_NAME
+ assert artifact["size"] == len(raw)
+ assert artifact["sha256"] == hashlib.sha256(raw).hexdigest()
+
+ # El artefacto crudo quedó staged idéntico (lo servirá el HTTP al core).
+ staged = artifact_store.resolve("exec-1", prowler_artifact.PROWLER_ARTIFACT_NAME)
+ assert staged.read_bytes() == raw
+
+
+def test_finalize_scan_keeps_read_scan_findings_bridge(staging):
+ """Puente intacto (N21): los findings quedan paginables por tool_streaming."""
+ outdir = staging / "scan-out"
+ _write_ocsf(outdir, _ocsf(3))
+
+ prowler_artifact.finalize_scan("exec-2", outdir, 0, {})
+
+ page = tool_streaming.read_findings("exec-2", 0)
+ assert [f["check_id"] for f in page["findings"]] == ["c0", "c1", "c2"]
+ assert page["done"] is True
+
+
+def test_finalize_scan_unreadable_output_returns_none(staging):
+ """Sin salida JSON legible -> None (el worker publica failed con diagnóstico)."""
+ outdir = staging / "empty"
+ outdir.mkdir(parents=True, exist_ok=True)
+ assert prowler_artifact.finalize_scan("exec-3", outdir, 1, {}) is None
+
+
+# ---------------------------------------------------------- read_prowler_output
+
+
+def test_read_prowler_output_picks_readable_file(staging):
+ outdir = staging / "out"
+ raw = _write_ocsf(outdir, _ocsf(2))
+ path, findings = prowler_artifact.read_prowler_output(outdir)
+ assert path is not None
+ assert path.read_bytes() == raw
+ assert len(findings) == 2
+
+
+def test_read_prowler_output_wraps_dict_payload(staging):
+ outdir = staging / "out"
+ outdir.mkdir(parents=True, exist_ok=True)
+ (outdir / "r.json").write_text(json.dumps({"findings": _ocsf(4)}), encoding="utf-8")
+ _path, findings = prowler_artifact.read_prowler_output(outdir)
+ assert len(findings) == 4
+
+
+def test_finalize_scan_bridge_survives_staging_failure(staging, monkeypatch):
+ """Si el staging falla, se publica done SIN artifact ref pero el puente sigue.
+
+ Es la red de seguridad: el plano de datos nunca tumba el escaneo; el core cae al
+ puente read_scan_findings.
+ """
+ outdir = staging / "out"
+ _write_ocsf(outdir, _ocsf(2))
+
+ def _boom(*_a, **_k):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(artifact_store, "put_file", _boom)
+
+ done = prowler_artifact.finalize_scan("exec-9", outdir, 0, {})
+ assert done["status"] == "done"
+ assert "artifact" not in done
+ # Puente intacto pese al fallo de staging.
+ assert tool_streaming.read_findings("exec-9", 0)["findings"]
diff --git a/docker/kali/tests/test_shell_exec.py b/docker/kali/tests/test_shell_exec.py
new file mode 100644
index 0000000..d4a9619
--- /dev/null
+++ b/docker/kali/tests/test_shell_exec.py
@@ -0,0 +1,97 @@
+"""Tests stdlib-only del runner de SHELL CRUDA (`shell_exec.py`).
+
+Ejercitan la LÓGICA del runner SIN ejecutar comandos reales (``run_tool_streaming`` se
+sustituye por un fake). Fijan que:
+ - ``run_shell`` con un runner de fixture devuelve ``done`` con ``output`` = salida del ring;
+ - un ``command`` inválido (no-string / vacío) -> ``failed`` SIN ejecutar nada (fail-closed);
+ - timeout -> ``failed`` con diagnóstico; cancelación -> ``cancelled``;
+ - un ``returncode`` != 0 es ``done`` (resultado legítimo del comando, no fallo del runner);
+ - el comando se pasa a ``sh -c`` verbatim (shell cruda, no se restringe el contenido).
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import shell_exec # noqa: E402
+import tool_streaming # noqa: E402
+
+
+def _fake_runner(returncode=0, timed_out=False, cancelled=False, lines=None):
+ """Fake de ``run_tool_streaming``: registra el cmd, vuelca ``lines`` al ring y retorna.
+
+ ``lines`` es una lista de (stream, text) que se escribe al ring del ``execution_id`` para
+ que ``_ring_output`` las recoja como salida del comando.
+ """
+ captured = {"cmd": None}
+
+ def _run(cmd, execution_id, timeout=0, env=None, cwd=None):
+ captured["cmd"] = cmd
+ for stream, text in lines or []:
+ tool_streaming.append(execution_id, stream, text)
+ return (returncode, timed_out, cancelled)
+
+ return _run, captured
+
+
+def test_run_shell_passes_command_to_sh_c_verbatim(monkeypatch):
+ runner, captured = _fake_runner(lines=[("stdout", "hello")])
+ monkeypatch.setattr(shell_exec.tool_streaming, "run_tool_streaming", runner)
+
+ result = shell_exec.run_shell("echo hello | tr a-z A-Z", "exec-sh-1")
+ assert result["status"] == "done"
+ assert result["returncode"] == 0
+ # Shell cruda: el comando va TAL CUAL a `sh -c` (no se restringe pipes/encadenado).
+ assert captured["cmd"] == ["sh", "-c", "echo hello | tr a-z A-Z"]
+ # output = salida acumulada del ring (verbatim).
+ assert "hello" in result["output"]
+
+
+def test_run_shell_nonzero_returncode_is_done_not_failed(monkeypatch):
+ # Un comando que termina con rc!=0 (p. ej. grep sin match) NO es fallo del runner.
+ runner, _ = _fake_runner(returncode=1, lines=[("stderr", "no match")])
+ monkeypatch.setattr(shell_exec.tool_streaming, "run_tool_streaming", runner)
+
+ result = shell_exec.run_shell("grep nope /etc/hosts", "exec-sh-rc")
+ assert result["status"] == "done"
+ assert result["returncode"] == 1
+ assert "no match" in result["output"]
+
+
[email protected]("bad", ["", " ", None, 123, ["ls"]])
+def test_run_shell_rejects_invalid_command_without_running(monkeypatch, bad):
+ called = {"ran": False}
+
+ def _should_not_run(*args, **kwargs):
+ called["ran"] = True
+ return (0, False, False)
+
+ monkeypatch.setattr(shell_exec.tool_streaming, "run_tool_streaming", _should_not_run)
+ result = shell_exec.run_shell(bad, "exec-sh-bad")
+ assert result["status"] == "failed"
+ assert called["ran"] is False # fail-closed: no se lanzó `sh -c`
+ assert "command inválido" in result["error"]
+
+
+def test_run_shell_timeout_reports_failed(monkeypatch):
+ runner, _ = _fake_runner(returncode=-1, timed_out=True)
+ monkeypatch.setattr(shell_exec.tool_streaming, "run_tool_streaming", runner)
+
+ result = shell_exec.run_shell("sleep 999", "exec-sh-timeout", timeout=5)
+ assert result["status"] == "failed"
+ assert result["timed_out"] is True
+ assert "timeout" in result["error"].lower()
+
+
+def test_run_shell_cancelled(monkeypatch):
+ runner, _ = _fake_runner(returncode=-1, cancelled=True)
+ monkeypatch.setattr(shell_exec.tool_streaming, "run_tool_streaming", runner)
+
+ result = shell_exec.run_shell("sleep 999", "exec-sh-cancel")
+ assert result["status"] == "cancelled"
+ assert result["cancelled"] is True
diff --git a/docker/kali/tests/test_tool_streaming.py b/docker/kali/tests/test_tool_streaming.py
new file mode 100644
index 0000000..756e950
--- /dev/null
+++ b/docker/kali/tests/test_tool_streaming.py
@@ -0,0 +1,414 @@
+"""Tests stdlib-only de las primitivas de streaming (`docker/kali/tool_streaming.py`).
+
+No importan `mcp`/`anyio`: sólo librería estándar + pytest. Verifican lectura
+incremental por cursor, orden de `seq`, timeout con muerte del grupo (sin
+huérfanos) y la semántica de una página vacía al final del cursor.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import sys
+import threading
+import time
+import uuid
+from pathlib import Path
+
+# El módulo bajo prueba vive en docker/kali/ (junto al servidor MCP, que NO se
+# importa aquí porque arrastra `mcp`/`anyio`). Lo añadimos al path explícitamente.
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import tool_streaming # noqa: E402
+
+
+def _new_id() -> str:
+ return uuid.uuid4().hex
+
+
+def test_incremental_reads_by_cursor_in_seq_order() -> None:
+ """Un comando lento se lee en varias páginas; la final reporta done y orden seq."""
+ execution_id = _new_id()
+ code = "import sys,time\nfor i in range(5):\n print(i, flush=True); time.sleep(0.2)"
+ cmd = [sys.executable, "-c", code]
+
+ done_holder: dict[str, tuple[int, bool, bool]] = {}
+
+ import threading
+
+ def runner() -> None:
+ done_holder["result"] = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=30
+ )
+
+ thread = threading.Thread(target=runner)
+ thread.start()
+
+ # Lectura incremental: avanzamos el cursor y acumulamos páginas mientras corre.
+ cursor = 0
+ collected: list[dict] = []
+ got_a_partial_page = False
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ page = tool_streaming.read(execution_id, cursor)
+ if page["lines"]:
+ collected.extend(page["lines"])
+ cursor = page["next_cursor"]
+ # Si todavía no acabó y ya tenemos salida, confirma la incrementalidad.
+ if not page["done"] and len(collected) < 5:
+ got_a_partial_page = True
+ if page["done"]:
+ # Drenamos cualquier cola pendiente tras done.
+ tail = tool_streaming.read(execution_id, cursor)
+ collected.extend(tail["lines"])
+ cursor = tail["next_cursor"]
+ break
+ time.sleep(0.1)
+
+ thread.join(timeout=10)
+
+ returncode, timed_out, cancelled = done_holder["result"]
+ assert timed_out is False
+ assert cancelled is False
+ assert returncode == 0
+
+ stdout_lines = [line for line in collected if line["stream"] == "stdout"]
+ texts = [line["text"] for line in stdout_lines]
+ assert texts == ["0", "1", "2", "3", "4"]
+
+ # seq estrictamente creciente en el orden entregado.
+ seqs = [line["seq"] for line in collected]
+ assert seqs == sorted(seqs)
+ assert len(seqs) == len(set(seqs))
+
+ # Se observó al menos una página parcial (lectura en vivo, no sólo al final).
+ assert got_a_partial_page
+
+
+def test_timeout_kills_process_group_no_orphans() -> None:
+ """Un comando que duerme más que el timeout -> timed_out=True y sin hijos vivos."""
+ execution_id = _new_id()
+ # Hijo que a su vez crea un nieto en el mismo grupo; ambos deben morir.
+ code = (
+ "import os,sys,time,subprocess\n"
+ "child = subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)'])\n"
+ "print(child.pid, flush=True)\n"
+ "time.sleep(60)\n"
+ )
+ cmd = [sys.executable, "-c", code]
+
+ start = time.monotonic()
+ returncode, timed_out, cancelled = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=1
+ )
+ elapsed = time.monotonic() - start
+
+ assert timed_out is True
+ # Un timeout NO es una cancelación: son estados distinguibles (N22.2).
+ assert cancelled is False
+ # No debe esperar los 60s: el timeout de 1s mató el grupo con margen.
+ assert elapsed < 20
+
+ # El PID del nieto quedó en la salida; comprobamos que ya no existe.
+ page = tool_streaming.read(execution_id, 0)
+ grandchild_pid = None
+ for line in page["lines"]:
+ if line["stream"] == "stdout" and line["text"].strip().isdigit():
+ grandchild_pid = int(line["text"].strip())
+ break
+
+ assert page["done"] is True
+
+ if grandchild_pid is not None:
+ # Dar un instante a la propagación de la señal al grupo.
+ time.sleep(0.5)
+ alive = _pid_alive(grandchild_pid)
+ assert alive is False
+
+
+def _pid_alive(pid: int) -> bool:
+ """True si el proceso existe (signal 0 no mata, sólo chequea)."""
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ return True
+
+
+def test_request_cancel_kills_process_group_no_orphans() -> None:
+ """request_cancel mata el grupo (sin huérfanos) y marca cancelled=True (≠ timed_out)."""
+ execution_id = _new_id()
+ # Padre (líder de grupo) con un hijo en el MISMO grupo; cancelar debe matar ambos.
+ code = (
+ "import os,sys,time,subprocess\n"
+ "child = subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)'])\n"
+ "print(child.pid, flush=True)\n"
+ "time.sleep(60)\n"
+ )
+ cmd = [sys.executable, "-c", code]
+
+ holder: dict[str, tuple[int, bool, bool]] = {}
+
+ def runner() -> None:
+ holder["result"] = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=60
+ )
+
+ thread = threading.Thread(target=runner)
+ thread.start()
+
+ # Espera a que el proceso esté registrado (vivo) antes de cancelar.
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ with tool_streaming._procs_lock:
+ registered = execution_id in tool_streaming._procs
+ if registered:
+ break
+ time.sleep(0.02)
+
+ killed = tool_streaming.request_cancel(execution_id)
+ thread.join(timeout=15)
+ assert not thread.is_alive()
+
+ _returncode, timed_out, cancelled = holder["result"]
+ assert cancelled is True
+ assert timed_out is False # cancelación ≠ timeout (estados distinguibles)
+ assert killed is True
+
+ # El nieto (su PID quedó en la salida) ya no existe: grupo muerto, sin huérfanos.
+ page = tool_streaming.read(execution_id, 0)
+ grandchild_pid = None
+ for line in page["lines"]:
+ if line["stream"] == "stdout" and line["text"].strip().isdigit():
+ grandchild_pid = int(line["text"].strip())
+ break
+ if grandchild_pid is not None:
+ time.sleep(0.5)
+ assert _pid_alive(grandchild_pid) is False
+
+
+def test_read_at_tail_returns_empty_page_and_same_cursor() -> None:
+ """Leer con el cursor en la cola: página vacía y next_cursor sin cambios."""
+ execution_id = _new_id()
+ cmd = [sys.executable, "-c", "print('only-line', flush=True)"]
+ tool_streaming.run_tool_streaming(cmd, execution_id, timeout=10)
+
+ first = tool_streaming.read(execution_id, 0)
+ assert first["lines"]
+ tail_cursor = first["next_cursor"]
+
+ second = tool_streaming.read(execution_id, tail_cursor)
+ assert second["lines"] == []
+ assert second["next_cursor"] == tail_cursor
+ assert second["done"] is True
+
+
+def test_unknown_execution_id_is_empty() -> None:
+ """Un execution_id desconocido no revienta: página vacía, no done."""
+ page = tool_streaming.read("does-not-exist", 0)
+ assert page["lines"] == []
+ assert page["next_cursor"] == 0
+ assert page["done"] is False
+
+
+def test_unknown_status_is_unknown() -> None:
+ """get_status de un execution_id no registrado devuelve {'status':'unknown'}."""
+ assert tool_streaming.get_status("never-started") == {"status": "unknown"}
+
+
+def test_start_background_returns_before_process_ends() -> None:
+ """start_background DEVUELVE un Thread y el estado es 'running' nada más lanzar."""
+ execution_id = _new_id()
+ # Worker lento (duerme antes de imprimir) para que, justo tras lanzar, siga vivo.
+ code = "import time;time.sleep(1.0);print('late', flush=True)"
+ cmd = [sys.executable, "-c", code]
+
+ def worker() -> dict:
+ rc, timed_out, _cancelled = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=30
+ )
+ return {"status": "done", "returncode": rc, "timed_out": timed_out, "value": 42}
+
+ thread = tool_streaming.start_background(execution_id, worker)
+ try:
+ assert isinstance(thread, threading.Thread)
+ # Inmediatamente tras lanzar: aún corriendo (el worker duerme 1s).
+ assert tool_streaming.get_status(execution_id) == {"status": "running"}
+ finally:
+ thread.join(timeout=15)
+
+
+def test_start_background_transitions_running_to_done() -> None:
+ """get_status pasa de 'running' a 'done' con los campos devueltos por el worker."""
+ execution_id = _new_id()
+ code = "import time;time.sleep(0.4);print('ok', flush=True)"
+ cmd = [sys.executable, "-c", code]
+
+ def worker() -> dict:
+ rc, timed_out, _cancelled = tool_streaming.run_tool_streaming(
+ cmd, execution_id, timeout=30
+ )
+ return {"status": "done", "returncode": rc, "timed_out": timed_out, "value": 42}
+
+ thread = tool_streaming.start_background(execution_id, worker)
+ # Al principio 'running'.
+ assert tool_streaming.get_status(execution_id)["status"] == "running"
+
+ thread.join(timeout=15)
+ final = tool_streaming.get_status(execution_id)
+ assert final["status"] == "done"
+ assert final["returncode"] == 0
+ assert final["timed_out"] is False
+ assert final["value"] == 42
+
+ # La salida del worker llegó al ring (streaming reutilizado).
+ page = tool_streaming.read(execution_id, 0)
+ texts = [line["text"] for line in page["lines"] if line["stream"] == "stdout"]
+ assert texts == ["ok"]
+
+
+def test_start_background_worker_raises_marks_failed() -> None:
+ """Un worker que lanza -> get_status 'failed' con 'error' (sin reventar el hilo)."""
+ execution_id = _new_id()
+
+ def worker() -> dict:
+ raise RuntimeError("boom-xyz")
+
+ thread = tool_streaming.start_background(execution_id, worker)
+ thread.join(timeout=10)
+
+ status = tool_streaming.get_status(execution_id)
+ assert status["status"] == "failed"
+ assert "boom-xyz" in status["error"]
+
+
+# --- Paginación de findings (fix del límite SSE de 1 MiB) --------------------
+
+
+def _small_finding(i: int) -> dict:
+ """Un finding mínimo y pequeño para los tests de orden/conteo."""
+ return {"check_id": f"check_{i}", "index": i, "severity": "low"}
+
+
+def _sized_finding(i: int, payload_bytes: int) -> dict:
+ """Un finding cuyo tamaño JSON ronda `payload_bytes` (relleno controlado)."""
+ return {"check_id": f"check_{i}", "index": i, "blob": "x" * payload_bytes}
+
+
+def test_set_findings_then_read_paginates_in_order() -> None:
+ """250 findings pequeños -> páginas de 100/100/50, orden preservado, done al final."""
+ execution_id = _new_id()
+ findings = [_small_finding(i) for i in range(250)]
+ tool_streaming.set_findings(execution_id, findings)
+
+ collected: list[dict] = []
+ cursor = 0
+ pages = 0
+ page_sizes: list[int] = []
+ while True:
+ page = tool_streaming.read_findings(execution_id, cursor)
+ pages += 1
+ page_sizes.append(len(page["findings"]))
+ collected.extend(page["findings"])
+ cursor = page["next_cursor"]
+ if page["done"]:
+ break
+ assert pages < 100 # guarda anti-bucle en el propio test
+
+ assert page_sizes == [100, 100, 50]
+ assert cursor == 250
+ # Orden preservado y concatenación == original.
+ assert [f["index"] for f in collected] == list(range(250))
+ assert collected == findings
+
+
+def test_read_findings_unknown_execution_id_empty_done() -> None:
+ """execution_id desconocido -> página vacía, next_cursor=cursor, done=True."""
+ page = tool_streaming.read_findings("does-not-exist", 0)
+ assert page["findings"] == []
+ assert page["next_cursor"] == 0
+ assert page["done"] is True
+
+
+def test_read_findings_byte_budget_caps_page() -> None:
+ """Findings ~50 KiB -> cada página acotada por bytes (<= máximo) y completa."""
+ execution_id = _new_id()
+ # ~50 KiB de relleno por finding: el tope de 256 KiB manda sobre el de 100.
+ findings = [_sized_finding(i, 50 * 1024) for i in range(20)]
+ tool_streaming.set_findings(execution_id, findings)
+
+ collected: list[dict] = []
+ cursor = 0
+ multipage = False
+ guard = 0
+ while True:
+ page = tool_streaming.read_findings(execution_id, cursor)
+ guard += 1
+ assert guard < 100
+ # Ninguna página (con >1 finding) supera el presupuesto de bytes.
+ page_bytes = len(json.dumps(page["findings"]).encode("utf-8"))
+ if len(page["findings"]) > 1:
+ # El array JSON añade comas/corchetes; comparamos la suma de ítems.
+ items_bytes = sum(
+ len(json.dumps(f).encode("utf-8")) for f in page["findings"]
+ )
+ assert items_bytes <= tool_streaming.FINDINGS_PAGE_MAX_BYTES
+ # El tope de bytes se alcanza antes que el de 100 -> hay varias páginas.
+ if not page["done"]:
+ multipage = True
+ assert len(page["findings"]) < 100
+ collected.extend(page["findings"])
+ cursor = page["next_cursor"]
+ if page["done"]:
+ break
+
+ assert multipage is True
+ assert collected == findings
+ assert cursor == 20
+
+
+def test_read_findings_single_oversized_finding_returned() -> None:
+ """Un único finding > presupuesto -> página de 1 (anti-inanición), done=True."""
+ execution_id = _new_id()
+ big = _sized_finding(0, tool_streaming.FINDINGS_PAGE_MAX_BYTES + 10_000)
+ tool_streaming.set_findings(execution_id, [big])
+
+ page = tool_streaming.read_findings(execution_id, 0)
+ assert len(page["findings"]) == 1
+ assert page["findings"][0]["index"] == 0
+ assert page["next_cursor"] == 1
+ assert page["done"] is True
+
+
+def test_read_findings_explicit_limit() -> None:
+ """limit=10 acota la página a <=10 findings aunque quepan más por bytes."""
+ execution_id = _new_id()
+ findings = [_small_finding(i) for i in range(30)]
+ tool_streaming.set_findings(execution_id, findings)
+
+ page = tool_streaming.read_findings(execution_id, 0, limit=10)
+ assert len(page["findings"]) == 10
+ assert page["next_cursor"] == 10
+ assert page["done"] is False
+
+
+def test_read_findings_cursor_at_tail_empty_done() -> None:
+ """cursor en la cola (== total) -> página vacía, done=True, sin reventar."""
+ execution_id = _new_id()
+ findings = [_small_finding(i) for i in range(5)]
+ tool_streaming.set_findings(execution_id, findings)
+
+ page = tool_streaming.read_findings(execution_id, 5)
+ assert page["findings"] == []
+ assert page["next_cursor"] == 5
+ assert page["done"] is True
+
+ # Un escaneo sin findings: primera lectura ya es vacía y done.
+ empty_id = _new_id()
+ tool_streaming.set_findings(empty_id, [])
+ first = tool_streaming.read_findings(empty_id, 0)
+ assert first["findings"] == []
+ assert first["done"] is True
diff --git a/docker/kali/tool_streaming.py b/docker/kali/tool_streaming.py
new file mode 100644
index 0000000..2a3e42b
--- /dev/null
+++ b/docker/kali/tool_streaming.py
@@ -0,0 +1,422 @@
+"""Primitivas de *streaming* de salida de tools para `kali-mcp` (STDLIB PURA).
+
+Por qué un módulo separado (N13 KISS + testeabilidad):
+ `docker/kali/kali_mcp_server.py` importa `mcp`/`anyio` en el top del módulo y
+ esas dependencias NO están en el venv de desarrollo. Para poder cubrir la lógica
+ de streaming con tests unitarios SIN el SDK, toda la mecánica vive aquí usando
+ SOLO la librería estándar (sin `mcp`, sin `anyio`).
+
+Qué provee:
+ - Un *ring buffer* por `execution_id` (thread-safe) que acumula líneas de salida
+ con un `seq` creciente, para lectura incremental por cursor.
+ - `run_tool_streaming(cmd, execution_id, timeout, ...)`: lanza un subproceso,
+ vuelca su stdout/stderr línea a línea al ring en vivo, aplica un timeout y, al
+ expirar, mata el GRUPO de procesos completo (sin huérfanos, N18.3).
+
+Disciplina de seguridad (N-untrusted): la salida de la tool es DATO NO CONFIABLE.
+Aquí se TRANSPORTA verbatim (se trocea en líneas y se guarda tal cual); NUNCA se
+interpreta ni se ejecuta nada derivado de ella.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import threading
+import time
+from collections import deque
+from datetime import datetime, timezone
+from typing import Any, Callable
+
+# Tamaño máximo del ring por ejecución. Acota la memoria: un escaneo largo con
+# mucho verbose no crece sin límite; sólo se retienen las últimas N líneas.
+RING_MAXLEN = 2000
+
+
+def _now_iso() -> str:
+ """Timestamp ISO-8601 en UTC (sufijo 'Z'), estable para la UI/logs."""
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+class _Execution:
+ """Estado de una ejecución: buffer circular de líneas + contador de seq.
+
+ Thread-safe: un lock protege el deque, el contador `_seq` y la bandera `done`,
+ porque el/los hilo(s) lector(es) del subproceso escriben mientras el event loop
+ (u otro hilo) lee por cursor.
+ """
+
+ __slots__ = ("_lines", "_seq", "_done", "_lock")
+
+ def __init__(self) -> None:
+ self._lines: deque[dict[str, Any]] = deque(maxlen=RING_MAXLEN)
+ self._seq = 0
+ self._done = False
+ self._lock = threading.Lock()
+
+ def append(self, stream: str, text: str) -> None:
+ with self._lock:
+ self._seq += 1
+ self._lines.append(
+ {
+ "seq": self._seq,
+ "ts": _now_iso(),
+ "stream": stream,
+ "text": text,
+ }
+ )
+
+ def mark_done(self) -> None:
+ with self._lock:
+ self._done = True
+
+ def read(self, cursor: int) -> tuple[list[dict[str, Any]], int, bool]:
+ """Devuelve (líneas con seq > cursor, next_cursor, done).
+
+ `next_cursor` es el mayor `seq` entregado; si no hay nada nuevo, se
+ devuelve el mismo `cursor` (página vacía, cursor sin cambios).
+ """
+ with self._lock:
+ page = [line for line in self._lines if line["seq"] > cursor]
+ next_cursor = page[-1]["seq"] if page else cursor
+ return page, next_cursor, self._done
+
+
+# Registro global de ejecuciones. Un lock protege la creación/lookup del dict.
+_executions: dict[str, _Execution] = {}
+_registry_lock = threading.Lock()
+
+# --- Registro de cancelación por execution_id (N22.2) ------------------------
+# Para cancelar un escaneo EN CURSO desde fuera (tool `cancel_scan` -> core ->
+# endpoint REST/MCP), hace falta (a) una señal cooperativa y (b) una referencia al
+# proceso vivo para matar su grupo. Separado del ring (salida) y del estado: aquí sólo
+# viven el Popen vivo y un Event de cancelación por ejecución. Reutiliza el kill de
+# grupo que ya existe (`_kill_process_group`), NO duplica el mecanismo (N13).
+_procs: dict[str, "subprocess.Popen"] = {}
+_cancels: dict[str, threading.Event] = {}
+_procs_lock = threading.Lock()
+
+
+def _cancel_event(execution_id: str) -> threading.Event:
+ """Devuelve (creándolo si hace falta) el Event de cancelación de la ejecución."""
+ with _procs_lock:
+ event = _cancels.get(execution_id)
+ if event is None:
+ event = threading.Event()
+ _cancels[execution_id] = event
+ return event
+
+
+def request_cancel(execution_id: str) -> bool:
+ """Solicita cancelar una ejecución: marca el Event y mata su grupo de proceso.
+
+ Idempotente y None-safe: si la ejecución no existe o ya terminó, marca el Event
+ igualmente (por si el proceso aún no se registró) y devuelve ``False`` (no había
+ proceso vivo que matar). Reutiliza :func:`_kill_process_group` (SIGTERM->SIGKILL
+ sobre el grupo, sin huérfanos — N18.3). Devuelve ``True`` si mató un proceso vivo.
+ """
+ with _procs_lock:
+ event = _cancels.get(execution_id)
+ if event is None:
+ event = threading.Event()
+ _cancels[execution_id] = event
+ event.set()
+ proc = _procs.get(execution_id)
+ if proc is not None and proc.poll() is None:
+ _kill_process_group(proc)
+ return True
+ return False
+
+
+def _get_execution(execution_id: str) -> _Execution:
+ with _registry_lock:
+ execution = _executions.get(execution_id)
+ if execution is None:
+ execution = _Execution()
+ _executions[execution_id] = execution
+ return execution
+
+
+def append(execution_id: str, stream: str, text: str) -> None:
+ """Añade una línea de salida (`stream`='stdout'|'stderr') al ring de la ejecución."""
+ _get_execution(execution_id).append(stream, text)
+
+
+def read(execution_id: str, cursor: int = 0) -> dict[str, Any]:
+ """Lee incrementalmente la salida de una ejecución a partir de `cursor`.
+
+ Returns:
+ {"lines": [{seq, ts, stream, text}, ...], "next_cursor": int, "done": bool}
+ Para un `execution_id` desconocido devuelve página vacía y done=False.
+ """
+ with _registry_lock:
+ execution = _executions.get(execution_id)
+ if execution is None:
+ return {"lines": [], "next_cursor": cursor, "done": False}
+ lines, next_cursor, done = execution.read(cursor)
+ return {"lines": lines, "next_cursor": next_cursor, "done": done}
+
+
+# --- Estado de ejecución en segundo plano (por execution_id) -----------------
+# Registro thread-safe del ESTADO (no de la salida) de una ejecución lanzada en
+# background. Separado del ring buffer de líneas: el ring transporta la salida
+# verbatim (dato NO confiable), mientras que esto guarda el veredicto estructurado
+# del worker ({'status': running|done|failed, ...}) para que el cliente lo sondee.
+_status: dict[str, dict[str, Any]] = {}
+_status_lock = threading.Lock()
+
+
+def set_status(execution_id: str, **fields: Any) -> None:
+ """Fija (reemplaza) el dict de estado de `execution_id` con `fields`."""
+ with _status_lock:
+ _status[execution_id] = dict(fields)
+
+
+def get_status(execution_id: str) -> dict[str, Any]:
+ """Devuelve el dict de estado guardado, o {'status':'unknown'} si no existe."""
+ with _status_lock:
+ status = _status.get(execution_id)
+ return dict(status) if status is not None else {"status": "unknown"}
+
+
+# --- Almacén + paginador de findings por execution_id ------------------------
+# Igual que el ring de líneas y el registro de estado, los findings de un escaneo
+# TERMINADO se guardan en memoria indexados por execution_id. A diferencia del
+# ring (que crece en vivo y se lee por `seq`), la lista de findings es ESTABLE y
+# COMPLETA cuando el worker termina; por eso se pagina por ÍNDICE (0-based), no
+# por `seq`.
+#
+# Motivación (fix del límite SSE de 1 MiB): entregar TODOS los findings inline en
+# un único evento del transporte MCP streamable-http revienta cuando el payload
+# real (datos AWS reales iam+s3) supera 1 048 576 B. Se trocea en páginas MUY por
+# debajo de ese límite, igual que el patrón de lectura por cursor de los logs.
+
+# Doble presupuesto por página: tope de BYTES (manda: robustez independiente del
+# tamaño) y tope de CONTEO. Se elige el menor. 256 KiB deja holgura ~2x frente a
+# 1 MiB aun con la doble serialización de FastMCP (bloque de texto JSON +
+# `structuredContent` en el mismo evento SSE). Si el envoltorio pesara más de lo
+# estimado, basta bajar FINDINGS_PAGE_MAX_BYTES (único punto de ajuste).
+FINDINGS_PAGE_MAX_BYTES = 262144
+FINDINGS_PAGE_DEFAULT_LIMIT = 100
+
+# Registro global de findings por ejecución (lista COMPLETA y estable del escaneo
+# terminado). Un lock protege el acceso al dict.
+_findings: dict[str, list[dict[str, Any]]] = {}
+_findings_lock = threading.Lock()
+
+
+def set_findings(execution_id: str, findings: list[dict[str, Any]]) -> None:
+ """Guarda (reemplaza) la lista COMPLETA de findings de `execution_id`.
+
+ La llama el worker al terminar el escaneo, ANTES de publicar el estado `done`,
+ para garantizar que cuando el cliente vea `done` los findings ya estén
+ disponibles para paginar con `read_findings`.
+ """
+ with _findings_lock:
+ _findings[execution_id] = list(findings)
+
+
+def read_findings(
+ execution_id: str, cursor: int = 0, limit: int | None = None
+) -> dict[str, Any]:
+ """Pagina los findings guardados de una ejecución a partir del índice `cursor`.
+
+ Entrega findings consecutivos desde `cursor` hasta agotar el MENOR de: `limit`
+ (o FINDINGS_PAGE_DEFAULT_LIMIT) findings, o FINDINGS_PAGE_MAX_BYTES bytes
+ (medidos con `json.dumps` acumulado). Garantía anti-inanición: si un solo
+ finding supera el presupuesto de bytes, se devuelve igualmente esa página de 1
+ (un finding OCSF individual está muy lejos de 1 MiB; lo que explota es la SUMA).
+
+ Args:
+ execution_id: id de la ejecución (el devuelto por `prowler_scan`).
+ cursor: índice 0-based del primer finding a devolver; 0 desde el principio.
+ limit: tope de findings por página; None usa FINDINGS_PAGE_DEFAULT_LIMIT.
+
+ Returns:
+ {"findings": [...página...], "next_cursor": int, "done": bool}.
+ `execution_id` desconocido o `cursor` en/más allá del final -> página vacía
+ con done=True (no revienta).
+ """
+ with _findings_lock:
+ stored = _findings.get(execution_id)
+ items = list(stored) if stored is not None else None
+
+ if items is None:
+ return {"findings": [], "next_cursor": cursor, "done": True}
+
+ total = len(items)
+ start = cursor if cursor > 0 else 0
+ if start >= total:
+ return {"findings": [], "next_cursor": cursor, "done": True}
+
+ max_count = (
+ limit if limit is not None and limit > 0 else FINDINGS_PAGE_DEFAULT_LIMIT
+ )
+
+ page: list[dict[str, Any]] = []
+ size = 0
+ index = start
+ while index < total and len(page) < max_count:
+ finding = items[index]
+ encoded = len(json.dumps(finding).encode("utf-8"))
+ # El presupuesto de bytes manda: si añadir este finding desbordara el tope
+ # y la página ya tiene al menos uno, se cierra la página aquí. Si la página
+ # está vacía se añade igualmente (anti-inanición).
+ if page and size + encoded > FINDINGS_PAGE_MAX_BYTES:
+ break
+ page.append(finding)
+ size += encoded
+ index += 1
+
+ return {"findings": page, "next_cursor": index, "done": index >= total}
+
+
+def start_background(
+ execution_id: str, worker: Callable[[], dict[str, Any]]
+) -> threading.Thread:
+ """Lanza `worker()` en un hilo demonio y registra su estado por `execution_id`.
+
+ Marca el estado inicial {'status':'running'} ANTES de arrancar el hilo (así un
+ sondeo inmediato ve 'running', nunca 'unknown'), corre `worker()` (callable sin
+ args que devuelve el dict de estado final) y, al terminar, guarda ese dict como
+ estado final. Si `worker` lanza, guarda {'status':'failed','error':str(exc)}.
+ Devuelve el `Thread` (ya arrancado) por si el caller quiere `join`.
+ """
+ set_status(execution_id, status="running")
+
+ def _runner() -> None:
+ try:
+ result = worker()
+ set_status(execution_id, **result)
+ except Exception as exc: # noqa: BLE001 - cualquier fallo -> estado failed
+ set_status(execution_id, status="failed", error=str(exc))
+
+ thread = threading.Thread(target=_runner, daemon=True)
+ thread.start()
+ return thread
+
+
+def _pump(pipe: Any, execution: _Execution, stream: str) -> None:
+ """Hilo lector: vuelca `pipe` línea a línea al ring hasta EOF."""
+ try:
+ for raw in iter(pipe.readline, ""):
+ if raw == "":
+ break
+ execution.append(stream, raw.rstrip("\n"))
+ finally:
+ try:
+ pipe.close()
+ except Exception: # noqa: BLE001 - cierre best-effort
+ pass
+
+
+def _kill_process_group(proc: subprocess.Popen) -> None:
+ """Mata el GRUPO de procesos del subproceso (SIGTERM, luego SIGKILL).
+
+ El subproceso se lanza con `start_new_session=True`, así que es líder de su
+ propio grupo; matar el grupo entero evita huérfanos (N18.3) aunque Prowler
+ lance hijos.
+ """
+ try:
+ pgid = os.getpgid(proc.pid)
+ except ProcessLookupError:
+ return
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ try:
+ os.killpg(pgid, sig)
+ except ProcessLookupError:
+ return
+ try:
+ proc.wait(timeout=5)
+ return
+ except subprocess.TimeoutExpired:
+ continue
+
+
+def run_tool_streaming(
+ cmd: list[str],
+ execution_id: str,
+ timeout: int,
+ env: dict[str, str] | None = None,
+ cwd: str | None = None,
+) -> tuple[int, bool]:
+ """Ejecuta `cmd` volcando su salida en vivo al ring de `execution_id`.
+
+ stdout y stderr se leen por separado (cada uno en su hilo) y se etiquetan como
+ 'stdout'/'stderr' en el ring. Al terminar (o al expirar el timeout) la ejecución
+ se marca `done`.
+
+ Args:
+ cmd: comando y argumentos (lista; sin shell).
+ execution_id: identificador de la ejecución (clave del ring buffer).
+ timeout: segundos máximos antes de matar el grupo de procesos.
+ env: entorno del subproceso (None = heredar el del proceso actual).
+ cwd: directorio de trabajo del subproceso.
+
+ Returns:
+ (returncode, timed_out, cancelled). En timeout `timed_out=True`; en
+ cancelación externa (`request_cancel`) `cancelled=True`. `returncode` es el del
+ proceso tras matar el grupo (puede ser negativo = señal). `cancelled` tiene
+ prioridad semántica sobre `timed_out` para el caller.
+ """
+ execution = _get_execution(execution_id)
+ cancel_event = _cancel_event(execution_id) # asegura el Event antes del Popen
+ proc = subprocess.Popen( # noqa: S603 - cmd controlado por el caller, sin shell
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ bufsize=1, # line-buffered: la salida llega al ring a medida que ocurre
+ env=env,
+ cwd=cwd,
+ start_new_session=True, # grupo propio -> killpg sin huérfanos
+ )
+ # Registra el proceso vivo para que `request_cancel` pueda matar su grupo.
+ with _procs_lock:
+ _procs[execution_id] = proc
+
+ readers = [
+ threading.Thread(target=_pump, args=(proc.stdout, execution, "stdout"), daemon=True),
+ threading.Thread(target=_pump, args=(proc.stderr, execution, "stderr"), daemon=True),
+ ]
+ for reader in readers:
+ reader.start()
+
+ timed_out = False
+ cancelled = False
+ deadline = time.monotonic() + timeout
+ try:
+ while True:
+ # Cancelación externa: mata el grupo y sale (prioridad sobre el timeout).
+ if cancel_event.is_set():
+ _kill_process_group(proc)
+ break
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ timed_out = True
+ _kill_process_group(proc)
+ break
+ try:
+ proc.wait(timeout=min(remaining, 0.5))
+ break
+ except subprocess.TimeoutExpired:
+ continue
+ finally:
+ # Asegura que no quede el grupo vivo pase lo que pase.
+ if proc.poll() is None:
+ _kill_process_group(proc)
+ for reader in readers:
+ reader.join(timeout=5)
+ execution.mark_done()
+ # `request_cancel` pudo matar el proceso directamente (proc.wait() retornó por
+ # el kill, no por el Event): consultar el Event es la fuente de verdad de la
+ # cancelación, independientemente de qué rama cerró el bucle.
+ cancelled = cancel_event.is_set()
+ with _procs_lock:
+ _procs.pop(execution_id, None)
+ _cancels.pop(execution_id, None)
+
+ returncode = proc.returncode if proc.returncode is not None else -1
+ return returncode, timed_out, cancelled