Buckets:

download
raw
11 kB
#!/usr/bin/env python3
"""
Zen-AI-Pentest Full Orchestrator Proxy
Executes all repo checks and saves a comprehensive JSON report.
"""
import json
import os
import shlex
import subprocess
import threading
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
REPO_PATH = "/home/atakan/Zen-Ai-Pentest"
REPORT_PATH = "/home/atakan/Zen-Ai-Pentest/reports/n8n_full_report.json"
# Dangerous characters that must never appear in safe command arguments
_DANGEROUS_CHARS = set(";|&$()`<>{}[]")
def _run_cmd_internal(cmd, timeout=120):
"""
INTERNAL USE ONLY – runs a hardcoded shell command via sh -c (shell=False).
Must NEVER be called with user-supplied input.
"""
try:
result = subprocess.run(
["sh", "-c", cmd],
shell=False,
capture_output=True,
text=True,
timeout=timeout,
cwd=REPO_PATH,
)
return result.stdout, result.stderr, result.returncode
except subprocess.TimeoutExpired:
return "", f"Command timed out after {timeout}s", -1
except Exception as e:
return "", str(e), -1
def _run_cmd_safe(cmd_list, timeout=120):
"""
Safe command execution with shell=False.
Accepts a list of arguments (never a string).
"""
try:
result = subprocess.run(
cmd_list,
shell=False,
capture_output=True,
text=True,
timeout=timeout,
cwd=REPO_PATH,
)
return result.stdout, result.stderr, result.returncode
except subprocess.TimeoutExpired:
return "", f"Command timed out after {timeout}s", -1
except Exception as e:
return "", str(e), -1
def perform_full_orchestrator():
os.makedirs(os.path.dirname(REPORT_PATH), exist_ok=True)
venv = ". /home/atakan/Zen-Ai-Pentest/.venv/bin/activate && "
git_out, git_err, git_code = _run_cmd_internal("timeout 60 git pull 2>&1 || true", 90)
black_out, _, _ = _run_cmd_internal(
venv + "timeout 30 black --check . 2>&1 || echo 'BLACK_NOT_INSTALLED_OR_FAILED'",
45,
)
isort_out, _, _ = _run_cmd_internal(
venv + "timeout 30 isort --check-only . 2>&1 || echo 'ISORT_NOT_INSTALLED_OR_FAILED'",
45,
)
ruff_out, _, _ = _run_cmd_internal(venv + "timeout 45 ruff check . 2>&1 || echo 'RUFF_FAILED'", 60)
unit_out, _, _ = _run_cmd_internal(
venv
+ "timeout 90 pytest tests/test_api_main.py tests/test_api_schemas.py tests/test_core_state_machine.py tests/test_nmap_integration.py tests/test_guardrails.py -q --tb=short --continue-on-collection-errors 2>&1 || true",
120,
)
integration_out, _, _ = _run_cmd_internal(
venv + "timeout 60 pytest tests/test_api_integration.py -q --tb=short --continue-on-collection-errors 2>&1 || true",
90,
)
sec_out, _, _ = _run_cmd_internal(venv + "timeout 60 bandit -r zen_ai_pentest -ll -ii 2>&1 || true", 90)
dep_out, _, _ = _run_cmd_internal(
venv
+ "timeout 60 sh -c 'pip-audit -r requirements.txt; exit 0' 2>&1 || timeout 60 safety check 2>&1 || echo 'NO_DEP_SCAN_TOOL'",
90,
)
cov_out, _, _ = _run_cmd_internal(
venv + "timeout 90 pytest tests/test_agent_base.py --cov=agents.agent_base -q 2>&1 || true",
120,
)
docker_out, _, _ = _run_cmd_internal("timeout 30 docker compose config 2>&1 || true", 45)
makefile_out, _, _ = _run_cmd_internal("timeout 15 make help 2>&1 || true", 30)
req_out, _, _ = _run_cmd_internal(venv + "timeout 15 pip check 2>&1 || true", 30)
def has_error(output, markers):
s = output.lower()
return any(m in s for m in markers)
def pytest_ok(output):
"""Check pytest output for actual failures by parsing the summary line."""
lines = output.strip().splitlines()
summary_lines = [
line
for line in lines
if " in " in line and "s" in line and any(c.isdigit() for c in line) and "warnings summary" not in line.lower()
]
if not summary_lines:
return False
last_summary = summary_lines[-1]
return "failed" not in last_summary and "error" not in last_summary.lower()
report = {
"timestamp": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"repo": "SHAd0WTAka/Zen-Ai-Pentest",
"checks": {
"gitPull": {
"ok": not has_error(git_out, ["fatal", "error"]) and git_code == 0,
"output": git_out + git_err,
},
"codeQuality": {
"ok": not has_error(
black_out,
["black_not_installed_or_failed", "would reformat"],
)
and not has_error(ruff_out, ["ruff_failed"]),
"black": black_out,
"isort": isort_out,
"ruff": ruff_out,
},
"unitTests": {"ok": pytest_ok(unit_out), "output": unit_out},
"integrationTests": {
"ok": pytest_ok(integration_out),
"output": integration_out,
},
"securityScan": {
"ok": True,
"issuesFound": "Issue:" in sec_out or "Severity:" in sec_out,
"output": sec_out,
},
"dependencyScan": {
"ok": not dep_out.strip().endswith("NO_DEP_SCAN_TOOL"),
"output": dep_out,
},
"coverage": {"ok": "%" in cov_out, "output": cov_out},
"dockerValidation": {
"ok": not has_error(docker_out, ["error", "invalid"]),
"output": docker_out,
},
"makefileHealth": {
"ok": "test" in makefile_out.lower() or "coverage" in makefile_out.lower(),
"output": makefile_out,
},
"requirementsCheck": {
"ok": "No broken requirements" in req_out or req_out.strip() == "" or "requires" in req_out.lower(),
"output": req_out,
},
},
"overallStatus": "completed",
}
with open(REPORT_PATH, "w") as f:
json.dump(report, f, indent=2)
class Handler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def do_POST(self):
if self.path == "/exec":
self._handle_exec()
elif self.path == "/save-report":
self._handle_save_report()
elif self.path == "/trigger-orchestrator":
self._handle_trigger()
elif self.path == "/run-full-orchestrator":
self._handle_run_sync()
else:
self.send_response(404)
self.end_headers()
def do_GET(self):
if self.path == "/report":
self._handle_get_report()
else:
self.send_response(404)
self.end_headers()
def _handle_exec(self):
length = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(length).decode("utf-8"))
command = body.get("command", "")
# Security: Parse command safely and validate strictly
try:
cmd_parts = shlex.split(command)
except ValueError:
self._respond_json({"error": "Invalid command syntax"}, status=400)
return
if not cmd_parts:
self._respond_json({"error": "Empty command"}, status=400)
return
# Strict allowlist: exact match on the base command
allowed_commands = {
"pytest",
"black",
"isort",
"ruff",
"git",
"npm",
"pip",
}
base_cmd = cmd_parts[0]
if base_cmd not in allowed_commands:
self._respond_json({"error": "Command not allowed"}, status=403)
return
# Reject any argument containing dangerous shell metacharacters
for part in cmd_parts:
if any(ch in part for ch in _DANGEROUS_CHARS):
self._respond_json({"error": "Dangerous characters detected"}, status=403)
return
stdout, stderr, code = _run_cmd_safe(cmd_parts, body.get("timeout", 120))
self._respond_json({"stdout": stdout, "stderr": stderr, "exitCode": code})
def _handle_save_report(self):
length = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(length).decode("utf-8"))
path = body.get("path", REPORT_PATH)
# Security: Validate path to prevent path traversal
reports_dir = os.path.abspath(os.path.join(REPO_PATH, "reports"))
try:
resolved_path = os.path.abspath(path)
if not resolved_path.startswith(reports_dir):
self._respond_json({"saved": False, "error": "Path not allowed"}, status=403)
return
except ValueError:
self._respond_json({"saved": False, "error": "Invalid path"}, status=400)
return
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
json.dump(body.get("data", {}), f, indent=2)
self._respond_json({"saved": True, "path": path})
except Exception as e:
self._respond_json({"saved": False, "error": str(e)}, status=500)
def _handle_trigger(self):
thread = threading.Thread(target=perform_full_orchestrator)
thread.start()
self._respond_json(
{
"started": True,
"message": "Orchestrator started in background. Check /report in a few minutes.",
"reportPath": REPORT_PATH,
}
)
def _handle_run_sync(self):
perform_full_orchestrator()
try:
with open(REPORT_PATH) as f:
report = json.load(f)
self._respond_json(report)
except Exception as e:
self._respond_json({"error": str(e)}, status=500)
def _handle_get_report(self):
try:
with open(REPORT_PATH) as f:
report = json.load(f)
self._respond_json(report)
except FileNotFoundError:
self._respond_json(
{"error": "Report not found yet. Run /trigger-orchestrator first."},
status=404,
)
except Exception as e:
self._respond_json({"error": str(e)}, status=500)
def _respond_json(self, data, status=200):
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(data).encode("utf-8"))
if __name__ == "__main__":
server = HTTPServer(("127.0.0.1", 9876), Handler)
print("Zen-AI-Pentest Orchestrator Proxy running on http://127.0.0.1:9876")
server.serve_forever()

Xet Storage Details

Size:
11 kB
·
Xet hash:
2d2eb85b1cd09042a973e0f4450d58386ff6f032d43e80f69bd0c70795925265

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.