MalwareGuard / backend /app /main.py
Codex
Fix Clerk account recovery and tier safety
34bbf1b
Raw History Blame Contribute Delete
10.3 kB
"""
Malware Detection Platform - FastAPI Main Application
Production-ready malware detection API combining:
- XGBoost ML model for EMBER 2018 v2 feature classification
- Gemini AI for human-readable explanations
- VirusTotal API for secondary verification
Author: AI Security Engineer
"""
# Used libraries
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from .config import settings
from .rate_limit import limiter
from .routers import admin, auth, partner, predict, virustotal, chat, upload, url, feedback, generic_upload, webhooks
from .database import database_is_ephemeral, init_db
from .services.ml_service import get_ml_service
from .services.shap_service import get_shap_service
from .services.gemini_service import get_gemini_service
from .services.virustotal_service import get_virustotal_service
from .services.url_service import get_url_service
from .services.feedback_service import get_feedback_service
from .services.csv_analyzer import get_csv_analyzer
from .services.mp4_analyzer import get_mp4_analyzer
from .services.bootstrap_service import bootstrap_admin_account
from .dependencies import sync_clerk_users_from_clerk
# Configure logging.
logging.basicConfig(
level=logging.INFO if settings.debug else logging.WARNING,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Application lifespan manager.
Handles startup and shutdown events.
"""
# Startup.
logger.info("=" * 60)
logger.info("Malware Detection Platform Starting...")
logger.info("=" * 60)
settings.validate_security()
try:
init_db()
logger.info("Database schema ready")
if settings.is_production and database_is_ephemeral():
logger.warning(
"Using ephemeral SQLite storage. Configure DATABASE_URL or attach Hugging Face persistent storage at /data."
)
synced_users = await sync_clerk_users_from_clerk()
if synced_users:
logger.info("Synchronized %s Clerk users into the local account projection", synced_users)
bootstrap_admin_account()
except Exception as e:
logger.error(f"Database initialization failed: {e}")
raise
# Load ML model (single load for all requests).
try:
ml_service = get_ml_service()
logger.info(f"ML Model loaded: {ml_service.get_model_info()}")
except Exception as e:
logger.error(f"Failed to load ML model: {e}")
raise
# Initialize SHAP service.
try:
shap_service = get_shap_service()
shap_service.initialize(ml_service.model)
logger.info("SHAP service initialized")
except Exception as e:
logger.warning(f"SHAP initialization failed (non-critical): {e}")
# Initialize Gemini service
try:
gemini_service = get_gemini_service()
if gemini_service.initialized:
logger.info("Gemini AI service initialized")
else:
logger.warning("Gemini AI service not initialized (check API key)")
except Exception as e:
logger.warning(f"Gemini initialization failed (non-critical): {e}")
# Check VirusTotal configuration
vt_service = get_virustotal_service()
if vt_service.initialized:
logger.info("VirusTotal service configured")
else:
logger.warning("VirusTotal API key not configured")
# Load URL HyperModel
try:
url_service = get_url_service()
if url_service.model_loaded:
logger.info(f"URL HyperModel loaded: {url_service.get_model_info()['model_type']}")
else:
logger.warning("URL HyperModel not loaded")
except Exception as e:
logger.warning(f"URL HyperModel initialization failed (non-critical): {e}")
# Initialize RL Feedback service
try:
fb_service = get_feedback_service()
stats = fb_service.get_stats()
logger.info(
f"RL Feedback service ready "
f"(malware={stats['malware_total']}, url={stats['url_total']} samples)"
)
except Exception as e:
logger.warning(f"RL Feedback initialization failed (non-critical): {e}")
# Initialize CSV/MP4 analyzers for generic file analysis
try:
csv_analyzer = get_csv_analyzer()
mp4_analyzer = get_mp4_analyzer()
logger.info(f"CSV Analyzer: model_loaded={csv_analyzer.model_loaded}")
logger.info(f"MP4 Analyzer: initialized={mp4_analyzer.initialized}")
except Exception as e:
logger.warning(f"Generic file analyzers initialization (non-critical): {e}")
logger.info("=" * 60)
logger.info("Malware Detection Platform Ready!")
logger.info(f"API available at: http://{settings.host}:{settings.port}")
logger.info("=" * 60)
yield
# Shutdown
logger.info("Shutting down Malware Detection Platform...")
# Close VirusTotal client
await vt_service.close()
logger.info("Shutdown complete")
# Create FastAPI app
app = FastAPI(
title="Malware Detection Platform",
description="""
## AI-Powered Malware Detection API
This platform combines machine learning with AI explanations for comprehensive malware analysis.
### Features
- **XGBoost Prediction**: Fast malware classification using EMBER 2018 v2 features
- **Gemini AI Explanation**: Human-readable analysis and recommendations
- **VirusTotal Verification**: Cross-reference with 70+ antivirus engines
- **URL Scanner**: Malicious URL detection via stacking HyperModel
- **CSV Injection Detection**: ML-based formula injection attack detection
- **MP4 Analysis**: Heuristic-based video file structural analysis
### Endpoints
- `/api/predict` - Run XGBoost malware prediction
- `/api/predict/explain` - Prediction with Gemini AI explanation
- `/api/virustotal/{hash}` - Look up file hash on VirusTotal
- `/api/virustotal/compare` - Compare XGBoost vs VirusTotal verdicts
- `/api/url/analyze` - Analyze URL for malicious indicators
- `/api/upload/analyze-generic` - Analyze CSV/MP4 files
""",
version="1.0.0",
lifespan=lifespan,
docs_url="/docs" if settings.debug else None,
redoc_url="/redoc" if settings.debug else None,
openapi_url="/openapi.json" if settings.debug else None,
)
# Add rate limiter to app state
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=settings.effective_cors_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PATCH", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-API-Key"],
)
@app.middleware("http")
async def origin_guard(request: Request, call_next):
origin = request.headers.get("origin")
if origin and origin not in settings.effective_cors_origins:
return JSONResponse(
status_code=403,
content={"detail": "Origin not allowed"},
)
return await call_next(request)
@app.middleware("http")
async def security_headers(request: Request, call_next):
response = await call_next(request)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "DENY")
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
response.headers.setdefault("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
return response
# Global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""Handle uncaught exceptions with meaningful error messages."""
logger.error(f"Unhandled exception: {exc}", exc_info=True)
# Don't expose internal errors in production
if settings.debug:
detail = str(exc)
else:
detail = "An internal error occurred. Please try again later."
return JSONResponse(
status_code=500,
content={"detail": detail}
)
# Include routers
app.include_router(predict.router)
app.include_router(virustotal.router)
app.include_router(chat.router)
app.include_router(upload.router)
app.include_router(url.router)
app.include_router(feedback.router)
app.include_router(auth.router)
app.include_router(admin.router)
app.include_router(partner.router)
app.include_router(generic_upload.router)
app.include_router(webhooks.router)
@app.get("/", tags=["root"])
async def root():
"""Root endpoint with API information."""
return {
"name": "Malware Detection Platform",
"version": "1.0.0",
"status": "running",
"docs": "/docs",
"endpoints": {
"prediction": "/api/predict",
"prediction_with_explanation": "/api/predict/explain",
"virustotal_lookup": "/api/virustotal/{hash}",
"comparison": "/api/virustotal/compare"
}
}
@app.get("/health", tags=["health"])
async def health_check():
"""Global health check endpoint."""
if settings.is_production:
return {"status": "healthy"}
ml_service = get_ml_service()
vt_service = get_virustotal_service()
gemini_service = get_gemini_service()
return {
"status": "healthy",
"services": {
"ml_model": ml_service.model_loaded,
"gemini": gemini_service.initialized,
"virustotal": vt_service.initialized
}
}
# For running with: python -m app.main
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app.main:app",
host=settings.host,
port=settings.port,
reload=settings.debug
)