Spaces:
Running
Running
Deploy emergency security hardening
Browse files- backend/app/config.py +69 -16
- backend/app/dependencies.py +12 -6
- backend/app/main.py +39 -28
- backend/app/rate_limit.py +6 -0
- backend/app/routers/admin.py +13 -1
- backend/app/routers/auth.py +43 -14
- backend/app/routers/chat.py +18 -15
- backend/app/routers/feedback.py +22 -16
- backend/app/routers/predict.py +43 -33
- backend/app/routers/upload.py +18 -11
- backend/app/routers/url.py +22 -8
- backend/app/routers/virustotal.py +23 -15
- backend/malwareguard.db +0 -0
- backend/tests/conftest.py +2 -0
- backend/tests/test_security_hardening.py +127 -0
- backend/tests/test_upload.py +2 -1
backend/app/config.py
CHANGED
|
@@ -5,14 +5,28 @@ Loads environment variables and provides app-wide settings.
|
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
-
import
|
| 9 |
-
from
|
| 10 |
-
|
| 11 |
-
from
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"""Application settings loaded from environment variables."""
|
| 17 |
|
| 18 |
|
|
@@ -30,10 +44,11 @@ class Settings(BaseSettings):
|
|
| 30 |
host: str = "0.0.0.0"
|
| 31 |
port: int = 8000
|
| 32 |
debug: bool = True
|
|
|
|
| 33 |
|
| 34 |
# Auth / Database
|
| 35 |
database_url: str = "sqlite:///./malwareguard.db"
|
| 36 |
-
jwt_secret_key: str =
|
| 37 |
jwt_expire_minutes: int = 60 * 24
|
| 38 |
admin_emails: str = ""
|
| 39 |
bootstrap_admin_email: str = ""
|
|
@@ -53,21 +68,59 @@ class Settings(BaseSettings):
|
|
| 53 |
ember_feature_count: int = 2381 # EMBER 2018 v2 feature count
|
| 54 |
|
| 55 |
|
| 56 |
-
# Rate Limiting
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
|
| 61 |
# CORS Origins
|
| 62 |
cors_origins: list[str] = [
|
| 63 |
-
|
| 64 |
-
"http://localhost:3000",
|
| 65 |
-
"http://127.0.0.1:5173",
|
| 66 |
-
"http://127.0.0.1:3000",
|
| 67 |
"https://malwareguard.tech",
|
| 68 |
"https://www.malwareguard.tech",
|
| 69 |
"https://malwareguard-one.vercel.app",
|
| 70 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
class Config:
|
| 73 |
env_file = ".env"
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
import os
|
| 11 |
+
from pydantic_settings import BaseSettings
|
| 12 |
+
from pydantic import field_validator
|
| 13 |
+
from functools import lru_cache
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DEFAULT_JWT_SECRET = "change-this-in-production"
|
| 17 |
+
LOCAL_CORS_ORIGINS = [
|
| 18 |
+
"http://localhost:5173",
|
| 19 |
+
"http://localhost:3000",
|
| 20 |
+
"http://127.0.0.1:5173",
|
| 21 |
+
"http://127.0.0.1:3000",
|
| 22 |
+
]
|
| 23 |
+
PRODUCTION_CORS_ORIGINS = [
|
| 24 |
+
"https://malwareguard.tech",
|
| 25 |
+
"https://www.malwareguard.tech",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Settings(BaseSettings):
|
| 30 |
"""Application settings loaded from environment variables."""
|
| 31 |
|
| 32 |
|
|
|
|
| 44 |
host: str = "0.0.0.0"
|
| 45 |
port: int = 8000
|
| 46 |
debug: bool = True
|
| 47 |
+
environment: str = "development"
|
| 48 |
|
| 49 |
# Auth / Database
|
| 50 |
database_url: str = "sqlite:///./malwareguard.db"
|
| 51 |
+
jwt_secret_key: str = DEFAULT_JWT_SECRET
|
| 52 |
jwt_expire_minutes: int = 60 * 24
|
| 53 |
admin_emails: str = ""
|
| 54 |
bootstrap_admin_email: str = ""
|
|
|
|
| 68 |
ember_feature_count: int = 2381 # EMBER 2018 v2 feature count
|
| 69 |
|
| 70 |
|
| 71 |
+
# Rate Limiting
|
| 72 |
+
rate_limit_auth: str = "5/minute"
|
| 73 |
+
rate_limit_signup: str = "3/hour"
|
| 74 |
+
rate_limit_upload: str = "6/hour"
|
| 75 |
+
rate_limit_url: str = "30/minute"
|
| 76 |
+
rate_limit_chat: str = "20/minute"
|
| 77 |
+
rate_limit_feedback: str = "20/minute"
|
| 78 |
+
rate_limit_admin: str = "60/minute"
|
| 79 |
+
rate_limit_prediction: str = "60/minute"
|
| 80 |
+
rate_limit_virustotal: str = "10/minute"
|
| 81 |
|
| 82 |
|
| 83 |
# CORS Origins
|
| 84 |
cors_origins: list[str] = [
|
| 85 |
+
*LOCAL_CORS_ORIGINS,
|
|
|
|
|
|
|
|
|
|
| 86 |
"https://malwareguard.tech",
|
| 87 |
"https://www.malwareguard.tech",
|
| 88 |
"https://malwareguard-one.vercel.app",
|
| 89 |
]
|
| 90 |
+
|
| 91 |
+
@field_validator("cors_origins", mode="before")
|
| 92 |
+
@classmethod
|
| 93 |
+
def parse_cors_origins(cls, value: Any) -> list[str]:
|
| 94 |
+
if isinstance(value, str):
|
| 95 |
+
value = value.strip()
|
| 96 |
+
if not value:
|
| 97 |
+
return []
|
| 98 |
+
if value.startswith("["):
|
| 99 |
+
return value
|
| 100 |
+
return [item.strip() for item in value.split(",") if item.strip()]
|
| 101 |
+
return value
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def is_production(self) -> bool:
|
| 105 |
+
return not self.debug or self.environment.lower() in {"production", "prod"}
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def effective_cors_origins(self) -> list[str]:
|
| 109 |
+
if self.is_production:
|
| 110 |
+
return PRODUCTION_CORS_ORIGINS
|
| 111 |
+
return list(dict.fromkeys([*LOCAL_CORS_ORIGINS, *self.cors_origins]))
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def cookie_secure(self) -> bool:
|
| 115 |
+
return self.is_production
|
| 116 |
+
|
| 117 |
+
def validate_security(self) -> None:
|
| 118 |
+
if not self.is_production:
|
| 119 |
+
return
|
| 120 |
+
if self.jwt_secret_key == DEFAULT_JWT_SECRET or len(self.jwt_secret_key) < 32:
|
| 121 |
+
raise RuntimeError(
|
| 122 |
+
"JWT_SECRET_KEY must be set to a strong non-default value in production"
|
| 123 |
+
)
|
| 124 |
|
| 125 |
class Config:
|
| 126 |
env_file = ".env"
|
backend/app/dependencies.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
from datetime import datetime, timedelta
|
| 4 |
import hashlib
|
| 5 |
|
| 6 |
-
from fastapi import Depends, HTTPException, Request, status
|
| 7 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 8 |
from sqlalchemy.orm import Session
|
| 9 |
|
|
@@ -40,15 +40,22 @@ def user_public(user: User) -> dict:
|
|
| 40 |
|
| 41 |
|
| 42 |
async def get_current_user_optional(
|
|
|
|
| 43 |
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
|
|
|
| 44 |
db: Session = Depends(get_db),
|
| 45 |
) -> User | None:
|
| 46 |
-
if credentials
|
|
|
|
| 47 |
return None
|
| 48 |
-
payload = decode_access_token(
|
| 49 |
if not payload or not payload.get("sub"):
|
| 50 |
return None
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
if not user or not user.is_active:
|
| 53 |
return None
|
| 54 |
return user
|
|
@@ -79,8 +86,7 @@ async def require_admin(user: User = Depends(get_current_user)) -> User:
|
|
| 79 |
|
| 80 |
|
| 81 |
def anonymous_key(request: Request) -> str:
|
| 82 |
-
|
| 83 |
-
ip = forwarded.split(",", 1)[0].strip() or (request.client.host if request.client else "unknown")
|
| 84 |
return hashlib.sha256(f"{ip}:{settings.jwt_secret_key}".encode("utf-8")).hexdigest()
|
| 85 |
|
| 86 |
|
|
|
|
| 3 |
from datetime import datetime, timedelta
|
| 4 |
import hashlib
|
| 5 |
|
| 6 |
+
from fastapi import Cookie, Depends, HTTPException, Request, status
|
| 7 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 8 |
from sqlalchemy.orm import Session
|
| 9 |
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
async def get_current_user_optional(
|
| 43 |
+
request: Request,
|
| 44 |
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
| 45 |
+
session_token: str | None = Cookie(default=None, alias="malwareguard_session"),
|
| 46 |
db: Session = Depends(get_db),
|
| 47 |
) -> User | None:
|
| 48 |
+
token = session_token or (credentials.credentials if credentials else None)
|
| 49 |
+
if not token:
|
| 50 |
return None
|
| 51 |
+
payload = decode_access_token(token)
|
| 52 |
if not payload or not payload.get("sub"):
|
| 53 |
return None
|
| 54 |
+
try:
|
| 55 |
+
user_id = int(payload["sub"])
|
| 56 |
+
except (TypeError, ValueError):
|
| 57 |
+
return None
|
| 58 |
+
user = db.query(User).filter(User.id == user_id).first()
|
| 59 |
if not user or not user.is_active:
|
| 60 |
return None
|
| 61 |
return user
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
def anonymous_key(request: Request) -> str:
|
| 89 |
+
ip = request.client.host if request.client else "unknown"
|
|
|
|
| 90 |
return hashlib.sha256(f"{ip}:{settings.jwt_secret_key}".encode("utf-8")).hexdigest()
|
| 91 |
|
| 92 |
|
backend/app/main.py
CHANGED
|
@@ -14,11 +14,11 @@ from contextlib import asynccontextmanager
|
|
| 14 |
from fastapi import FastAPI, Request
|
| 15 |
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
from fastapi.responses import JSONResponse
|
| 17 |
-
from slowapi import
|
| 18 |
-
from slowapi.
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
from .
|
| 22 |
from .routers import admin, auth, predict, virustotal, chat, upload, url, feedback
|
| 23 |
from .database import init_db
|
| 24 |
from .services.ml_service import get_ml_service
|
|
@@ -36,12 +36,8 @@ logging.basicConfig(
|
|
| 36 |
)
|
| 37 |
logger = logging.getLogger(__name__)
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
@asynccontextmanager
|
| 44 |
-
async def lifespan(app: FastAPI):
|
| 45 |
"""
|
| 46 |
Application lifespan manager.
|
| 47 |
Handles startup and shutdown events.
|
|
@@ -50,6 +46,7 @@ async def lifespan(app: FastAPI):
|
|
| 50 |
logger.info("=" * 60)
|
| 51 |
logger.info("Malware Detection Platform Starting...")
|
| 52 |
logger.info("=" * 60)
|
|
|
|
| 53 |
|
| 54 |
try:
|
| 55 |
init_db()
|
|
@@ -150,26 +147,37 @@ app = FastAPI(
|
|
| 150 |
- `/api/virustotal/compare` - Compare XGBoost vs VirusTotal verdicts
|
| 151 |
- `/api/url/analyze` - Analyze URL for malicious indicators
|
| 152 |
""",
|
| 153 |
-
version="1.0.0",
|
| 154 |
-
lifespan=lifespan,
|
| 155 |
-
docs_url="/docs",
|
| 156 |
-
redoc_url="/redoc"
|
| 157 |
-
|
|
|
|
| 158 |
|
| 159 |
# Add rate limiter to app state
|
| 160 |
app.state.limiter = limiter
|
| 161 |
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 162 |
|
| 163 |
# Configure CORS
|
| 164 |
-
app.add_middleware(
|
| 165 |
-
CORSMiddleware,
|
| 166 |
-
allow_origins=settings.
|
| 167 |
-
allow_credentials=True,
|
| 168 |
-
allow_methods=["
|
| 169 |
-
allow_headers=["
|
| 170 |
-
)
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
# Global exception handler
|
| 174 |
@app.exception_handler(Exception)
|
| 175 |
async def global_exception_handler(request: Request, exc: Exception):
|
|
@@ -217,9 +225,12 @@ async def root():
|
|
| 217 |
|
| 218 |
|
| 219 |
@app.get("/health", tags=["health"])
|
| 220 |
-
async def health_check():
|
| 221 |
-
"""Global health check endpoint."""
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
| 223 |
vt_service = get_virustotal_service()
|
| 224 |
gemini_service = get_gemini_service()
|
| 225 |
|
|
|
|
| 14 |
from fastapi import FastAPI, Request
|
| 15 |
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
from fastapi.responses import JSONResponse
|
| 17 |
+
from slowapi import _rate_limit_exceeded_handler
|
| 18 |
+
from slowapi.errors import RateLimitExceeded
|
| 19 |
+
|
| 20 |
+
from .config import settings
|
| 21 |
+
from .rate_limit import limiter
|
| 22 |
from .routers import admin, auth, predict, virustotal, chat, upload, url, feedback
|
| 23 |
from .database import init_db
|
| 24 |
from .services.ml_service import get_ml_service
|
|
|
|
| 36 |
)
|
| 37 |
logger = logging.getLogger(__name__)
|
| 38 |
|
| 39 |
+
@asynccontextmanager
|
| 40 |
+
async def lifespan(app: FastAPI):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
"""
|
| 42 |
Application lifespan manager.
|
| 43 |
Handles startup and shutdown events.
|
|
|
|
| 46 |
logger.info("=" * 60)
|
| 47 |
logger.info("Malware Detection Platform Starting...")
|
| 48 |
logger.info("=" * 60)
|
| 49 |
+
settings.validate_security()
|
| 50 |
|
| 51 |
try:
|
| 52 |
init_db()
|
|
|
|
| 147 |
- `/api/virustotal/compare` - Compare XGBoost vs VirusTotal verdicts
|
| 148 |
- `/api/url/analyze` - Analyze URL for malicious indicators
|
| 149 |
""",
|
| 150 |
+
version="1.0.0",
|
| 151 |
+
lifespan=lifespan,
|
| 152 |
+
docs_url="/docs" if settings.debug else None,
|
| 153 |
+
redoc_url="/redoc" if settings.debug else None,
|
| 154 |
+
openapi_url="/openapi.json" if settings.debug else None,
|
| 155 |
+
)
|
| 156 |
|
| 157 |
# Add rate limiter to app state
|
| 158 |
app.state.limiter = limiter
|
| 159 |
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 160 |
|
| 161 |
# Configure CORS
|
| 162 |
+
app.add_middleware(
|
| 163 |
+
CORSMiddleware,
|
| 164 |
+
allow_origins=settings.effective_cors_origins,
|
| 165 |
+
allow_credentials=True,
|
| 166 |
+
allow_methods=["GET", "POST", "PATCH", "OPTIONS"],
|
| 167 |
+
allow_headers=["Authorization", "Content-Type"],
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@app.middleware("http")
|
| 172 |
+
async def security_headers(request: Request, call_next):
|
| 173 |
+
response = await call_next(request)
|
| 174 |
+
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
| 175 |
+
response.headers.setdefault("X-Frame-Options", "DENY")
|
| 176 |
+
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
|
| 177 |
+
response.headers.setdefault("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
| 178 |
+
return response
|
| 179 |
+
|
| 180 |
+
|
| 181 |
# Global exception handler
|
| 182 |
@app.exception_handler(Exception)
|
| 183 |
async def global_exception_handler(request: Request, exc: Exception):
|
|
|
|
| 225 |
|
| 226 |
|
| 227 |
@app.get("/health", tags=["health"])
|
| 228 |
+
async def health_check():
|
| 229 |
+
"""Global health check endpoint."""
|
| 230 |
+
if settings.is_production:
|
| 231 |
+
return {"status": "healthy"}
|
| 232 |
+
|
| 233 |
+
ml_service = get_ml_service()
|
| 234 |
vt_service = get_virustotal_service()
|
| 235 |
gemini_service = get_gemini_service()
|
| 236 |
|
backend/app/rate_limit.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared API rate limiter."""
|
| 2 |
+
|
| 3 |
+
from slowapi import Limiter
|
| 4 |
+
from slowapi.util import get_remote_address
|
| 5 |
+
|
| 6 |
+
limiter = Limiter(key_func=get_remote_address)
|
backend/app/routers/admin.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
| 1 |
"""Admin-only user management endpoints."""
|
| 2 |
|
| 3 |
from pydantic import BaseModel, Field
|
| 4 |
-
from fastapi import APIRouter, Depends, HTTPException
|
| 5 |
from sqlalchemy import func
|
| 6 |
from sqlalchemy.orm import Session
|
| 7 |
|
| 8 |
from ..database import get_db
|
| 9 |
from ..db_models import AuditLog, ScanEvent, User
|
| 10 |
from ..dependencies import record_audit_log, require_admin, user_public
|
|
|
|
|
|
|
| 11 |
from ..services.feedback_service import get_feedback_service
|
| 12 |
from ..services.gemini_service import get_gemini_service
|
| 13 |
from ..services.ml_service import get_ml_service
|
|
@@ -94,7 +96,9 @@ def service_health() -> dict:
|
|
| 94 |
|
| 95 |
|
| 96 |
@router.get("/users")
|
|
|
|
| 97 |
async def list_users(
|
|
|
|
| 98 |
_: User = Depends(require_admin),
|
| 99 |
db: Session = Depends(get_db),
|
| 100 |
):
|
|
@@ -103,7 +107,9 @@ async def list_users(
|
|
| 103 |
|
| 104 |
|
| 105 |
@router.get("/overview")
|
|
|
|
| 106 |
async def get_overview(
|
|
|
|
| 107 |
_: User = Depends(require_admin),
|
| 108 |
db: Session = Depends(get_db),
|
| 109 |
):
|
|
@@ -133,7 +139,9 @@ async def get_overview(
|
|
| 133 |
|
| 134 |
|
| 135 |
@router.get("/scans")
|
|
|
|
| 136 |
async def list_scans(
|
|
|
|
| 137 |
limit: int = 50,
|
| 138 |
_: User = Depends(require_admin),
|
| 139 |
db: Session = Depends(get_db),
|
|
@@ -144,7 +152,9 @@ async def list_scans(
|
|
| 144 |
|
| 145 |
|
| 146 |
@router.get("/audit-logs")
|
|
|
|
| 147 |
async def list_audit_logs(
|
|
|
|
| 148 |
limit: int = 50,
|
| 149 |
_: User = Depends(require_admin),
|
| 150 |
db: Session = Depends(get_db),
|
|
@@ -155,7 +165,9 @@ async def list_audit_logs(
|
|
| 155 |
|
| 156 |
|
| 157 |
@router.patch("/users/{user_id}")
|
|
|
|
| 158 |
async def update_user(
|
|
|
|
| 159 |
user_id: int,
|
| 160 |
body: UserUpdateRequest,
|
| 161 |
actor: User = Depends(require_admin),
|
|
|
|
| 1 |
"""Admin-only user management endpoints."""
|
| 2 |
|
| 3 |
from pydantic import BaseModel, Field
|
| 4 |
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
| 5 |
from sqlalchemy import func
|
| 6 |
from sqlalchemy.orm import Session
|
| 7 |
|
| 8 |
from ..database import get_db
|
| 9 |
from ..db_models import AuditLog, ScanEvent, User
|
| 10 |
from ..dependencies import record_audit_log, require_admin, user_public
|
| 11 |
+
from ..config import settings
|
| 12 |
+
from ..rate_limit import limiter
|
| 13 |
from ..services.feedback_service import get_feedback_service
|
| 14 |
from ..services.gemini_service import get_gemini_service
|
| 15 |
from ..services.ml_service import get_ml_service
|
|
|
|
| 96 |
|
| 97 |
|
| 98 |
@router.get("/users")
|
| 99 |
+
@limiter.limit(settings.rate_limit_admin)
|
| 100 |
async def list_users(
|
| 101 |
+
request: Request,
|
| 102 |
_: User = Depends(require_admin),
|
| 103 |
db: Session = Depends(get_db),
|
| 104 |
):
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
@router.get("/overview")
|
| 110 |
+
@limiter.limit(settings.rate_limit_admin)
|
| 111 |
async def get_overview(
|
| 112 |
+
request: Request,
|
| 113 |
_: User = Depends(require_admin),
|
| 114 |
db: Session = Depends(get_db),
|
| 115 |
):
|
|
|
|
| 139 |
|
| 140 |
|
| 141 |
@router.get("/scans")
|
| 142 |
+
@limiter.limit(settings.rate_limit_admin)
|
| 143 |
async def list_scans(
|
| 144 |
+
request: Request,
|
| 145 |
limit: int = 50,
|
| 146 |
_: User = Depends(require_admin),
|
| 147 |
db: Session = Depends(get_db),
|
|
|
|
| 152 |
|
| 153 |
|
| 154 |
@router.get("/audit-logs")
|
| 155 |
+
@limiter.limit(settings.rate_limit_admin)
|
| 156 |
async def list_audit_logs(
|
| 157 |
+
request: Request,
|
| 158 |
limit: int = 50,
|
| 159 |
_: User = Depends(require_admin),
|
| 160 |
db: Session = Depends(get_db),
|
|
|
|
| 165 |
|
| 166 |
|
| 167 |
@router.patch("/users/{user_id}")
|
| 168 |
+
@limiter.limit(settings.rate_limit_admin)
|
| 169 |
async def update_user(
|
| 170 |
+
request: Request,
|
| 171 |
user_id: int,
|
| 172 |
body: UserUpdateRequest,
|
| 173 |
actor: User = Depends(require_admin),
|
backend/app/routers/auth.py
CHANGED
|
@@ -1,15 +1,18 @@
|
|
| 1 |
"""Signup, login, and current-user endpoints."""
|
| 2 |
|
| 3 |
from pydantic import BaseModel, Field, field_validator
|
| 4 |
-
from fastapi import APIRouter, Depends, HTTPException, status
|
| 5 |
from sqlalchemy.orm import Session
|
| 6 |
|
|
|
|
| 7 |
from ..database import get_db
|
| 8 |
from ..db_models import User
|
| 9 |
-
from ..dependencies import
|
|
|
|
| 10 |
from ..security import create_access_token, hash_password, verify_password
|
| 11 |
|
| 12 |
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
class SignupRequest(BaseModel):
|
|
@@ -32,39 +35,57 @@ class LoginRequest(BaseModel):
|
|
| 32 |
|
| 33 |
|
| 34 |
class AuthResponse(BaseModel):
|
| 35 |
-
access_token: str
|
| 36 |
token_type: str = "bearer"
|
| 37 |
user: dict
|
| 38 |
|
| 39 |
|
| 40 |
-
def
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
|
| 46 |
@router.post("/signup", response_model=AuthResponse, status_code=status.HTTP_201_CREATED)
|
| 47 |
-
|
|
|
|
| 48 |
existing = db.query(User).filter(User.email == body.email).first()
|
| 49 |
if existing:
|
| 50 |
raise HTTPException(status_code=409, detail="An account with this email already exists")
|
| 51 |
-
role, tier = _role_and_tier(body.email)
|
| 52 |
user = User(
|
| 53 |
email=body.email,
|
| 54 |
password_hash=hash_password(body.password),
|
| 55 |
display_name=body.display_name,
|
| 56 |
-
role=
|
| 57 |
-
tier=
|
| 58 |
)
|
| 59 |
db.add(user)
|
| 60 |
db.commit()
|
| 61 |
db.refresh(user)
|
| 62 |
token = create_access_token(str(user.id), {"role": user.role, "tier": user.tier})
|
| 63 |
-
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
@router.post("/login", response_model=AuthResponse)
|
| 67 |
-
|
|
|
|
| 68 |
email = body.email.strip().lower()
|
| 69 |
user = db.query(User).filter(User.email == email).first()
|
| 70 |
if not user or not verify_password(body.password, user.password_hash):
|
|
@@ -72,7 +93,15 @@ async def login(body: LoginRequest, db: Session = Depends(get_db)):
|
|
| 72 |
if not user.is_active:
|
| 73 |
raise HTTPException(status_code=403, detail="Account disabled")
|
| 74 |
token = create_access_token(str(user.id), {"role": user.role, "tier": user.tier})
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
@router.get("/me")
|
|
|
|
| 1 |
"""Signup, login, and current-user endpoints."""
|
| 2 |
|
| 3 |
from pydantic import BaseModel, Field, field_validator
|
| 4 |
+
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
| 5 |
from sqlalchemy.orm import Session
|
| 6 |
|
| 7 |
+
from ..config import settings
|
| 8 |
from ..database import get_db
|
| 9 |
from ..db_models import User
|
| 10 |
+
from ..dependencies import get_current_user, user_public
|
| 11 |
+
from ..rate_limit import limiter
|
| 12 |
from ..security import create_access_token, hash_password, verify_password
|
| 13 |
|
| 14 |
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
| 15 |
+
SESSION_COOKIE = "malwareguard_session"
|
| 16 |
|
| 17 |
|
| 18 |
class SignupRequest(BaseModel):
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
class AuthResponse(BaseModel):
|
| 38 |
+
access_token: str | None = None
|
| 39 |
token_type: str = "bearer"
|
| 40 |
user: dict
|
| 41 |
|
| 42 |
|
| 43 |
+
def set_session_cookie(response: Response, token: str) -> None:
|
| 44 |
+
response.set_cookie(
|
| 45 |
+
key=SESSION_COOKIE,
|
| 46 |
+
value=token,
|
| 47 |
+
max_age=settings.jwt_expire_minutes * 60,
|
| 48 |
+
httponly=True,
|
| 49 |
+
secure=settings.cookie_secure,
|
| 50 |
+
samesite="lax",
|
| 51 |
+
path="/",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def clear_session_cookie(response: Response) -> None:
|
| 56 |
+
response.delete_cookie(
|
| 57 |
+
key=SESSION_COOKIE,
|
| 58 |
+
httponly=True,
|
| 59 |
+
secure=settings.cookie_secure,
|
| 60 |
+
samesite="lax",
|
| 61 |
+
path="/",
|
| 62 |
+
)
|
| 63 |
|
| 64 |
|
| 65 |
@router.post("/signup", response_model=AuthResponse, status_code=status.HTTP_201_CREATED)
|
| 66 |
+
@limiter.limit(settings.rate_limit_signup)
|
| 67 |
+
async def signup(request: Request, response: Response, body: SignupRequest, db: Session = Depends(get_db)):
|
| 68 |
existing = db.query(User).filter(User.email == body.email).first()
|
| 69 |
if existing:
|
| 70 |
raise HTTPException(status_code=409, detail="An account with this email already exists")
|
|
|
|
| 71 |
user = User(
|
| 72 |
email=body.email,
|
| 73 |
password_hash=hash_password(body.password),
|
| 74 |
display_name=body.display_name,
|
| 75 |
+
role="user",
|
| 76 |
+
tier="free",
|
| 77 |
)
|
| 78 |
db.add(user)
|
| 79 |
db.commit()
|
| 80 |
db.refresh(user)
|
| 81 |
token = create_access_token(str(user.id), {"role": user.role, "tier": user.tier})
|
| 82 |
+
set_session_cookie(response, token)
|
| 83 |
+
return AuthResponse(access_token=None if settings.is_production else token, user=user_public(user))
|
| 84 |
|
| 85 |
|
| 86 |
@router.post("/login", response_model=AuthResponse)
|
| 87 |
+
@limiter.limit(settings.rate_limit_auth)
|
| 88 |
+
async def login(request: Request, response: Response, body: LoginRequest, db: Session = Depends(get_db)):
|
| 89 |
email = body.email.strip().lower()
|
| 90 |
user = db.query(User).filter(User.email == email).first()
|
| 91 |
if not user or not verify_password(body.password, user.password_hash):
|
|
|
|
| 93 |
if not user.is_active:
|
| 94 |
raise HTTPException(status_code=403, detail="Account disabled")
|
| 95 |
token = create_access_token(str(user.id), {"role": user.role, "tier": user.tier})
|
| 96 |
+
set_session_cookie(response, token)
|
| 97 |
+
return AuthResponse(access_token=None if settings.is_production else token, user=user_public(user))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@router.post("/logout")
|
| 101 |
+
@limiter.limit(settings.rate_limit_auth)
|
| 102 |
+
async def logout(request: Request, response: Response):
|
| 103 |
+
clear_session_cookie(response)
|
| 104 |
+
return {"success": True}
|
| 105 |
|
| 106 |
|
| 107 |
@router.get("/me")
|
backend/app/routers/chat.py
CHANGED
|
@@ -2,12 +2,14 @@
|
|
| 2 |
Chat Router - Gemini-powered chatbot endpoint for the malware detection platform.
|
| 3 |
"""
|
| 4 |
|
| 5 |
-
from fastapi import APIRouter
|
| 6 |
from pydantic import BaseModel, Field
|
| 7 |
from typing import Optional, List
|
| 8 |
-
import logging
|
| 9 |
-
|
| 10 |
-
from ..
|
|
|
|
|
|
|
| 11 |
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
|
@@ -130,8 +132,9 @@ Guidelines:
|
|
| 130 |
User message: {message}"""
|
| 131 |
|
| 132 |
|
| 133 |
-
@router.post("/", response_model=ChatResponse)
|
| 134 |
-
|
|
|
|
| 135 |
"""
|
| 136 |
Send a message to the AI chatbot.
|
| 137 |
|
|
@@ -146,13 +149,13 @@ async def chat(request: ChatRequest):
|
|
| 146 |
if not gemini_service.initialized:
|
| 147 |
gemini_service.initialize()
|
| 148 |
|
| 149 |
-
if not gemini_service.initialized or gemini_service.model is None:
|
| 150 |
-
logger.warning("Gemini chatbot unavailable, using fallback response")
|
| 151 |
-
return ChatResponse(response=_fallback_chat_response(
|
| 152 |
-
|
| 153 |
-
try:
|
| 154 |
-
# Format the prompt with user message
|
| 155 |
-
prompt = CHATBOT_SYSTEM_PROMPT.format(message=
|
| 156 |
|
| 157 |
# Call Gemini API
|
| 158 |
response = gemini_service.model.generate_content(prompt)
|
|
@@ -161,11 +164,11 @@ async def chat(request: ChatRequest):
|
|
| 161 |
return ChatResponse(response=response.text)
|
| 162 |
else:
|
| 163 |
logger.warning("Gemini returned an empty chatbot response, using fallback")
|
| 164 |
-
return ChatResponse(response=_fallback_chat_response(
|
| 165 |
|
| 166 |
except Exception as e:
|
| 167 |
logger.error(f"Chat error: {e}")
|
| 168 |
-
return ChatResponse(response=_fallback_chat_response(
|
| 169 |
|
| 170 |
|
| 171 |
@router.get("/health")
|
|
|
|
| 2 |
Chat Router - Gemini-powered chatbot endpoint for the malware detection platform.
|
| 3 |
"""
|
| 4 |
|
| 5 |
+
from fastapi import APIRouter, Request
|
| 6 |
from pydantic import BaseModel, Field
|
| 7 |
from typing import Optional, List
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
from ..config import settings
|
| 11 |
+
from ..rate_limit import limiter
|
| 12 |
+
from ..services.gemini_service import get_gemini_service
|
| 13 |
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
|
|
|
| 132 |
User message: {message}"""
|
| 133 |
|
| 134 |
|
| 135 |
+
@router.post("/", response_model=ChatResponse)
|
| 136 |
+
@limiter.limit(settings.rate_limit_chat)
|
| 137 |
+
async def chat(request: Request, body: ChatRequest):
|
| 138 |
"""
|
| 139 |
Send a message to the AI chatbot.
|
| 140 |
|
|
|
|
| 149 |
if not gemini_service.initialized:
|
| 150 |
gemini_service.initialize()
|
| 151 |
|
| 152 |
+
if not gemini_service.initialized or gemini_service.model is None:
|
| 153 |
+
logger.warning("Gemini chatbot unavailable, using fallback response")
|
| 154 |
+
return ChatResponse(response=_fallback_chat_response(body.message))
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
# Format the prompt with user message
|
| 158 |
+
prompt = CHATBOT_SYSTEM_PROMPT.format(message=body.message)
|
| 159 |
|
| 160 |
# Call Gemini API
|
| 161 |
response = gemini_service.model.generate_content(prompt)
|
|
|
|
| 164 |
return ChatResponse(response=response.text)
|
| 165 |
else:
|
| 166 |
logger.warning("Gemini returned an empty chatbot response, using fallback")
|
| 167 |
+
return ChatResponse(response=_fallback_chat_response(body.message))
|
| 168 |
|
| 169 |
except Exception as e:
|
| 170 |
logger.error(f"Chat error: {e}")
|
| 171 |
+
return ChatResponse(response=_fallback_chat_response(body.message))
|
| 172 |
|
| 173 |
|
| 174 |
@router.get("/health")
|
backend/app/routers/feedback.py
CHANGED
|
@@ -9,8 +9,8 @@ Endpoints:
|
|
| 9 |
GET /api/feedback/health — Health check
|
| 10 |
"""
|
| 11 |
|
| 12 |
-
import logging
|
| 13 |
-
from fastapi import APIRouter, Depends, HTTPException
|
| 14 |
|
| 15 |
from ..models.feedback import (
|
| 16 |
MalwareFeedbackRequest,
|
|
@@ -22,7 +22,9 @@ from ..models.feedback import (
|
|
| 22 |
)
|
| 23 |
from ..services.feedback_service import get_feedback_service
|
| 24 |
from ..db_models import User
|
| 25 |
-
from ..
|
|
|
|
|
|
|
| 26 |
|
| 27 |
logger = logging.getLogger(__name__)
|
| 28 |
|
|
@@ -35,8 +37,9 @@ router = APIRouter(
|
|
| 35 |
|
| 36 |
# ── Malware RL ────────────────────────────────────────────────────────────────
|
| 37 |
|
| 38 |
-
@router.post("/malware", response_model=FeedbackResponse)
|
| 39 |
-
|
|
|
|
| 40 |
"""
|
| 41 |
Submit malware RL feedback based on VirusTotal comparison.
|
| 42 |
|
|
@@ -55,9 +58,7 @@ async def submit_malware_feedback(body: MalwareFeedbackRequest, _: User = Depend
|
|
| 55 |
vt_total=body.vt_total_engines,
|
| 56 |
vt_ratio=body.vt_detection_ratio,
|
| 57 |
)
|
| 58 |
-
|
| 59 |
-
svc.maybe_auto_update("malware")
|
| 60 |
-
return FeedbackResponse(**result)
|
| 61 |
except Exception as e:
|
| 62 |
logger.error(f"Malware feedback error: {e}", exc_info=True)
|
| 63 |
raise HTTPException(status_code=500, detail=f"Feedback failed: {e}")
|
|
@@ -65,8 +66,13 @@ async def submit_malware_feedback(body: MalwareFeedbackRequest, _: User = Depend
|
|
| 65 |
|
| 66 |
# ── URL RL ────────────────────────────────────────────────────────────────────
|
| 67 |
|
| 68 |
-
@router.post("/url", response_model=FeedbackResponse)
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
"""
|
| 71 |
Submit URL RL feedback from user confirmation popup.
|
| 72 |
|
|
@@ -83,9 +89,7 @@ async def submit_url_feedback(body: URLFeedbackRequest):
|
|
| 83 |
is_correct=body.is_correct,
|
| 84 |
base_model_scores=body.base_model_scores,
|
| 85 |
)
|
| 86 |
-
|
| 87 |
-
svc.maybe_auto_update("url")
|
| 88 |
-
return FeedbackResponse(**result)
|
| 89 |
except Exception as e:
|
| 90 |
logger.error(f"URL feedback error: {e}", exc_info=True)
|
| 91 |
raise HTTPException(status_code=500, detail=f"Feedback failed: {e}")
|
|
@@ -144,9 +148,11 @@ async def update_model(body: ModelUpdateRequest, _: User = Depends(require_admin
|
|
| 144 |
# ── Health ────────────────────────────────────────────────────────────────────
|
| 145 |
|
| 146 |
@router.get("/health")
|
| 147 |
-
async def feedback_health():
|
| 148 |
-
"""Health check for the RL feedback service."""
|
| 149 |
-
|
|
|
|
|
|
|
| 150 |
svc = get_feedback_service()
|
| 151 |
stats = svc.get_stats()
|
| 152 |
return {
|
|
|
|
| 9 |
GET /api/feedback/health — Health check
|
| 10 |
"""
|
| 11 |
|
| 12 |
+
import logging
|
| 13 |
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
| 14 |
|
| 15 |
from ..models.feedback import (
|
| 16 |
MalwareFeedbackRequest,
|
|
|
|
| 22 |
)
|
| 23 |
from ..services.feedback_service import get_feedback_service
|
| 24 |
from ..db_models import User
|
| 25 |
+
from ..config import settings
|
| 26 |
+
from ..dependencies import get_current_user, require_admin, require_analyst
|
| 27 |
+
from ..rate_limit import limiter
|
| 28 |
|
| 29 |
logger = logging.getLogger(__name__)
|
| 30 |
|
|
|
|
| 37 |
|
| 38 |
# ── Malware RL ────────────────────────────────────────────────────────────────
|
| 39 |
|
| 40 |
+
@router.post("/malware", response_model=FeedbackResponse)
|
| 41 |
+
@limiter.limit(settings.rate_limit_feedback)
|
| 42 |
+
async def submit_malware_feedback(request: Request, body: MalwareFeedbackRequest, _: User = Depends(require_analyst)):
|
| 43 |
"""
|
| 44 |
Submit malware RL feedback based on VirusTotal comparison.
|
| 45 |
|
|
|
|
| 58 |
vt_total=body.vt_total_engines,
|
| 59 |
vt_ratio=body.vt_detection_ratio,
|
| 60 |
)
|
| 61 |
+
return FeedbackResponse(**result)
|
|
|
|
|
|
|
| 62 |
except Exception as e:
|
| 63 |
logger.error(f"Malware feedback error: {e}", exc_info=True)
|
| 64 |
raise HTTPException(status_code=500, detail=f"Feedback failed: {e}")
|
|
|
|
| 66 |
|
| 67 |
# ── URL RL ────────────────────────────────────────────────────────────────────
|
| 68 |
|
| 69 |
+
@router.post("/url", response_model=FeedbackResponse)
|
| 70 |
+
@limiter.limit(settings.rate_limit_feedback)
|
| 71 |
+
async def submit_url_feedback(
|
| 72 |
+
request: Request,
|
| 73 |
+
body: URLFeedbackRequest,
|
| 74 |
+
_: User = Depends(get_current_user),
|
| 75 |
+
):
|
| 76 |
"""
|
| 77 |
Submit URL RL feedback from user confirmation popup.
|
| 78 |
|
|
|
|
| 89 |
is_correct=body.is_correct,
|
| 90 |
base_model_scores=body.base_model_scores,
|
| 91 |
)
|
| 92 |
+
return FeedbackResponse(**result)
|
|
|
|
|
|
|
| 93 |
except Exception as e:
|
| 94 |
logger.error(f"URL feedback error: {e}", exc_info=True)
|
| 95 |
raise HTTPException(status_code=500, detail=f"Feedback failed: {e}")
|
|
|
|
| 148 |
# ── Health ────────────────────────────────────────────────────────────────────
|
| 149 |
|
| 150 |
@router.get("/health")
|
| 151 |
+
async def feedback_health():
|
| 152 |
+
"""Health check for the RL feedback service."""
|
| 153 |
+
if settings.is_production:
|
| 154 |
+
return {"status": "healthy"}
|
| 155 |
+
try:
|
| 156 |
svc = get_feedback_service()
|
| 157 |
stats = svc.get_stats()
|
| 158 |
return {
|
backend/app/routers/predict.py
CHANGED
|
@@ -3,8 +3,8 @@ Prediction API Router.
|
|
| 3 |
Handles XGBoost malware prediction and Gemini explanation endpoints.
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
import logging
|
| 7 |
-
from fastapi import APIRouter, HTTPException, Depends
|
| 8 |
from typing import Optional
|
| 9 |
from pydantic import BaseModel, Field
|
| 10 |
|
|
@@ -19,6 +19,8 @@ from ..services.shap_service import get_shap_service, SHAPService
|
|
| 19 |
from ..services.malware_type_service import get_malware_type_service
|
| 20 |
from ..db_models import User
|
| 21 |
from ..dependencies import require_analyst
|
|
|
|
|
|
|
| 22 |
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
|
@@ -40,9 +42,11 @@ class PredictionWithTypeResponse(BaseModel):
|
|
| 40 |
malware_type: Optional[MalwareTypeInfo] = None
|
| 41 |
|
| 42 |
|
| 43 |
-
@router.post("", response_model=PredictionWithTypeResponse)
|
|
|
|
| 44 |
async def predict(
|
| 45 |
-
request:
|
|
|
|
| 46 |
_: User = Depends(require_analyst),
|
| 47 |
ml_service: MLService = Depends(get_ml_service)
|
| 48 |
) -> PredictionWithTypeResponse:
|
|
@@ -58,23 +62,23 @@ async def predict(
|
|
| 58 |
- **include_shap**: Include SHAP feature importance (slower)
|
| 59 |
"""
|
| 60 |
try:
|
| 61 |
-
# Run prediction
|
| 62 |
-
prediction = ml_service.predict(
|
| 63 |
-
features=
|
| 64 |
-
threshold=
|
| 65 |
-
sha256=
|
| 66 |
-
)
|
| 67 |
|
| 68 |
# Add SHAP analysis if requested
|
| 69 |
-
if
|
| 70 |
shap_service = get_shap_service()
|
| 71 |
if not shap_service.initialized:
|
| 72 |
shap_service.initialize(ml_service.model)
|
| 73 |
|
| 74 |
top_features = shap_service.get_feature_importance(
|
| 75 |
-
features=
|
| 76 |
-
model=ml_service.model,
|
| 77 |
-
top_k=10
|
| 78 |
)
|
| 79 |
prediction.top_features = top_features
|
| 80 |
|
|
@@ -111,9 +115,11 @@ async def predict(
|
|
| 111 |
raise HTTPException(status_code=500, detail="Prediction failed")
|
| 112 |
|
| 113 |
|
| 114 |
-
@router.post("/explain", response_model=PredictionWithExplanationResponse)
|
|
|
|
| 115 |
async def predict_with_explanation(
|
| 116 |
-
request:
|
|
|
|
| 117 |
_: User = Depends(require_analyst),
|
| 118 |
ml_service: MLService = Depends(get_ml_service),
|
| 119 |
gemini_service: GeminiService = Depends(get_gemini_service)
|
|
@@ -129,12 +135,12 @@ async def predict_with_explanation(
|
|
| 129 |
provides explanation and context.
|
| 130 |
"""
|
| 131 |
try:
|
| 132 |
-
# Run prediction
|
| 133 |
-
prediction = ml_service.predict(
|
| 134 |
-
features=
|
| 135 |
-
threshold=
|
| 136 |
-
sha256=
|
| 137 |
-
)
|
| 138 |
|
| 139 |
# Get SHAP features for better explanation
|
| 140 |
shap_service = get_shap_service()
|
|
@@ -142,9 +148,9 @@ async def predict_with_explanation(
|
|
| 142 |
shap_service.initialize(ml_service.model)
|
| 143 |
|
| 144 |
top_features = shap_service.get_feature_importance(
|
| 145 |
-
features=
|
| 146 |
-
model=ml_service.model,
|
| 147 |
-
top_k=10
|
| 148 |
)
|
| 149 |
prediction.top_features = top_features
|
| 150 |
|
|
@@ -190,19 +196,23 @@ async def predict_with_explanation(
|
|
| 190 |
|
| 191 |
|
| 192 |
@router.get("/model-info")
|
| 193 |
-
async def get_model_info(
|
| 194 |
ml_service: MLService = Depends(get_ml_service)
|
| 195 |
-
) -> dict:
|
| 196 |
-
"""Get information about the loaded XGBoost model."""
|
| 197 |
-
|
|
|
|
|
|
|
| 198 |
|
| 199 |
|
| 200 |
@router.get("/health")
|
| 201 |
-
async def health_check(
|
| 202 |
ml_service: MLService = Depends(get_ml_service)
|
| 203 |
-
) -> dict:
|
| 204 |
-
"""Health check endpoint for the prediction service."""
|
| 205 |
-
|
|
|
|
|
|
|
| 206 |
"status": "healthy",
|
| 207 |
"model_loaded": ml_service.model_loaded,
|
| 208 |
"feature_count": ml_service.feature_count
|
|
|
|
| 3 |
Handles XGBoost malware prediction and Gemini explanation endpoints.
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
import logging
|
| 7 |
+
from fastapi import APIRouter, HTTPException, Depends, Request
|
| 8 |
from typing import Optional
|
| 9 |
from pydantic import BaseModel, Field
|
| 10 |
|
|
|
|
| 19 |
from ..services.malware_type_service import get_malware_type_service
|
| 20 |
from ..db_models import User
|
| 21 |
from ..dependencies import require_analyst
|
| 22 |
+
from ..config import settings
|
| 23 |
+
from ..rate_limit import limiter
|
| 24 |
|
| 25 |
logger = logging.getLogger(__name__)
|
| 26 |
|
|
|
|
| 42 |
malware_type: Optional[MalwareTypeInfo] = None
|
| 43 |
|
| 44 |
|
| 45 |
+
@router.post("", response_model=PredictionWithTypeResponse)
|
| 46 |
+
@limiter.limit(settings.rate_limit_prediction)
|
| 47 |
async def predict(
|
| 48 |
+
request: Request,
|
| 49 |
+
body: PredictionRequest,
|
| 50 |
_: User = Depends(require_analyst),
|
| 51 |
ml_service: MLService = Depends(get_ml_service)
|
| 52 |
) -> PredictionWithTypeResponse:
|
|
|
|
| 62 |
- **include_shap**: Include SHAP feature importance (slower)
|
| 63 |
"""
|
| 64 |
try:
|
| 65 |
+
# Run prediction
|
| 66 |
+
prediction = ml_service.predict(
|
| 67 |
+
features=body.features,
|
| 68 |
+
threshold=body.threshold,
|
| 69 |
+
sha256=body.sha256
|
| 70 |
+
)
|
| 71 |
|
| 72 |
# Add SHAP analysis if requested
|
| 73 |
+
if body.include_shap:
|
| 74 |
shap_service = get_shap_service()
|
| 75 |
if not shap_service.initialized:
|
| 76 |
shap_service.initialize(ml_service.model)
|
| 77 |
|
| 78 |
top_features = shap_service.get_feature_importance(
|
| 79 |
+
features=body.features,
|
| 80 |
+
model=ml_service.model,
|
| 81 |
+
top_k=10
|
| 82 |
)
|
| 83 |
prediction.top_features = top_features
|
| 84 |
|
|
|
|
| 115 |
raise HTTPException(status_code=500, detail="Prediction failed")
|
| 116 |
|
| 117 |
|
| 118 |
+
@router.post("/explain", response_model=PredictionWithExplanationResponse)
|
| 119 |
+
@limiter.limit(settings.rate_limit_prediction)
|
| 120 |
async def predict_with_explanation(
|
| 121 |
+
request: Request,
|
| 122 |
+
body: PredictionRequest,
|
| 123 |
_: User = Depends(require_analyst),
|
| 124 |
ml_service: MLService = Depends(get_ml_service),
|
| 125 |
gemini_service: GeminiService = Depends(get_gemini_service)
|
|
|
|
| 135 |
provides explanation and context.
|
| 136 |
"""
|
| 137 |
try:
|
| 138 |
+
# Run prediction
|
| 139 |
+
prediction = ml_service.predict(
|
| 140 |
+
features=body.features,
|
| 141 |
+
threshold=body.threshold,
|
| 142 |
+
sha256=body.sha256
|
| 143 |
+
)
|
| 144 |
|
| 145 |
# Get SHAP features for better explanation
|
| 146 |
shap_service = get_shap_service()
|
|
|
|
| 148 |
shap_service.initialize(ml_service.model)
|
| 149 |
|
| 150 |
top_features = shap_service.get_feature_importance(
|
| 151 |
+
features=body.features,
|
| 152 |
+
model=ml_service.model,
|
| 153 |
+
top_k=10
|
| 154 |
)
|
| 155 |
prediction.top_features = top_features
|
| 156 |
|
|
|
|
| 196 |
|
| 197 |
|
| 198 |
@router.get("/model-info")
|
| 199 |
+
async def get_model_info(
|
| 200 |
ml_service: MLService = Depends(get_ml_service)
|
| 201 |
+
) -> dict:
|
| 202 |
+
"""Get information about the loaded XGBoost model."""
|
| 203 |
+
if settings.is_production:
|
| 204 |
+
return {"loaded": True, "feature_count": settings.ember_feature_count}
|
| 205 |
+
return ml_service.get_model_info()
|
| 206 |
|
| 207 |
|
| 208 |
@router.get("/health")
|
| 209 |
+
async def health_check(
|
| 210 |
ml_service: MLService = Depends(get_ml_service)
|
| 211 |
+
) -> dict:
|
| 212 |
+
"""Health check endpoint for the prediction service."""
|
| 213 |
+
if settings.is_production:
|
| 214 |
+
return {"status": "healthy"}
|
| 215 |
+
return {
|
| 216 |
"status": "healthy",
|
| 217 |
"model_loaded": ml_service.model_loaded,
|
| 218 |
"feature_count": ml_service.feature_count
|
backend/app/routers/upload.py
CHANGED
|
@@ -6,8 +6,8 @@ from fastapi import APIRouter, HTTPException, UploadFile, File, Depends, Request
|
|
| 6 |
from sqlalchemy.orm import Session
|
| 7 |
from pydantic import BaseModel, Field
|
| 8 |
from typing import Optional, List
|
| 9 |
-
import logging
|
| 10 |
-
import hashlib
|
| 11 |
|
| 12 |
|
| 13 |
from ..services.ember_features import extract_features_from_bytes, extract_features_and_lief, LIEF_AVAILABLE
|
|
@@ -24,6 +24,8 @@ from ..dependencies import (
|
|
| 24 |
record_scan_event,
|
| 25 |
require_analyst,
|
| 26 |
)
|
|
|
|
|
|
|
| 27 |
from ..models.prediction import (
|
| 28 |
PredictionResponse,
|
| 29 |
ConfidenceLevel,
|
|
@@ -97,7 +99,8 @@ def summarize_pe_headers(lief_binary) -> Optional[dict]:
|
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
-
@router.post("/analyze", response_model=FileAnalysisResponse)
|
|
|
|
| 101 |
async def analyze_file(
|
| 102 |
request: Request,
|
| 103 |
file: UploadFile = File(..., description="PE file to analyze"),
|
|
@@ -136,8 +139,8 @@ async def analyze_file(
|
|
| 136 |
if len(content) == 0:
|
| 137 |
raise HTTPException(status_code=400, detail="Empty file uploaded")
|
| 138 |
|
| 139 |
-
if len(content) > 50 * 1024 * 1024: # 50MB limit
|
| 140 |
-
raise HTTPException(status_code=400, detail="File too large. Maximum size is 50MB.")
|
| 141 |
|
| 142 |
|
| 143 |
# Check for PE signature (MZ header)
|
|
@@ -192,7 +195,7 @@ async def analyze_file(
|
|
| 192 |
|
| 193 |
# Classify malware type if prediction is malware
|
| 194 |
malware_type_info = None
|
| 195 |
-
if prediction_response.prediction == "
|
| 196 |
try:
|
| 197 |
malware_type_service = get_malware_type_service()
|
| 198 |
if lief_binary:
|
|
@@ -215,7 +218,7 @@ async def analyze_file(
|
|
| 215 |
# Generate explanation if requested
|
| 216 |
explanation = None
|
| 217 |
top_features = None
|
| 218 |
-
if include_explanation:
|
| 219 |
try:
|
| 220 |
# Get SHAP feature importance
|
| 221 |
shap_service = get_shap_service()
|
|
@@ -265,8 +268,10 @@ async def analyze_file(
|
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
-
@router.post("/extract-features", response_model=FeatureExtractionResponse)
|
|
|
|
| 269 |
async def extract_features(
|
|
|
|
| 270 |
file: UploadFile = File(..., description="PE file to extract features from"),
|
| 271 |
_: User = Depends(require_analyst),
|
| 272 |
):
|
|
@@ -330,9 +335,11 @@ async def extract_features(
|
|
| 330 |
|
| 331 |
|
| 332 |
@router.get("/health")
|
| 333 |
-
async def upload_health():
|
| 334 |
-
"""Check if the upload/feature extraction service is healthy."""
|
| 335 |
-
|
|
|
|
|
|
|
| 336 |
"status": "healthy" if LIEF_AVAILABLE else "degraded",
|
| 337 |
"lief_available": LIEF_AVAILABLE,
|
| 338 |
"feature_extraction": "enabled" if LIEF_AVAILABLE else "disabled"
|
|
|
|
| 6 |
from sqlalchemy.orm import Session
|
| 7 |
from pydantic import BaseModel, Field
|
| 8 |
from typing import Optional, List
|
| 9 |
+
import logging
|
| 10 |
+
import hashlib
|
| 11 |
|
| 12 |
|
| 13 |
from ..services.ember_features import extract_features_from_bytes, extract_features_and_lief, LIEF_AVAILABLE
|
|
|
|
| 24 |
record_scan_event,
|
| 25 |
require_analyst,
|
| 26 |
)
|
| 27 |
+
from ..config import settings
|
| 28 |
+
from ..rate_limit import limiter
|
| 29 |
from ..models.prediction import (
|
| 30 |
PredictionResponse,
|
| 31 |
ConfidenceLevel,
|
|
|
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
+
@router.post("/analyze", response_model=FileAnalysisResponse)
|
| 103 |
+
@limiter.limit(settings.rate_limit_upload)
|
| 104 |
async def analyze_file(
|
| 105 |
request: Request,
|
| 106 |
file: UploadFile = File(..., description="PE file to analyze"),
|
|
|
|
| 139 |
if len(content) == 0:
|
| 140 |
raise HTTPException(status_code=400, detail="Empty file uploaded")
|
| 141 |
|
| 142 |
+
if len(content) > 50 * 1024 * 1024: # 50MB limit
|
| 143 |
+
raise HTTPException(status_code=400, detail="File too large. Maximum size is 50MB.")
|
| 144 |
|
| 145 |
|
| 146 |
# Check for PE signature (MZ header)
|
|
|
|
| 195 |
|
| 196 |
# Classify malware type if prediction is malware
|
| 197 |
malware_type_info = None
|
| 198 |
+
if prediction_response.prediction == "Malicious" or prediction_response.probability > 0.3:
|
| 199 |
try:
|
| 200 |
malware_type_service = get_malware_type_service()
|
| 201 |
if lief_binary:
|
|
|
|
| 218 |
# Generate explanation if requested
|
| 219 |
explanation = None
|
| 220 |
top_features = None
|
| 221 |
+
if include_explanation and is_analyst(current_user):
|
| 222 |
try:
|
| 223 |
# Get SHAP feature importance
|
| 224 |
shap_service = get_shap_service()
|
|
|
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
+
@router.post("/extract-features", response_model=FeatureExtractionResponse)
|
| 272 |
+
@limiter.limit(settings.rate_limit_upload)
|
| 273 |
async def extract_features(
|
| 274 |
+
request: Request,
|
| 275 |
file: UploadFile = File(..., description="PE file to extract features from"),
|
| 276 |
_: User = Depends(require_analyst),
|
| 277 |
):
|
|
|
|
| 335 |
|
| 336 |
|
| 337 |
@router.get("/health")
|
| 338 |
+
async def upload_health():
|
| 339 |
+
"""Check if the upload/feature extraction service is healthy."""
|
| 340 |
+
if settings.is_production:
|
| 341 |
+
return {"status": "healthy"}
|
| 342 |
+
return {
|
| 343 |
"status": "healthy" if LIEF_AVAILABLE else "degraded",
|
| 344 |
"lief_available": LIEF_AVAILABLE,
|
| 345 |
"feature_extraction": "enabled" if LIEF_AVAILABLE else "disabled"
|
backend/app/routers/url.py
CHANGED
|
@@ -19,7 +19,8 @@ from ..database import get_db
|
|
| 19 |
from ..db_models import User
|
| 20 |
from ..dependencies import enforce_scan_quota, get_current_user_optional, record_scan_event
|
| 21 |
from ..models.url import URLAnalyzeRequest, URLAnalyzeResponse, URLModelInfoResponse
|
| 22 |
-
from ..
|
|
|
|
| 23 |
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
|
@@ -32,7 +33,8 @@ router = APIRouter(
|
|
| 32 |
)
|
| 33 |
|
| 34 |
|
| 35 |
-
@router.post("/analyze", response_model=URLAnalyzeResponse)
|
|
|
|
| 36 |
async def analyze_url(
|
| 37 |
request: Request,
|
| 38 |
body: URLAnalyzeRequest,
|
|
@@ -84,9 +86,19 @@ async def analyze_url(
|
|
| 84 |
|
| 85 |
|
| 86 |
@router.get("/model-info", response_model=URLModelInfoResponse)
|
| 87 |
-
async def url_model_info():
|
| 88 |
-
"""Get information about the URL detection model."""
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
url_service = get_url_service()
|
| 91 |
return URLModelInfoResponse(**url_service.get_model_info())
|
| 92 |
except Exception as e:
|
|
@@ -94,9 +106,11 @@ async def url_model_info():
|
|
| 94 |
|
| 95 |
|
| 96 |
@router.get("/health")
|
| 97 |
-
async def url_health():
|
| 98 |
-
"""Health check for URL analysis service."""
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
url_service = get_url_service()
|
| 101 |
return {
|
| 102 |
"status": "healthy" if url_service.model_loaded else "unhealthy",
|
|
|
|
| 19 |
from ..db_models import User
|
| 20 |
from ..dependencies import enforce_scan_quota, get_current_user_optional, record_scan_event
|
| 21 |
from ..models.url import URLAnalyzeRequest, URLAnalyzeResponse, URLModelInfoResponse
|
| 22 |
+
from ..rate_limit import limiter
|
| 23 |
+
from ..services.url_service import get_url_service
|
| 24 |
|
| 25 |
logger = logging.getLogger(__name__)
|
| 26 |
|
|
|
|
| 33 |
)
|
| 34 |
|
| 35 |
|
| 36 |
+
@router.post("/analyze", response_model=URLAnalyzeResponse)
|
| 37 |
+
@limiter.limit(settings.rate_limit_url)
|
| 38 |
async def analyze_url(
|
| 39 |
request: Request,
|
| 40 |
body: URLAnalyzeRequest,
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
@router.get("/model-info", response_model=URLModelInfoResponse)
|
| 89 |
+
async def url_model_info():
|
| 90 |
+
"""Get information about the URL detection model."""
|
| 91 |
+
if settings.is_production:
|
| 92 |
+
return {
|
| 93 |
+
"model_type": "Stacking HyperModel",
|
| 94 |
+
"base_models": [],
|
| 95 |
+
"meta_learner": "hidden",
|
| 96 |
+
"scaler_features": 0,
|
| 97 |
+
"meta_features": 0,
|
| 98 |
+
"dl_available": False,
|
| 99 |
+
"feature_categories": [],
|
| 100 |
+
}
|
| 101 |
+
try:
|
| 102 |
url_service = get_url_service()
|
| 103 |
return URLModelInfoResponse(**url_service.get_model_info())
|
| 104 |
except Exception as e:
|
|
|
|
| 106 |
|
| 107 |
|
| 108 |
@router.get("/health")
|
| 109 |
+
async def url_health():
|
| 110 |
+
"""Health check for URL analysis service."""
|
| 111 |
+
if settings.is_production:
|
| 112 |
+
return {"status": "healthy"}
|
| 113 |
+
try:
|
| 114 |
url_service = get_url_service()
|
| 115 |
return {
|
| 116 |
"status": "healthy" if url_service.model_loaded else "unhealthy",
|
backend/app/routers/virustotal.py
CHANGED
|
@@ -3,8 +3,8 @@ VirusTotal API Router.
|
|
| 3 |
Handles hash lookup and comparison endpoints.
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
import logging
|
| 7 |
-
from fastapi import APIRouter, HTTPException, Depends, Path
|
| 8 |
from pydantic import BaseModel, Field
|
| 9 |
from typing import List
|
| 10 |
|
|
@@ -18,7 +18,9 @@ from ..services.virustotal_service import get_virustotal_service, VirusTotalServ
|
|
| 18 |
from ..services.ml_service import get_ml_service, MLService
|
| 19 |
from ..services.feedback_service import get_feedback_service
|
| 20 |
from ..db_models import User
|
|
|
|
| 21 |
from ..dependencies import require_analyst
|
|
|
|
| 22 |
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
|
@@ -30,6 +32,8 @@ async def health_check(
|
|
| 30 |
vt_service: VirusTotalService = Depends(get_virustotal_service)
|
| 31 |
) -> dict:
|
| 32 |
"""Health check endpoint for VirusTotal service."""
|
|
|
|
|
|
|
| 33 |
return {
|
| 34 |
"status": "healthy",
|
| 35 |
"api_configured": vt_service.initialized
|
|
@@ -37,8 +41,10 @@ async def health_check(
|
|
| 37 |
|
| 38 |
|
| 39 |
@router.get("/{hash}", response_model=VirusTotalResponse)
|
|
|
|
| 40 |
async def lookup_hash(
|
| 41 |
-
|
|
|
|
| 42 |
...,
|
| 43 |
description="SHA256, SHA1, or MD5 hash to look up",
|
| 44 |
min_length=32,
|
|
@@ -78,9 +84,11 @@ async def lookup_hash(
|
|
| 78 |
return result
|
| 79 |
|
| 80 |
|
| 81 |
-
@router.post("/compare", response_model=ComparisonResult)
|
|
|
|
| 82 |
async def compare_predictions(
|
| 83 |
-
request:
|
|
|
|
| 84 |
_: User = Depends(require_analyst),
|
| 85 |
ml_service: MLService = Depends(get_ml_service),
|
| 86 |
vt_service: VirusTotalService = Depends(get_virustotal_service)
|
|
@@ -95,14 +103,14 @@ async def compare_predictions(
|
|
| 95 |
agree on whether the sample is malicious or benign.
|
| 96 |
"""
|
| 97 |
try:
|
| 98 |
-
# Run XGBoost prediction
|
| 99 |
-
prediction = ml_service.predict(
|
| 100 |
-
features=
|
| 101 |
-
sha256=
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
# Query VirusTotal
|
| 105 |
-
vt_result = await vt_service.lookup_hash(
|
| 106 |
|
| 107 |
if not vt_result.found:
|
| 108 |
raise HTTPException(
|
|
@@ -136,8 +144,8 @@ async def compare_predictions(
|
|
| 136 |
try:
|
| 137 |
feedback_svc = get_feedback_service()
|
| 138 |
rl_result = feedback_svc.log_malware_feedback(
|
| 139 |
-
features=
|
| 140 |
-
sha256=
|
| 141 |
predicted=prediction.prediction.value,
|
| 142 |
probability=prediction.probability,
|
| 143 |
vt_mal=vt_result.malicious_count or 0,
|
|
|
|
| 3 |
Handles hash lookup and comparison endpoints.
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
import logging
|
| 7 |
+
from fastapi import APIRouter, HTTPException, Depends, Path, Request
|
| 8 |
from pydantic import BaseModel, Field
|
| 9 |
from typing import List
|
| 10 |
|
|
|
|
| 18 |
from ..services.ml_service import get_ml_service, MLService
|
| 19 |
from ..services.feedback_service import get_feedback_service
|
| 20 |
from ..db_models import User
|
| 21 |
+
from ..config import settings
|
| 22 |
from ..dependencies import require_analyst
|
| 23 |
+
from ..rate_limit import limiter
|
| 24 |
|
| 25 |
logger = logging.getLogger(__name__)
|
| 26 |
|
|
|
|
| 32 |
vt_service: VirusTotalService = Depends(get_virustotal_service)
|
| 33 |
) -> dict:
|
| 34 |
"""Health check endpoint for VirusTotal service."""
|
| 35 |
+
if settings.is_production:
|
| 36 |
+
return {"status": "healthy"}
|
| 37 |
return {
|
| 38 |
"status": "healthy",
|
| 39 |
"api_configured": vt_service.initialized
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
@router.get("/{hash}", response_model=VirusTotalResponse)
|
| 44 |
+
@limiter.limit(settings.rate_limit_virustotal)
|
| 45 |
async def lookup_hash(
|
| 46 |
+
request: Request,
|
| 47 |
+
hash: str = Path(
|
| 48 |
...,
|
| 49 |
description="SHA256, SHA1, or MD5 hash to look up",
|
| 50 |
min_length=32,
|
|
|
|
| 84 |
return result
|
| 85 |
|
| 86 |
|
| 87 |
+
@router.post("/compare", response_model=ComparisonResult)
|
| 88 |
+
@limiter.limit(settings.rate_limit_virustotal)
|
| 89 |
async def compare_predictions(
|
| 90 |
+
request: Request,
|
| 91 |
+
body: CompareRequest,
|
| 92 |
_: User = Depends(require_analyst),
|
| 93 |
ml_service: MLService = Depends(get_ml_service),
|
| 94 |
vt_service: VirusTotalService = Depends(get_virustotal_service)
|
|
|
|
| 103 |
agree on whether the sample is malicious or benign.
|
| 104 |
"""
|
| 105 |
try:
|
| 106 |
+
# Run XGBoost prediction
|
| 107 |
+
prediction = ml_service.predict(
|
| 108 |
+
features=body.features,
|
| 109 |
+
sha256=body.sha256
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Query VirusTotal
|
| 113 |
+
vt_result = await vt_service.lookup_hash(body.sha256)
|
| 114 |
|
| 115 |
if not vt_result.found:
|
| 116 |
raise HTTPException(
|
|
|
|
| 144 |
try:
|
| 145 |
feedback_svc = get_feedback_service()
|
| 146 |
rl_result = feedback_svc.log_malware_feedback(
|
| 147 |
+
features=body.features,
|
| 148 |
+
sha256=body.sha256,
|
| 149 |
predicted=prediction.prediction.value,
|
| 150 |
probability=prediction.probability,
|
| 151 |
vt_mal=vt_result.malicious_count or 0,
|
backend/malwareguard.db
ADDED
|
Binary file (65.5 kB). View file
|
|
|
backend/tests/conftest.py
CHANGED
|
@@ -5,6 +5,7 @@ from types import SimpleNamespace
|
|
| 5 |
import pytest
|
| 6 |
from fastapi.testclient import TestClient
|
| 7 |
|
|
|
|
| 8 |
from app.main import app
|
| 9 |
from app.models.prediction import ConfidenceLevel, PredictionLabel, PredictionResponse
|
| 10 |
from app.models.virustotal import VirusTotalResponse
|
|
@@ -230,4 +231,5 @@ def services(monkeypatch):
|
|
| 230 |
|
| 231 |
@pytest.fixture
|
| 232 |
def client(services):
|
|
|
|
| 233 |
return TestClient(app)
|
|
|
|
| 5 |
import pytest
|
| 6 |
from fastapi.testclient import TestClient
|
| 7 |
|
| 8 |
+
from app.database import Base, engine
|
| 9 |
from app.main import app
|
| 10 |
from app.models.prediction import ConfidenceLevel, PredictionLabel, PredictionResponse
|
| 11 |
from app.models.virustotal import VirusTotalResponse
|
|
|
|
| 231 |
|
| 232 |
@pytest.fixture
|
| 233 |
def client(services):
|
| 234 |
+
Base.metadata.create_all(bind=engine)
|
| 235 |
return TestClient(app)
|
backend/tests/test_security_hardening.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
from fastapi.testclient import TestClient
|
| 5 |
+
from sqlalchemy import create_engine
|
| 6 |
+
from sqlalchemy.orm import sessionmaker
|
| 7 |
+
|
| 8 |
+
from app import db_models # noqa: F401
|
| 9 |
+
from app.config import DEFAULT_JWT_SECRET, settings
|
| 10 |
+
from app.database import Base, get_db
|
| 11 |
+
from app.db_models import User
|
| 12 |
+
from app.main import app
|
| 13 |
+
from app.security import create_access_token, hash_password
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@pytest.fixture
|
| 17 |
+
def isolated_client(tmp_path):
|
| 18 |
+
app.dependency_overrides.clear()
|
| 19 |
+
db_path = tmp_path / "security.db"
|
| 20 |
+
engine = create_engine(f"sqlite:///{db_path}", connect_args={"check_same_thread": False})
|
| 21 |
+
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 22 |
+
Base.metadata.create_all(bind=engine)
|
| 23 |
+
|
| 24 |
+
def override_get_db():
|
| 25 |
+
db = TestingSessionLocal()
|
| 26 |
+
try:
|
| 27 |
+
yield db
|
| 28 |
+
finally:
|
| 29 |
+
db.close()
|
| 30 |
+
|
| 31 |
+
app.dependency_overrides[get_db] = override_get_db
|
| 32 |
+
try:
|
| 33 |
+
yield TestClient(app), TestingSessionLocal
|
| 34 |
+
finally:
|
| 35 |
+
app.dependency_overrides.clear()
|
| 36 |
+
Base.metadata.drop_all(bind=engine)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_production_rejects_default_jwt_secret(monkeypatch):
|
| 40 |
+
monkeypatch.setattr(settings, "debug", False)
|
| 41 |
+
monkeypatch.setattr(settings, "environment", "production")
|
| 42 |
+
monkeypatch.setattr(settings, "jwt_secret_key", DEFAULT_JWT_SECRET)
|
| 43 |
+
|
| 44 |
+
with pytest.raises(RuntimeError, match="JWT_SECRET_KEY"):
|
| 45 |
+
settings.validate_security()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_unknown_cors_origin_is_rejected():
|
| 49 |
+
client = TestClient(app)
|
| 50 |
+
response = client.options(
|
| 51 |
+
"/api/auth/login",
|
| 52 |
+
headers={
|
| 53 |
+
"Origin": "https://evil.example",
|
| 54 |
+
"Access-Control-Request-Method": "POST",
|
| 55 |
+
"Access-Control-Request-Headers": "content-type",
|
| 56 |
+
},
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
assert response.status_code in {400, 405}
|
| 60 |
+
assert response.headers.get("access-control-allow-origin") != "https://evil.example"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_signup_never_promotes_admin_email(monkeypatch, isolated_client):
|
| 64 |
+
client, SessionLocal = isolated_client
|
| 65 |
+
monkeypatch.setattr(settings, "admin_emails", "owner@example.com")
|
| 66 |
+
|
| 67 |
+
response = client.post(
|
| 68 |
+
"/api/auth/signup",
|
| 69 |
+
json={
|
| 70 |
+
"email": "owner@example.com",
|
| 71 |
+
"password": "safe-password-123",
|
| 72 |
+
"display_name": "Owner",
|
| 73 |
+
},
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
assert response.status_code == 201
|
| 77 |
+
body = response.json()
|
| 78 |
+
assert body["user"]["role"] == "user"
|
| 79 |
+
assert body["user"]["tier"] == "free"
|
| 80 |
+
|
| 81 |
+
db = SessionLocal()
|
| 82 |
+
try:
|
| 83 |
+
user = db.query(User).filter(User.email == "owner@example.com").one()
|
| 84 |
+
assert user.role == "user"
|
| 85 |
+
assert user.tier == "free"
|
| 86 |
+
finally:
|
| 87 |
+
db.close()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_normal_user_cannot_access_admin_or_analyst_routes(isolated_client):
|
| 91 |
+
client, SessionLocal = isolated_client
|
| 92 |
+
db = SessionLocal()
|
| 93 |
+
try:
|
| 94 |
+
user = User(
|
| 95 |
+
email="user@example.com",
|
| 96 |
+
password_hash=hash_password("safe-password-123"),
|
| 97 |
+
role="user",
|
| 98 |
+
tier="free",
|
| 99 |
+
is_active=True,
|
| 100 |
+
)
|
| 101 |
+
db.add(user)
|
| 102 |
+
db.commit()
|
| 103 |
+
db.refresh(user)
|
| 104 |
+
token = create_access_token(str(user.id), {"role": user.role, "tier": user.tier})
|
| 105 |
+
finally:
|
| 106 |
+
db.close()
|
| 107 |
+
|
| 108 |
+
client.cookies.set("malwareguard_session", token)
|
| 109 |
+
assert client.get("/api/admin/overview").status_code == 403
|
| 110 |
+
assert client.post("/api/predict", json={"features": [0.0] * 2381}).status_code == 403
|
| 111 |
+
assert client.get("/api/feedback/stats").status_code == 403
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_url_feedback_requires_login(isolated_client):
|
| 115 |
+
client, _ = isolated_client
|
| 116 |
+
response = client.post(
|
| 117 |
+
"/api/feedback/url",
|
| 118 |
+
json={
|
| 119 |
+
"url": "https://example.com",
|
| 120 |
+
"predicted_label": "Benign",
|
| 121 |
+
"malicious_score": 0.01,
|
| 122 |
+
"is_correct": True,
|
| 123 |
+
"base_model_scores": {},
|
| 124 |
+
},
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
assert response.status_code == 401
|
backend/tests/test_upload.py
CHANGED
|
@@ -42,5 +42,6 @@ def test_upload_analyze_happy_path_with_mocked_lief(client, monkeypatch):
|
|
| 42 |
body = response.json()
|
| 43 |
assert body["features_extracted"] is True
|
| 44 |
assert body["feature_count"] == 2381
|
| 45 |
-
assert
|
|
|
|
| 46 |
assert body["prediction"]["prediction"] == "Malicious"
|
|
|
|
| 42 |
body = response.json()
|
| 43 |
assert body["features_extracted"] is True
|
| 44 |
assert body["feature_count"] == 2381
|
| 45 |
+
assert body["features"] is None
|
| 46 |
+
assert body["pe_headers"] is None
|
| 47 |
assert body["prediction"]["prediction"] == "Malicious"
|