ai_data_scientist / shared /security_config.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
7.1 kB
"""
Security configuration for the MCP AI Data Scientist system.
"""
import os
from typing import Dict, List, Optional
from dataclasses import dataclass
from pathlib import Path
@dataclass
class SecurityConfig:
"""Security configuration settings."""
# File upload security
max_file_size_mb: int = 100
allowed_file_types: List[str] = None
scan_uploads: bool = True
quarantine_threats: bool = True
# Rate limiting
requests_per_minute: int = 60
requests_per_hour: int = 1000
requests_per_day: int = 10000
# Authentication
jwt_secret_key: str = ""
jwt_algorithm: str = "HS256"
jwt_expiration_hours: int = 24
# Audit logging
audit_log_enabled: bool = True
audit_log_path: str = "logs/security_audit.log"
audit_log_level: str = "INFO"
# SQL injection prevention
enable_sql_validation: bool = True
max_input_length: int = 10000
# CSRF protection
csrf_enabled: bool = True
csrf_secret_key: str = ""
# Security headers
enable_security_headers: bool = True
hsts_max_age: int = 31536000 # 1 year
# File storage
secure_storage_path: str = "uploads"
file_permissions: int = 0o600
directory_permissions: int = 0o700
def __post_init__(self):
"""Initialize default values and validate configuration."""
if self.allowed_file_types is None:
self.allowed_file_types = [
'text/csv',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/json',
'text/plain',
'application/x-parquet'
]
# Load from environment variables if available
self.jwt_secret_key = os.getenv('JWT_SECRET_KEY', self.jwt_secret_key)
self.csrf_secret_key = os.getenv('CSRF_SECRET_KEY', self.csrf_secret_key)
# Validate required settings
if not self.jwt_secret_key:
raise ValueError("JWT_SECRET_KEY must be set")
if not self.csrf_secret_key:
raise ValueError("CSRF_SECRET_KEY must be set")
# Ensure log directory exists
log_path = Path(self.audit_log_path)
log_path.parent.mkdir(parents=True, exist_ok=True)
# Ensure storage directory exists
storage_path = Path(self.secure_storage_path)
storage_path.mkdir(parents=True, exist_ok=True)
# Global security configuration
security_config = SecurityConfig()
# Security patterns for threat detection
SECURITY_PATTERNS = {
'sql_injection': [
r"(\b(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC|UNION)\b)",
r"(--|#|/\*|\*/)",
r"(\b(OR|AND)\s+\d+\s*=\s*\d+)",
r"(\b(OR|AND)\s+['\"]?\w+['\"]?\s*=\s*['\"]?\w+['\"]?)",
r"(;\s*(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC))",
r"(\bUNION\s+(ALL\s+)?SELECT)",
r"(\b(INFORMATION_SCHEMA|SYSOBJECTS|SYSCOLUMNS)\b)",
r"(xp_cmdshell|sp_executesql)",
r"(\b(CAST|CONVERT|CHAR|ASCII)\s*\()",
],
'xss': [
r"<script[^>]*>",
r"javascript:",
r"vbscript:",
r"data:text/html",
r"on\w+\s*=",
r"<iframe[^>]*>",
r"<object[^>]*>",
r"<embed[^>]*>",
],
'command_injection': [
r";\s*(rm|del|format|shutdown)",
r"\|\s*(cat|type|more|less)",
r"&&\s*(whoami|id|pwd)",
r"`[^`]*`",
r"\$\([^)]*\)",
r">\s*/dev/null",
r"2>&1",
],
'path_traversal': [
r"\.\./",
r"\.\.\\",
r"%2e%2e%2f",
r"%2e%2e%5c",
r"..%252f",
r"..%c0%af",
]
}
# File type validation
DANGEROUS_FILE_EXTENSIONS = {
'.exe', '.bat', '.cmd', '.com', '.pif', '.scr', '.vbs', '.js',
'.jar', '.app', '.deb', '.pkg', '.dmg', '.sh', '.ps1', '.msi',
'.dll', '.sys', '.bin', '.run', '.deb', '.rpm'
}
# MIME type validation
ALLOWED_MIME_TYPES = {
'text/csv',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/json',
'text/plain',
'application/x-parquet',
'application/octet-stream' # For parquet files
}
# Security event severity levels
class SecuritySeverity:
LOW = "LOW"
MEDIUM = "MEDIUM"
HIGH = "HIGH"
CRITICAL = "CRITICAL"
# Security event types
class SecurityEventType:
FILE_UPLOAD = "file_upload"
AUTHENTICATION = "authentication"
AUTHORIZATION = "authorization"
SQL_INJECTION_ATTEMPT = "sql_injection_attempt"
XSS_ATTEMPT = "xss_attempt"
RATE_LIMIT_VIOLATION = "rate_limit_violation"
SUSPICIOUS_ACTIVITY = "suspicious_activity"
DATA_ACCESS = "data_access"
SYSTEM_ERROR = "system_error"
def get_security_headers() -> Dict[str, str]:
"""Get security headers for HTTP responses."""
return {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Strict-Transport-Security': f'max-age={security_config.hsts_max_age}; includeSubDomains',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), microphone=(), camera=()',
'Content-Security-Policy': (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data: https:; "
"font-src 'self'; "
"connect-src 'self'; "
"frame-ancestors 'none';"
)
}
def validate_security_config() -> List[str]:
"""Validate security configuration and return any issues."""
issues = []
# Check required environment variables
required_env_vars = ['JWT_SECRET_KEY', 'CSRF_SECRET_KEY']
for var in required_env_vars:
if not os.getenv(var):
issues.append(f"Missing required environment variable: {var}")
# Check file permissions
try:
storage_path = Path(security_config.secure_storage_path)
if storage_path.exists():
stat_info = storage_path.stat()
if stat_info.st_mode & 0o777 != security_config.directory_permissions:
issues.append(f"Insecure directory permissions on {storage_path}")
except Exception as e:
issues.append(f"Cannot check directory permissions: {e}")
# Check log file permissions
try:
log_path = Path(security_config.audit_log_path)
if log_path.exists():
stat_info = log_path.stat()
if stat_info.st_mode & 0o777 > 0o644:
issues.append(f"Insecure log file permissions on {log_path}")
except Exception as e:
issues.append(f"Cannot check log file permissions: {e}")
return issues