Buckets:

download
raw
5.06 kB
"""
Zen-AI-Pentest FastAPI Application
Main entry point for the backend API.
"""
import time
from contextlib import asynccontextmanager
import structlog
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from app.core.config import settings
from app.core.database import engine, init_db
from app.core.logging import setup_logging
from app.routers import (
agents,
assets,
auth,
health,
kimi_auth,
notifications,
reports,
scans,
twitch_tunnel,
users,
vulnerabilities,
websockets,
workflows,
)
# Setup logging
setup_logging()
logger = structlog.get_logger()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan events."""
# Startup
logger.info("Starting up Zen-AI-Pentest API...")
await init_db()
logger.info("Database initialized successfully")
yield
# Shutdown
logger.info("Shutting down Zen-AI-Pentest API...")
await engine.dispose()
# Create FastAPI application
app = FastAPI(
title="Zen-AI-Pentest API",
description="AI-Powered Penetration Testing Framework API",
version="1.0.0",
docs_url="/api/docs" if settings.DEBUG else None,
redoc_url="/api/redoc" if settings.DEBUG else None,
openapi_url="/api/openapi.json" if settings.DEBUG else None,
lifespan=lifespan,
)
# Add middlewares
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(GZipMiddleware, minimum_size=1000)
if not settings.DEBUG:
app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.ALLOWED_HOSTS)
# Request timing middleware
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""Add processing time to response headers."""
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
# Request logging middleware
@app.middleware("http")
async def log_requests(request: Request, call_next):
"""Log all incoming requests."""
logger.info(
"Incoming request",
method=request.method,
url=str(request.url),
client=request.client.host if request.client else None,
)
response = await call_next(request)
logger.info(
"Request completed",
method=request.method,
url=str(request.url),
status_code=response.status_code,
)
return response
# Exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""Handle all unhandled exceptions."""
logger.error(
"Unhandled exception",
error=str(exc),
url=str(request.url),
method=request.method,
)
return JSONResponse(
status_code=500,
content={
"success": False,
"error": {
"code": "INTERNAL_ERROR",
"message": "An internal error occurred",
},
},
)
# Include routers
app.include_router(health.router, prefix="/api/v1", tags=["Health"])
app.include_router(auth.router, prefix="/api/v1/auth", tags=["Authentication"])
app.include_router(users.router, prefix="/api/v1/users", tags=["Users"])
app.include_router(scans.router, prefix="/api/v1/scans", tags=["Scans"])
app.include_router(
vulnerabilities.router,
prefix="/api/v1/vulnerabilities",
tags=["Vulnerabilities"],
)
app.include_router(assets.router, prefix="/api/v1/assets", tags=["Assets"])
app.include_router(reports.router, prefix="/api/v1/reports", tags=["Reports"])
app.include_router(agents.router, prefix="/api/v1/agents", tags=["Agents"])
app.include_router(workflows.router, prefix="/api/v1/workflows", tags=["Workflows"])
app.include_router(
notifications.router,
prefix="/api/v1/notifications",
tags=["Notifications"],
)
app.include_router(kimi_auth.router, prefix="/api/v1/kimi-auth", tags=["Kimi Auth"])
app.include_router(
twitch_tunnel.router,
prefix="/api/v1/twitch-tunnel",
tags=["Twitch Tunnel"],
)
# Include WebSocket router
app.include_router(websockets.router, prefix="/ws")
@app.get("/")
async def root():
"""Root endpoint."""
return {
"name": "Zen-AI-Pentest API",
"version": "1.0.0",
"status": "operational",
"documentation": "/api/docs",
}
@app.get("/api/health")
async def api_health():
"""Health check endpoint."""
return {"status": "healthy", "timestamp": time.time()}
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app.main:app",
host=settings.HOST,
port=settings.PORT,
reload=settings.DEBUG,
workers=1 if settings.DEBUG else settings.WORKERS,
)

Xet Storage Details

Size:
5.06 kB
·
Xet hash:
cc35c464178fb58b82501f94c3fd8867e6032fb355e7cc6a7483c8334a17594b

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