Buckets:
"""
Zen-AI-Pentest API Server
FastAPI-basiertes Backend für das Pentesting-Framework.
"""
import os
import sys
from pathlib import Path
# Load .env file first (before any other imports)
from dotenv import load_dotenv
load_dotenv()
# Windows Asyncio Fix (must be first)
if sys.platform == "win32":
import warnings
warnings.filterwarnings("ignore", message="unclosed transport", category=ResourceWarning)
# Add parent to path
sys.path.insert(0, str(Path(__file__).parent.parent))
import json
import logging
import time
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from typing import Any, List, Optional
from fastapi import (
BackgroundTasks,
Depends,
FastAPI,
HTTPException,
Request,
Response,
WebSocket,
WebSocketDisconnect,
status,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.staticfiles import StaticFiles
from api.auth_deps import (
NEW_AUTH_AVAILABLE,
_jwt_handler,
_password_hasher,
optional_auth,
verify_admin_credentials,
verify_token,
)
from api.csrf_protection import csrf_protection, require_csrf
from api.rate_limiter import (
AuthRateLimitDependency,
RateLimitDependency,
RateLimitInfo,
RateLimitMiddleware,
check_auth_rate_limit,
rate_limit,
)
from api.schemas import (
FindingCreate,
FindingResponse,
ReportCreate,
ReportResponse,
ScanCreate,
ScanResponse,
ScanUpdate,
ScheduledScanCreate,
ScheduledScanResponse,
ScheduledScanUpdate,
TokenResponse,
ToolExecuteRequest,
ToolExecuteResponse,
UserLogin,
)
from api.security_logging import sanitize_for_log
from api.websocket import ConnectionManager
from api.websocket_manager import manager
from database.crud import (
create_finding,
create_report,
create_scan,
get_findings,
get_reports,
get_scan,
get_scans,
update_scan_status,
)
from database.models import Report, SessionLocal, get_db, init_db
# Import Agent v2 routes
try:
from api.routes.agents_v2 import router as agents_v2_router
AGENTS_V2_AVAILABLE = True
except ImportError as e:
logger = logging.getLogger(__name__)
logger.warning(f"Agent v2 routes not available: {e}")
AGENTS_V2_AVAILABLE = False
# Import Evidence routes
try:
from api.routes.evidence import router as evidence_router
EVIDENCE_ROUTES_AVAILABLE = True
except ImportError as e:
logger = logging.getLogger(__name__)
logger.warning(f"Evidence routes not available: {e}")
EVIDENCE_ROUTES_AVAILABLE = False
# Import Reports routes
try:
from api.routes.reports import router as reports_router
REPORTS_ROUTES_AVAILABLE = True
except ImportError as e:
logger = logging.getLogger(__name__)
logger.warning(f"Reports routes not available: {e}")
REPORTS_ROUTES_AVAILABLE = False
# Import Attack Path routes
try:
from api.routes.attack_path import router as attack_path_router
ATTACK_PATH_ROUTES_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"Attack Path routes not available: {e}")
ATTACK_PATH_ROUTES_AVAILABLE = False
# Import Secure Authentication routes
try:
from api.routes.secure_auth import router as secure_auth_router
SECURE_AUTH_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"Secure Auth routes not available: {e}")
SECURE_AUTH_AVAILABLE = False
# Import MCP routes
try:
from api.routes.mcp import router as mcp_router
MCP_ROUTES_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"MCP routes not available: {e}")
MCP_ROUTES_AVAILABLE = False
# Import v1 API routes
try:
from api.routes.v1 import api_v1_router
V1_ROUTES_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"V1 routes not available: {e}")
V1_ROUTES_AVAILABLE = False
# Import Kimi Terminal routes
try:
from api.routes.kimi_chat import router as kimi_chat_router
KIMI_TERMINAL_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"Kimi Terminal routes not available: {e}")
KIMI_TERMINAL_AVAILABLE = False
# Import Auth Bridge routes
try:
from api.routes.auth_bridge import router as auth_bridge_router
AUTH_BRIDGE_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"Auth Bridge routes not available: {e}")
AUTH_BRIDGE_AVAILABLE = False
# Import new JWT Auth Routes
try:
from api.routes.auth_routes import router as jwt_auth_router
JWT_AUTH_ROUTES_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"JWT Auth routes not available: {e}")
JWT_AUTH_ROUTES_AVAILABLE = False
# Import Risk Scoring routes
try:
from api.routes.risk import router as risk_router
RISK_ROUTES_AVAILABLE = True
except Exception as e:
logger = logging.getLogger(__name__)
logger.warning(f"Risk routes not available: {e}")
RISK_ROUTES_AVAILABLE = False
# Import Legacy route modules (extracted from this file)
from api.routes.legacy_auth import router as legacy_auth_router
from api.routes.legacy_misc import router as legacy_misc_router
from api.routes.legacy_scans import router as legacy_scans_router
from api.routes.legacy_schedules import router as legacy_schedules_router
from api.routes.legacy_settings import router as legacy_settings_router
from api.routes.legacy_tools import router as legacy_tools_router
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# WebSocket Manager
ws_manager = ConnectionManager()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan handler"""
# Startup
logger.info("Starting up Zen-AI-Pentest API...")
init_db()
logger.info("Database initialized")
# Initialize evidence database
try:
from evidence.models import init_evidence_db
init_evidence_db()
logger.info("Evidence database initialized")
except Exception as e:
logger.warning(f"Could not initialize evidence database: {e}")
# Initialize auth database
if NEW_AUTH_AVAILABLE:
try:
from database.auth_models import init_auth_db
init_auth_db()
logger.info("Auth database initialized")
# Create default admin user if not exists
from database.auth_models import (
SessionLocal,
UserRole,
create_user,
get_user_by_username,
)
db = SessionLocal()
try:
admin = get_user_by_username(db, "admin")
if not admin:
admin_pass = os.getenv("ADMIN_PASSWORD")
if not admin_pass:
logger.warning("ADMIN_PASSWORD not set; skipping default admin creation")
else:
create_user(
db,
username="admin",
email="admin@zen-pentest.local",
hashed_password=_password_hasher.hash_password(admin_pass),
role=UserRole.ADMIN,
)
logger.info("Default admin user created")
finally:
db.close()
except Exception as e:
logger.warning(f"Could not initialize auth database: {e}")
yield
# Shutdown
logger.info("Shutting down...")
# Custom dark theme CSS for Swagger UI
SWAGGER_UI_DARK_CSS = """
/* Zen Dark Theme for Swagger UI */
:root {
--bg-primary: #0a0a0f;
--bg-secondary: #14141f;
--bg-card: #1a1a2e;
--text-primary: #e2e8f0;
--text-secondary: #94a3b8;
--accent: #06b6d4;
--accent-hover: #0891b2;
--border: #27273a;
--success: #10b981;
--warning: #f59e0b;
--error: #ef4444;
}
body {
background: var(--bg-primary) !important;
color: var(--text-primary) !important;
}
.swagger-ui {
background: var(--bg-primary);
color: var(--text-primary);
filter: invert(1) hue-rotate(180deg);
}
.swagger-ui .topbar {
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%) !important;
border-bottom: 1px solid var(--border);
}
.swagger-ui .information-container {
background: var(--bg-secondary) !important;
}
.swagger-ui .scheme-container {
background: var(--bg-card) !important;
border: 1px solid var(--border);
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.swagger-ui .opblock {
background: var(--bg-card) !important;
border: 1px solid var(--border) !important;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
}
.swagger-ui .opblock-tag {
color: var(--text-primary) !important;
border-bottom: 1px solid var(--border);
}
.swagger-ui .opblock .opblock-summary-method {
background: var(--accent) !important;
color: #000 !important;
font-weight: 600;
}
.swagger-ui .opblock.opblock-get { border-color: var(--accent); }
.swagger-ui .opblock.opblock-post { border-color: var(--success); }
.swagger-ui .opblock.opblock-put { border-color: var(--warning); }
.swagger-ui .opblock.opblock-delete { border-color: var(--error); }
.swagger-ui .btn {
background: var(--bg-secondary) !important;
border: 1px solid var(--border) !important;
color: var(--text-primary) !important;
}
.swagger-ui .btn.authorize {
background: var(--success) !important;
color: #000 !important;
}
.swagger-ui input[type=text],
.swagger-ui textarea,
.swagger-ui select {
background: var(--bg-secondary) !important;
border: 1px solid var(--border) !important;
color: var(--text-primary) !important;
}
.swagger-ui .model-box {
background: var(--bg-secondary) !important;
}
.swagger-ui table thead tr th {
background: var(--bg-secondary) !important;
color: var(--text-primary) !important;
border-bottom: 2px solid var(--border);
}
.swagger-ui .responses-inner h4,
.swagger-ui .responses-inner h5 {
color: var(--text-primary) !important;
}
.swagger-ui .response-col_status {
color: var(--text-primary) !important;
}
/* Toggle Switch for Dark/Light Mode */
.theme-toggle {
position: fixed;
top: 20px;
right: 20px;
z-index: 9999;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 30px;
padding: 8px 16px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
color: var(--text-primary);
font-size: 14px;
transition: all 0.3s ease;
}
.theme-toggle:hover {
background: var(--accent);
color: #000;
}
"""
# ReDoc Dark Theme
REDOC_DARK_CSS = """
:root {
--bg-primary: #0a0a0f;
--bg-secondary: #14141f;
--text-primary: #e2e8f0;
--text-secondary: #94a3b8;
--accent: #06b6d4;
}
body {
background: var(--bg-primary) !important;
color: var(--text-primary) !important;
}
.menu-content {
background: var(--bg-secondary) !important;
border-right: 1px solid #27273a;
}
.api-content {
background: var(--bg-primary) !important;
}
h1, h2, h3, h4, h5, h6 {
color: var(--text-primary) !important;
}
p, span, div {
color: var(--text-secondary) !important;
}
code {
background: #1e1e2e !important;
color: var(--accent) !important;
}
pre {
background: #1e1e2e !important;
border: 1px solid #27273a !important;
}
"""
app = FastAPI(
title="Zen-AI-Pentest API",
description="""Professional Pentesting Framework API
## API Documentation Dark Mode
Switch between **Swagger UI** (`/docs`) and **ReDoc** (`/redoc`) - both support dark themes.
""",
version="2.2.0",
lifespan=lifespan,
docs_url=None, # Disable default docs - we'll create custom
redoc_url=None, # Disable default redoc - we'll create custom
)
# Mount static files directory
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "static")), name="static")
# =============================================================================
# CORS Configuration
# =============================================================================
# Load allowed origins from environment variable
cors_origins_str = os.getenv(
"CORS_ORIGINS",
"http://localhost:3000,http://localhost:8000,http://localhost:5173,http://127.0.0.1:3000,http://127.0.0.1:8000,http://127.0.0.1:5173",
)
ALLOWED_ORIGINS = [origin.strip() for origin in cors_origins_str.split(",")]
# Always allow Cloudflare Pages deployments
CLOUDFLARE_ORIGINS = [
"https://8f71ac40.zen-alpha-pentest.pages.dev",
"https://zen-alpha-pentest.pages.dev",
"https://ee3b90d9.zen-alpha-pentest.pages.dev",
"https://03c8d80c.zen-alpha-pentest.pages.dev",
"https://6c705498.zen-alpha-pentest.pages.dev",
"https://774236f6.zen-alpha-pentest.pages.dev",
"https://ff508d54.zen-alpha-pentest.pages.dev",
"https://d94de0db.zen-alpha-pentest.pages.dev",
"https://2896a912.zen-alpha-pentest.pages.dev",
"https://486b8269.zen-alpha-pentest.pages.dev",
"https://ae89eae8.zen-alpha-pentest.pages.dev",
"https://998aa233.zen-alpha-pentest.pages.dev",
"https://aa445635.zen-alpha-pentest.pages.dev",
"https://584dfeff.zen-alpha-pentest-dmn.pages.dev",
"https://zen-alpha-pentest-dmn.pages.dev",
]
# Cloudflare Tunnel for backend access
CLOUDFLARE_TUNNEL_ORIGINS = [
"https://air-promise-syndrome-delhi.trycloudflare.com",
"https://acquired-teeth-reasonably-ordering.trycloudflare.com",
"https://nikon-enemies-cbs-practitioners.trycloudflare.com",
]
ALLOWED_ORIGINS.extend([o for o in CLOUDFLARE_ORIGINS if o not in ALLOWED_ORIGINS])
ALLOWED_ORIGINS.extend([o for o in CLOUDFLARE_TUNNEL_ORIGINS if o not in ALLOWED_ORIGINS])
# Security Headers Middleware
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
"""Add security headers to all responses."""
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
return response
# CORS Middleware
import re
DEV_ORIGINS = [
"http://localhost:3000",
"http://localhost:5173",
"http://localhost:4173",
"http://127.0.0.1:3000",
"http://127.0.1:5173",
"http://127.0.0.1:4173",
"http://localhost:8000",
"http://127.0.0.1:8000",
]
ALL_ALLOWED_ORIGINS = list(set(DEV_ORIGINS + ALLOWED_ORIGINS + CLOUDFLARE_ORIGINS + CLOUDFLARE_TUNNEL_ORIGINS))
def is_origin_allowed(origin: str) -> bool:
"""Prüft ob eine Origin erlaubt ist (inkl. Pattern-Matching)"""
if not origin:
return False
if origin in ALL_ALLOWED_ORIGINS:
return True
if re.match(r"https://[a-z0-9-]+\.zen-alpha-pentest\.pages\.dev", origin):
return True
if re.match(r"https://[a-z-]+\.trycloudflare\.com", origin):
return True
return False
class DynamicCORSProcessor:
"""Middleware um CORS für dynamische Origins zu ermöglichen"""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] == "http":
headers = dict(scope.get("headers", []))
origin = headers.get(b"origin", b"").decode() if b"origin" in headers else None
if origin and is_origin_allowed(origin):
scope["cors_origin"] = origin
await self.app(scope, receive, send)
app.add_middleware(
CORSMiddleware,
allow_origins=ALL_ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["X-Request-ID", "X-RateLimit-Remaining", "X-RateLimit-Reset"],
max_age=86400,
)
app.add_middleware(
RateLimitMiddleware,
requests_per_minute=int(os.getenv("RATE_LIMIT_ANONYMOUS_RPM", "20")),
burst_size=int(os.getenv("RATE_LIMIT_ANONYMOUS_BURST", "5")),
)
# =============================================================================
# CUSTOM API DOCUMENTATION WITH DARK MODE
# =============================================================================
from fastapi.responses import HTMLResponse, JSONResponse
def get_zen_swagger_html() -> str:
"""Generate custom Swagger UI HTML with dark theme"""
try:
with open(os.path.join(os.path.dirname(__file__), "static", "swagger_dark.html"), "r") as f:
return f.read()
except Exception:
pass
html_template = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zen-AI-Pentest API - Swagger UI</title>
<link rel="shortcut icon" href="/favicon.ico">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
<style>
:root {
--bg-primary: #0a0a0f;
--bg-secondary: #14141f;
--bg-card: #1a1a2e;
--text-primary: #e2e8f0;
--text-secondary: #94a3b8;
--accent: #06b6d4;
--accent-hover: #0891b2;
--border: #27273a;
--success: #10b981;
--warning: #f59e0b;
--error: #ef4444;
}
* { scrollbar-width: thin; scrollbar-color: #27273a #0a0a0f; }
body { background: var(--bg-primary) !important; margin: 0; padding: 0; }
.swagger-ui { background: var(--bg-primary) !important; color: var(--text-primary) !important; }
.swagger-ui .topbar { background: linear-gradient(135deg, #1a1a2e 0%, #0f172a 100%) !important; border-bottom: 1px solid var(--border); padding: 15px 0; }
.swagger-ui .topbar .download-url-wrapper input[type=text] { background: var(--bg-secondary) !important; color: var(--text-primary) !important; border: 1px solid var(--border) !important; border-radius: 6px; padding: 8px 12px; }
.swagger-ui .topbar .download-url-wrapper .download-url-button { background: var(--accent) !important; color: #000 !important; font-weight: 600; border-radius: 6px; }
.swagger-ui .information-container { background: var(--bg-secondary) !important; padding: 30px 0; }
.swagger-ui .info { max-width: 1400px; margin: 0 auto; padding: 0 20px; }
.swagger-ui .info .title { color: var(--accent) !important; font-size: 2.8em; font-weight: 700; text-shadow: 0 0 40px rgba(6,182,212,0.3); margin-bottom: 10px; }
.swagger-ui .info .version { background: var(--accent) !important; color: #000 !important; padding: 4px 12px; border-radius: 4px; font-weight: 600; vertical-align: middle; }
.swagger-ui .info .description { color: var(--text-secondary) !important; font-size: 1.1em; line-height: 1.6; }
.swagger-ui .scheme-container { background: var(--bg-card) !important; border: 1px solid var(--border); border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.3); margin: 20px; padding: 20px; }
.swagger-ui .opblock-tag { font-size: 1.3em; color: var(--text-primary) !important; border-bottom: 2px solid var(--border); padding: 20px 0; margin: 0 20px; }
.swagger-ui .opblock { background: var(--bg-card) !important; border-radius: 12px; margin: 15px 20px; border: 1px solid var(--border) !important; box-shadow: 0 2px 10px rgba(0,0,0,0.2); }
.swagger-ui .opblock-summary { padding: 15px 20px; }
.swagger-ui .opblock .opblock-summary-method { border-radius: 6px; font-weight: 600; min-width: 70px; text-align: center; }
.swagger-ui .opblock.opblock-get .opblock-summary-method { background: var(--accent) !important; color: #000 !important; }
.swagger-ui .opblock.opblock-post .opblock-summary-method { background: var(--success) !important; color: #000 !important; }
.swagger-ui .opblock.opblock-put .opblock-summary-method { background: var(--warning) !important; color: #000 !important; }
.swagger-ui .opblock.opblock-delete .opblock-summary-method { background: var(--error) !important; color: #fff !important; }
.swagger-ui .opblock .opblock-summary-path { color: var(--text-primary) !important; }
.swagger-ui .opblock .opblock-summary-description { color: var(--text-secondary) !important; }
.swagger-ui .parameter__name { color: var(--accent) !important; font-weight: 600; }
.swagger-ui .parameter__type { color: var(--text-secondary) !important; }
.swagger-ui table thead tr th { background: var(--bg-secondary) !important; color: var(--text-primary) !important; border-bottom: 2px solid var(--border); padding: 12px; }
.swagger-ui table tbody tr td { background: var(--bg-card) !important; color: var(--text-primary) !important; border-bottom: 1px solid var(--border); padding: 12px; }
.swagger-ui .model-box { background: var(--bg-secondary) !important; border: 1px solid var(--border) !important; border-radius: 8px; padding: 15px; }
.swagger-ui .model-title { color: var(--accent) !important; }
.swagger-ui .prop-type { color: var(--success) !important; }
.swagger-ui .responses-inner h4, .swagger-ui .responses-inner h5 { color: var(--text-primary) !important; }
.swagger-ui .response-col_status { color: var(--text-primary) !important; font-weight: 600; }
.swagger-ui input[type=text], .swagger-ui input[type=password], .swagger-ui textarea, .swagger-ui select { background: var(--bg-secondary) !important; border: 1px solid var(--border) !important; color: var(--text-primary) !important; border-radius: 6px; padding: 8px 12px; }
.swagger-ui .btn { background: var(--bg-secondary) !important; border: 1px solid var(--border) !important; color: var(--text-primary) !important; border-radius: 6px; padding: 8px 16px; transition: all 0.2s ease; }
.swagger-ui .btn:hover { background: var(--accent) !important; color: #000 !important; border-color: var(--accent) !important; }
.swagger-ui .btn.authorize { background: var(--success) !important; color: #000 !important; }
.swagger-ui section.models { background: var(--bg-card) !important; border: 1px solid var(--border) !important; border-radius: 12px; margin: 20px; }
.swagger-ui section.models h4 { color: var(--text-primary) !important; background: var(--bg-secondary) !important; padding: 15px 20px; margin: 0; border-bottom: 1px solid var(--border); }
.swagger-ui .model { color: var(--text-primary) !important; }
.swagger-ui .model-title { color: var(--text-primary) !important; font-weight: 600; }
.theme-toggle { position: fixed; top: 20px; right: 20px; z-index: 10000; background: var(--bg-card); border: 1px solid var(--border); border-radius: 50px; padding: 10px 20px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: var(--text-primary); font-size: 14px; font-weight: 500; transition: all 0.3s ease; box-shadow: 0 4px 20px rgba(0,0,0,0.3); }
.theme-toggle:hover { background: var(--accent); color: #000; border-color: var(--accent); transform: translateY(-2px); }
body[data-theme="light"] { --bg-primary: #f8fafc; --bg-secondary: #f1f5f9; --bg-card: #ffffff; --text-primary: #1e293b; --text-secondary: #64748b; --border: #e2e8f0; }
</style>
</head>
<body>
<button class="theme-toggle" id="themeToggle" onclick="toggleTheme()">
<span class="icon" id="themeIcon">Moon</span>
<span id="themeText">Dark</span>
</button>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
const THEME_KEY = 'zen-api-theme';
function getPreferredTheme() {
const savedTheme = localStorage.getItem(THEME_KEY);
if (savedTheme) return savedTheme;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function applyTheme(theme) {
document.body.setAttribute('data-theme', theme);
const icon = document.getElementById('themeIcon');
const text = document.getElementById('themeText');
if (theme === 'dark') { icon.textContent = 'Sun'; text.textContent = 'Light'; }
else { icon.textContent = 'Moon'; text.textContent = 'Dark'; }
}
function toggleTheme() {
const currentTheme = document.body.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
localStorage.setItem(THEME_KEY, newTheme);
applyTheme(newTheme);
}
document.addEventListener('DOMContentLoaded', function() {
const theme = getPreferredTheme();
applyTheme(theme);
});
const ui = SwaggerUIBundle({
url: '/openapi.json',
dom_id: '#swagger-ui',
deepLinking: true,
presets: [SwaggerUIBundle.presets.apis],
plugins: [SwaggerUIBundle.plugins.DownloadUrl],
layout: "BaseLayout",
validatorUrl: null,
tryItOutEnabled: true,
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
});
</script>
</body>
</html>"""
return html_template
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
"""Swagger UI with Dark Mode support"""
from fastapi.responses import FileResponse
return FileResponse(os.path.join(os.path.dirname(__file__), "static", "swagger_dark.html"))
def get_zen_redoc_html() -> str:
"""Generate custom ReDoc HTML with dark theme"""
return """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zen-AI-Pentest API - ReDoc</title>
<link rel="shortcut icon" href="/favicon.ico">
<meta name="description" content="Zen-AI-Pentest API Documentation">
<style>
:root { --bg-primary: #0a0a0f; --bg-secondary: #14141f; --bg-card: #1a1a2e; --text-primary: #e2e8f0; --text-secondary: #94a3b8; --accent: #06b6d4; --border: #27273a; }
* { scrollbar-width: thin; scrollbar-color: #27273a #0a0a0f; }
body { background: var(--bg-primary) !important; margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
.menu-content { background: var(--bg-secondary) !important; border-right: 1px solid var(--border) !important; }
.api-info { background: linear-gradient(135deg, rgba(6,182,212,0.1) 0%, transparent 100%) !important; padding: 40px !important; border-bottom: 1px solid var(--border) !important; }
.api-info h1 { color: var(--accent) !important; font-size: 2.8em !important; font-weight: 700 !important; }
.api-content { background: var(--bg-primary) !important; padding: 40px !important; }
h1, h2, h3, h4, h5, h6 { color: var(--text-primary) !important; }
code { background: var(--bg-secondary) !important; color: var(--accent) !important; padding: 2px 8px !important; border-radius: 4px !important; }
pre { background: var(--bg-card) !important; border: 1px solid var(--border) !important; border-radius: 8px !important; padding: 20px !important; }
table { background: var(--bg-card) !important; border: 1px solid var(--border) !important; border-radius: 8px !important; }
table th { background: var(--bg-secondary) !important; color: var(--text-primary) !important; font-weight: 600; padding: 12px !important; }
table td { color: var(--text-secondary) !important; padding: 12px !important; }
a { color: var(--accent) !important; }
</style>
</head>
<body>
<redoc spec-url="/openapi.json"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js"></script>
</body>
</html>"""
@app.get("/redoc", include_in_schema=False)
async def custom_redoc_html() -> HTMLResponse:
"""ReDoc with Dark Mode support"""
return HTMLResponse(content=get_zen_redoc_html())
@app.get("/", include_in_schema=False)
async def root_redirect():
"""Redirect root to docs"""
from fastapi.responses import RedirectResponse
return RedirectResponse(url="/docs")
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
"""Custom Zen favicon"""
svg = """<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="32" height="32">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#06b6d4;stop-opacity:1" />
<stop offset="100%" style="stop-color:#0891b2;stop-opacity:1" />
</linearGradient>
</defs>
<rect width="100" height="100" rx="20" fill="#0a0a0f"/>
<path d="M50 10 L80 25 L80 50 C80 70 50 90 50 90 C50 90 20 70 20 50 L20 25 Z"
fill="url(#grad)" stroke="#06b6d4" stroke-width="2"/>
<path d="M35 45 L45 55 L65 35" fill="none" stroke="#0a0a0f" stroke-width="4" stroke-linecap="round"/>
</svg>"""
return Response(content=svg.encode(), media_type="image/svg+xml")
# ============================================================================
# WEBSOCKET
# ============================================================================
@app.websocket("/ws/scans/{scan_id}")
async def scan_websocket(websocket: WebSocket, scan_id: int):
"""WebSocket for real-time scan updates"""
await ws_manager.connect(websocket, scan_id)
try:
while True:
data = await websocket.receive_text()
message = json.loads(data)
if message.get("action") == "ping":
await websocket.send_json({"type": "pong"})
except WebSocketDisconnect:
ws_manager.disconnect(websocket, scan_id)
@app.websocket("/ws/notifications")
async def notifications_websocket(websocket: WebSocket):
"""WebSocket for global notifications"""
await ws_manager.connect(websocket, "global")
try:
while True:
_ = await websocket.receive_text()
except WebSocketDisconnect:
ws_manager.disconnect(websocket, "global")
# ============================================================================
# HEALTH & INFO - Root Level Endpoints for Docker/Kubernetes
# ============================================================================
_API_START_TIME = time.time()
_API_VERSION = "3.0.0"
def _get_uptime_seconds() -> int:
"""Berechne die Uptime der API in Sekunden."""
return int(time.time() - _API_START_TIME)
def _get_timestamp() -> str:
"""Gib aktuellen ISO-Timestamp zurück."""
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@app.get("/health", tags=["Health"], summary="Einfacher Health Check (Root)")
async def root_health_check():
"""
Einfacher Health Check für Load Balancer und Docker.
**Alternative:** `GET /api/v1/health` (empfohlen)
"""
return {
"status": "healthy",
"timestamp": _get_timestamp(),
"version": _API_VERSION,
}
@app.get(
"/health/detailed",
tags=["Health"],
summary="Detaillierter Health Check (Root)",
responses={503: {"description": "Mindestens ein Service ist nicht verfügbar"}},
)
async def root_health_check_detailed():
"""
Detaillierter Health Check für alle Services.
**Alternative:** `GET /api/v1/health/detailed` (empfohlen)
"""
import redis
from sqlalchemy import text
timestamp = _get_timestamp()
services_status = {}
overall_status = "healthy"
any_error = False
services_status["api"] = {
"status": "ok",
"uptime": _get_uptime_seconds(),
}
try:
start = time.time()
db = SessionLocal()
db.execute(text("SELECT 1"))
db.close()
latency = round((time.time() - start) * 1000, 2)
services_status["database"] = {
"status": "ok",
"type": "postgresql",
"latency_ms": latency,
}
except Exception as e:
services_status["database"] = {
"status": "error",
"type": "postgresql",
"error": str(e),
}
overall_status = "degraded"
any_error = True
try:
start = time.time()
redis_client = redis.from_url(
os.getenv("REDIS_URL", "redis://localhost:6379/0"),
socket_connect_timeout=2,
)
redis_client.ping()
latency = round((time.time() - start) * 1000, 2)
services_status["redis"] = {
"status": "ok",
"latency_ms": latency,
}
except Exception as e:
services_status["redis"] = {
"status": "error",
"error": str(e),
}
overall_status = "degraded"
any_error = True
try:
from celery import Celery
celery_app = Celery(
"zen_pentest",
broker=os.getenv("REDIS_URL", "redis://localhost:6379/0"),
backend=os.getenv("REDIS_URL", "redis://localhost:6379/0"),
)
ping_result = celery_app.control.ping(timeout=1.0)
workers = len(ping_result) if ping_result else 0
inspector = celery_app.control.inspect()
scheduled = inspector.scheduled() or {}
active = inspector.active() or {}
reserved = inspector.reserved() or {}
queued_tasks = 0
for worker_tasks in list(scheduled.values()) + list(active.values()) + list(reserved.values()):
queued_tasks += len(worker_tasks)
services_status["celery"] = {
"status": "ok",
"workers": workers,
"queued_tasks": queued_tasks,
}
except Exception as e:
services_status["celery"] = {
"status": "degraded",
"workers": 0,
"queued_tasks": 0,
"error": str(e),
}
response_data = {
"status": overall_status,
"timestamp": timestamp,
"version": _API_VERSION,
"services": services_status,
}
if any_error:
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content=response_data,
)
return response_data
@app.get(
"/health/ready",
tags=["Health"],
summary="Kubernetes Readiness Probe (Root)",
responses={503: {"description": "Service ist nicht ready"}},
)
async def root_health_ready():
"""
Kubernetes Readiness Probe.
**Alternative:** `GET /api/v1/health/ready` (empfohlen)
"""
import redis
from sqlalchemy import text
db_healthy = False
try:
db = SessionLocal()
db.execute(text("SELECT 1"))
db.close()
db_healthy = True
except Exception:
pass
redis_healthy = False
try:
redis_client = redis.from_url(
os.getenv("REDIS_URL", "redis://localhost:6379/0"),
socket_connect_timeout=2,
)
redis_client.ping()
redis_healthy = True
except Exception:
pass
checks = {
"database": db_healthy,
"redis": redis_healthy,
}
is_ready = db_healthy and redis_healthy
response_data = {
"ready": is_ready,
"timestamp": _get_timestamp(),
"checks": checks,
}
if not is_ready:
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content=response_data,
)
return response_data
@app.get(
"/health/live",
tags=["Health"],
summary="Kubernetes Liveness Probe (Root)",
)
async def root_health_live():
"""
Kubernetes Liveness Probe.
**Alternative:** `GET /api/v1/health/live` (empfohlen)
"""
return {
"alive": True,
"timestamp": _get_timestamp(),
"uptime_seconds": _get_uptime_seconds(),
}
@app.get("/info", tags=["Health"], summary="API Information (Root)")
async def root_api_info():
"""
API Information.
**Alternative:** `GET /api/v1/info` (empfohlen)
"""
return {
"name": "Zen-AI-Pentest API",
"version": _API_VERSION,
"description": "Professional Pentesting Framework",
"endpoints": {
"scans": "/api/v1/scans",
"findings": "/api/v1/findings",
"tools": "/api/v1/tools",
"reports": "/api/v1/reports",
"schedules": "/api/v1/schedules",
"health": "/api/v1/health",
"health_detailed": "/api/v1/health/detailed",
"health_ready": "/api/v1/health/ready",
"health_live": "/api/v1/health/live",
},
}
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
"""
WebSocket Endpoint für Echtzeit-Updates
Nutzung:
- Verbinden: wscat -c ws://localhost:8000/ws/client123
- Ping: {"type": "ping"}
- Subscribe: {"type": "subscribe", "channel": "scans"}
"""
await manager.connect(websocket, client_id)
try:
while True:
data = await websocket.receive_text()
message = json.loads(data)
if message.get("type") == "ping":
await manager.send_personal_message(
{
"type": "pong",
"timestamp": datetime.now(timezone.utc).isoformat(),
},
websocket,
)
elif message.get("type") == "subscribe":
channel = message.get("channel", "general")
await manager.send_personal_message(
{
"type": "subscribed",
"channel": channel,
"client_id": client_id,
},
websocket,
)
except WebSocketDisconnect:
manager.disconnect(websocket, client_id)
except Exception as e:
print(f"WebSocket error: {e}")
manager.disconnect(websocket, client_id)
# ============================================================================
# AGENT COMMUNICATION V2 WEBSOCKET
# ============================================================================
class SimpleAgentConnection:
"""Simple agent connection manager with task support"""
def __init__(self):
self.active_connections: dict[str, WebSocket] = {}
self.agent_info: dict[str, dict] = {}
async def connect(self, websocket: WebSocket, agent_id: str, api_key: str = None):
await websocket.accept()
self.active_connections[agent_id] = websocket
self.agent_info[agent_id] = {
"api_key": api_key,
"connected_at": datetime.now(timezone.utc).isoformat(),
"last_seen": datetime.now(timezone.utc).isoformat(),
}
logger.info(f"Agent {sanitize_for_log(agent_id)} connected via WebSocket")
def disconnect(self, agent_id: str):
if agent_id in self.active_connections:
del self.active_connections[agent_id]
if agent_id in self.agent_info:
del self.agent_info[agent_id]
logger.info(f"Agent {sanitize_for_log(agent_id)} disconnected")
async def send_to_agent(self, agent_id: str, message: dict) -> bool:
if agent_id in self.active_connections:
try:
await self.active_connections[agent_id].send_json(message)
self.agent_info[agent_id]["last_seen"] = datetime.now(timezone.utc).isoformat()
return True
except Exception as e:
logger.error(f"Failed to send to {sanitize_for_log(agent_id)}: {e}")
return False
return False
async def send_task(self, agent_id: str, task: dict) -> bool:
return await self.send_to_agent(
agent_id,
{
"type": "task",
"task": task,
"timestamp": datetime.now(timezone.utc).isoformat(),
},
)
async def broadcast(self, message: dict, exclude: Optional[str] = None):
for agent_id, ws in self.active_connections.items():
if agent_id != exclude:
try:
await ws.send_json(message)
self.agent_info[agent_id]["last_seen"] = datetime.now(timezone.utc).isoformat()
except Exception as e:
logger.error(f"Failed to send to {sanitize_for_log(agent_id)}: {e}")
def get_connected_agents(self) -> list:
return list(self.active_connections.keys())
def is_agent_connected(self, agent_id: str) -> bool:
return agent_id in self.active_connections
agent_connection_manager = SimpleAgentConnection()
@app.websocket("/agents/ws")
async def agent_websocket_endpoint(websocket: WebSocket):
"""
Agent Communication WebSocket Endpoint with API Key Auth
"""
agent_id: Optional[str] = None
api_key: Optional[str] = None
try:
await websocket.accept()
auth_data = await websocket.receive_json()
if auth_data.get("type") != "auth":
await websocket.send_json(
{
"type": "auth_failed",
"error": "Expected auth message with type 'auth'",
}
)
await websocket.close()
return
agent_id = auth_data.get("agent_id")
api_key = auth_data.get("api_key")
auth_data.get("api_secret")
if not agent_id:
await websocket.send_json({"type": "auth_failed", "error": "agent_id required"})
await websocket.close()
return
if not api_key or not api_key.startswith("zen_"):
await websocket.send_json({"type": "auth_failed", "error": "Invalid API key format"})
await websocket.close()
return
await agent_connection_manager.connect(websocket, agent_id, api_key)
await websocket.send_json(
{
"type": "auth_success",
"agent_id": agent_id,
"message": "Connected to Zen-AI-Pentest Agent Network",
}
)
from utils.security import sanitize_log_id
logger.info(f"Agent {sanitize_log_id(agent_id)} authenticated successfully")
while True:
try:
data = await websocket.receive_json()
msg_type = data.get("type")
if msg_type == "task_result":
task_id = data.get("task_id")
result = data.get("result", {})
logger.info(f"Task result received from {sanitize_log_id(agent_id)}: {sanitize_log_id(task_id)}")
try:
from agents.workflows.orchestrator import get_workflow_orchestrator
orchestrator = get_workflow_orchestrator()
await orchestrator.submit_task_result(task_id, result)
await websocket.send_json(
{
"type": "ack",
"message_id": task_id,
"status": "result_received",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
)
except Exception as e:
logger.error(f"Failed to process task result: {sanitize_for_log(str(e))}")
elif msg_type == "task_ack":
task_id = data.get("task_id")
logger.debug(f"Task {sanitize_log_id(task_id)} acknowledged by {sanitize_log_id(agent_id)}")
elif msg_type == "message":
recipient = data.get("recipient", "broadcast")
payload = data.get("payload", {})
await websocket.send_json(
{
"type": "ack",
"message_id": data.get("message_id", "unknown"),
"status": "received",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
)
if recipient == "broadcast":
await agent_connection_manager.broadcast(
{
"type": "message",
"sender": agent_id,
"payload": payload,
"timestamp": datetime.now(timezone.utc).isoformat(),
},
exclude=agent_id,
)
else:
await agent_connection_manager.send_to_agent(
recipient,
{
"type": "message",
"sender": agent_id,
"payload": payload,
"timestamp": datetime.now(timezone.utc).isoformat(),
},
)
elif msg_type == "heartbeat":
await websocket.send_json(
{
"type": "heartbeat_ack",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
)
elif msg_type == "disconnect":
break
except WebSocketDisconnect:
break
except json.JSONDecodeError:
await websocket.send_json({"type": "error", "error": "Invalid JSON"})
except Exception as e:
logger.error(f"WebSocket message error: {e}")
await websocket.send_json({"type": "error", "error": str(e)})
except WebSocketDisconnect:
logger.info("Agent WebSocket disconnected")
except Exception as e:
logger.error(f"Agent WebSocket error: {e}")
finally:
if agent_id:
agent_connection_manager.disconnect(agent_id)
# ============================================================================
# Include Legacy Routers (extracted from this file)
# ============================================================================
app.include_router(legacy_auth_router)
app.include_router(legacy_scans_router)
app.include_router(legacy_tools_router)
app.include_router(legacy_schedules_router)
app.include_router(legacy_settings_router)
app.include_router(legacy_misc_router)
# ============================================================================
# API v1.0 (Q1 2026)
# ============================================================================
# Import v1 routers
try:
from api.v1.siem import router as siem_v1_router
app.include_router(siem_v1_router, prefix="/api/v1/siem", tags=["SIEM v1.0"])
logger.info("API v1.0 SIEM endpoints loaded")
except ImportError as e:
logger.warning(f"Could not load SIEM v1.0 endpoints: {e}")
try:
from api.v1.dashboard import router as dashboard_v1_router
app.include_router(dashboard_v1_router, prefix="/api/v1", tags=["Dashboard v1.0"])
logger.info("API v1.0 Dashboard endpoints loaded")
except ImportError as e:
logger.warning(f"Could not load Dashboard v1.0 endpoints: {e}")
try:
from api.v1.scans_extended import router as scans_v1_router
app.include_router(scans_v1_router, prefix="/api/v1/scans-extended", tags=["Scans v1.0"])
logger.info("API v1.0 Scans endpoints loaded")
except ImportError as e:
logger.warning(f"Could not load Scans v1.0 endpoints: {e}")
# Subdomain scanning routes
try:
from api.routes.subdomain import router as subdomain_router
app.include_router(subdomain_router, prefix="/api/v1/subdomain", tags=["Subdomain"])
logger.info("Subdomain scanning endpoints loaded")
except ImportError as e:
logger.warning(f"Could not load Subdomain endpoints: {e}")
# Agent Communication v2 routes
if AGENTS_V2_AVAILABLE:
try:
app.include_router(agents_v2_router, prefix="/api/v2")
logger.info("Agent Communication v2 endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Agent v2 endpoints: {e}")
# API v1 Modular Routes (New Structure)
if V1_ROUTES_AVAILABLE:
try:
app.include_router(api_v1_router)
logger.info("API v1 modular endpoints loaded")
except Exception as e:
logger.warning(f"Could not load API v1 endpoints: {e}")
# Agent v1 routes (legacy agent management endpoints)
try:
from api.routes.agents import router as agents_v1_router
app.include_router(agents_v1_router, prefix="/api/v1/agents", tags=["Agents v1.0"])
logger.info("Agent v1 endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Agent v1 endpoints: {e}")
# Core v1 routes
try:
from api.routes.scans import router as scans_router
app.include_router(scans_router, prefix="/api/v1/scans", tags=["Scans"])
logger.info("Scans v1 endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Scans v1 endpoints: {e}")
try:
from api.routes.findings import router as findings_router
app.include_router(findings_router, prefix="/api/v1/findings", tags=["Findings"])
logger.info("Findings v1 endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Findings v1 endpoints: {e}")
# Evidence routes
if EVIDENCE_ROUTES_AVAILABLE:
try:
app.include_router(evidence_router, prefix="/api/v1")
logger.info("Evidence endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Evidence endpoints: {e}")
# Attack Path routes
if ATTACK_PATH_ROUTES_AVAILABLE:
try:
app.include_router(attack_path_router, prefix="/api/v1")
logger.info("Attack Path endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Attack Path endpoints: {e}")
# Reports routes
if REPORTS_ROUTES_AVAILABLE:
try:
app.include_router(reports_router, prefix="/api/v1")
logger.info("Reports endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Reports endpoints: {e}")
# Secure Authentication routes
if SECURE_AUTH_AVAILABLE:
try:
app.include_router(secure_auth_router)
logger.info("Secure Auth endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Secure Auth endpoints: {e}")
# MCP routes
if MCP_ROUTES_AVAILABLE:
try:
app.include_router(mcp_router)
logger.info("MCP endpoints loaded")
except Exception as e:
logger.warning(f"Could not load MCP endpoints: {e}")
# Kimi Terminal routes
if KIMI_TERMINAL_AVAILABLE:
try:
app.include_router(kimi_chat_router)
logger.info("Kimi Terminal endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Kimi Terminal endpoints: {e}")
# Auth Bridge routes
if AUTH_BRIDGE_AVAILABLE:
try:
app.include_router(auth_bridge_router)
logger.info("Auth Bridge endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Auth Bridge endpoints: {e}")
# JWT Authentication routes (new auth system)
if JWT_AUTH_ROUTES_AVAILABLE:
try:
app.include_router(jwt_auth_router)
logger.info("JWT Auth endpoints loaded at /auth")
except Exception as e:
logger.warning(f"Could not load JWT Auth endpoints: {e}")
# Risk Scoring routes
if RISK_ROUTES_AVAILABLE:
try:
app.include_router(risk_router, prefix="/api/v1")
logger.info("Risk Scoring endpoints loaded at /api/v1/risk")
except Exception as e:
logger.warning(f"Could not load Risk Scoring endpoints: {e}")
# Workflow routes
try:
import importlib.util
import sys
from pathlib import Path
workflows_path = Path(__file__).parent / "routes" / "workflows.py"
spec = importlib.util.spec_from_file_location("workflows", workflows_path)
workflows_module = importlib.util.module_from_spec(spec)
sys.modules["workflows"] = workflows_module
spec.loader.exec_module(workflows_module)
app.include_router(workflows_module.router)
logger.info("Workflow endpoints loaded")
except Exception as e:
logger.warning(f"Could not load Workflow endpoints: {e}")
# Scheduler routes (Celery-based Scan Scheduler)
try:
from api.routes.scheduler import router as scheduler_router
app.include_router(scheduler_router, prefix="/api/v1")
logger.info("Scheduler endpoints loaded at /api/v1/scheduler")
except Exception as e:
logger.warning(f"Could not load Scheduler endpoints: {e}")
# Notification routes
NOTIFICATION_ROUTES_AVAILABLE = False
try:
from api.routes.notifications import router as notifications_router
NOTIFICATION_ROUTES_AVAILABLE = True
except Exception as e:
logger.warning(f"Could not load Notification router: {e}")
if NOTIFICATION_ROUTES_AVAILABLE:
try:
app.include_router(notifications_router, prefix="/api/v1")
logger.info("Notification endpoints loaded at /api/v1/notifications")
except Exception as e:
logger.warning(f"Could not load Notification endpoints: {e}")
# OWASP ZAP Integration routes
ZAP_ROUTES_AVAILABLE = False
try:
from api.routes.zap import router as zap_router
ZAP_ROUTES_AVAILABLE = True
except Exception as e:
logger.warning(f"Could not load ZAP router: {e}")
if ZAP_ROUTES_AVAILABLE:
try:
app.include_router(zap_router, prefix="/api/v1")
logger.info("ZAP endpoints loaded at /api/v1/tools/zap")
except Exception as e:
logger.warning(f"Could not load ZAP endpoints: {e}")
# ============================================================================
# Backward-compatible re-exports
# ============================================================================
from api.auth_deps import _rbac_manager, _user_manager
from api.background import (
SCHEDULED_SCANS,
calculate_next_run,
execute_scan_internal,
execute_scheduled_scan,
execute_tool_internal,
execute_tool_task,
generate_report_task,
parse_tool_findings,
run_scan_task,
save_finding_to_db,
)
from api.rate_limiter import check_auth_rate_limit as check_rate_limit
from api.routes.legacy_tools import get_tool_category
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) # nosec B104
"""
Zen-AI-Pentest API Server
FastAPI-basiertes Backend für das Pentesting-Framework.
"""
import os
import sys
from pathlib import Path
# Load .env file first (before any other imports)
from dotenv import load_dotenv
load_dotenv()
# Windows Asyncio Fix (must be first)
if sys.platform == "win32":
import warnings
warnings.filterwarnings("ignore", message="unclosed transport", category=ResourceWarning)
# Add parent to path
sys.path.insert(0, str(Path(__file__).parent.parent))
import json
import logging
import time
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from typing import Any, List, Optional
from fastapi import (
BackgroundTasks,
Depends,
FastAPI,
HTTPException,
Request,
Response,
WebSocket,
WebSocketDisconnect,
status,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.staticfiles import StaticFiles
from api.auth_deps import (
NEW_AUTH_AVAILABLE,
_jwt_handler,
_password_hasher,
optional_auth,
verify_admin_credentials,
verify_token,
)
from api.csrf_protection import csrf_protection, require_csrf
from api.rate_limiter import (
AuthRateLimitDependency,
RateLimitDependency,
RateLimitInfo,
RateLimitMiddleware,
check_auth_rate_limit,
rate_limit,
)
from api.schemas import (
FindingCreate,
FindingResponse,
ReportCreate,
ReportResponse,
ScanCreate,
ScanResponse,
ScanUpdate,
ScheduledScanCreate,
ScheduledScanResponse,
ScheduledScanUpdate,
TokenResponse,
ToolExecuteRequest,
ToolExecuteResponse,
UserLogin,
)
from api.security_logging import sanitize_for_log
from api.websocket import ConnectionManager
from api.websocket_manager import manager
from database.crud import (
create_finding,
create_report,
create_scan,
get_findings,
get_reports,
get_scan,
get_scans,
update_scan_status,
)
from database.models import Report, SessionLocal, get_db, init_db
# Import Agent v2 routes
try:
from api.routes.agents_v2 import router as agents_v2_router
AGENTS_V2_AVAILABLE = True
except ImportError as e:
Xet Storage Details
- Size:
- 55.6 kB
- Xet hash:
- 1500ebb185eb60f43394d8768bf351278fe748dc7f691eff44ae1e649798d8f5
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.