""" Secure API endpoints with integrated security measures. """ from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Request from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from typing import Dict, List, Optional import asyncio from datetime import datetime from .security import ( file_validator, secure_storage, audit_logger, SecurityEvent, FileValidationResult ) from .auth import get_current_user from .models import User router = APIRouter() security = HTTPBearer() async def get_client_ip(request: Request) -> str: """Extract client IP from request.""" forwarded_for = request.headers.get('X-Forwarded-For') if forwarded_for: return forwarded_for.split(',')[0].strip() real_ip = request.headers.get('X-Real-IP') if real_ip: return real_ip return request.client.host if request.client else 'unknown' @router.post("/secure-upload") async def secure_file_upload( request: Request, file: UploadFile = File(...), credentials: HTTPAuthorizationCredentials = Depends(security) ) -> Dict: """ Secure file upload endpoint with comprehensive validation. """ # Get current user user = await get_current_user(credentials.credentials) if not user: raise HTTPException(status_code=401, detail="Invalid authentication") client_ip = await get_client_ip(request) try: # Read file content file_content = await file.read() # Validate file security validation_result = await file_validator.validate_file( file_content, file.filename, user.id ) # Log upload attempt audit_logger.log_file_upload_event( user.id, client_ip, file.filename, validation_result ) # Check if file passed validation if not validation_result.is_valid: raise HTTPException( status_code=400, detail={ "error": "File validation failed", "threats": validation_result.threats_detected, "warnings": validation_result.warnings } ) # Store file securely stored_path = secure_storage.store_file( user.id, file.filename, file_content ) # Log successful upload audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='file_upload_success', user_id=user.id, ip_address=client_ip, severity='LOW', details={ 'filename': file.filename, 'stored_path': stored_path, 'file_size': validation_result.size_bytes, 'file_type': validation_result.file_type, 'file_hash': validation_result.hash_sha256 } )) return { "success": True, "file_id": stored_path, "filename": file.filename, "size": validation_result.size_bytes, "type": validation_result.file_type, "hash": validation_result.hash_sha256, "warnings": validation_result.warnings } except HTTPException: raise except Exception as e: # Log upload error audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='file_upload_error', user_id=user.id, ip_address=client_ip, severity='HIGH', details={ 'filename': file.filename, 'error': str(e) } )) raise HTTPException( status_code=500, detail=f"File upload failed: {str(e)}" ) @router.get("/secure-download/{file_id}") async def secure_file_download( file_id: str, request: Request, credentials: HTTPAuthorizationCredentials = Depends(security) ): """ Secure file download with access control validation. """ # Get current user user = await get_current_user(credentials.credentials) if not user: raise HTTPException(status_code=401, detail="Invalid authentication") client_ip = await get_client_ip(request) try: # Retrieve file with access control file_content = secure_storage.get_file(user.id, file_id) # Log download audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='file_download', user_id=user.id, ip_address=client_ip, severity='LOW', details={ 'file_id': file_id, 'file_size': len(file_content) } )) return { "success": True, "content": file_content.hex(), # Return as hex for JSON compatibility "size": len(file_content) } except PermissionError: audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='unauthorized_file_access', user_id=user.id, ip_address=client_ip, severity='HIGH', details={'file_id': file_id} )) raise HTTPException( status_code=403, detail="Access denied to requested file" ) except FileNotFoundError: raise HTTPException( status_code=404, detail="File not found" ) except Exception as e: audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='file_download_error', user_id=user.id, ip_address=client_ip, severity='MEDIUM', details={ 'file_id': file_id, 'error': str(e) } )) raise HTTPException( status_code=500, detail=f"File download failed: {str(e)}" ) @router.delete("/secure-delete/{file_id}") async def secure_file_delete( file_id: str, request: Request, credentials: HTTPAuthorizationCredentials = Depends(security) ) -> Dict: """ Secure file deletion with access control validation. """ # Get current user user = await get_current_user(credentials.credentials) if not user: raise HTTPException(status_code=401, detail="Invalid authentication") client_ip = await get_client_ip(request) try: # Delete file with access control deleted = secure_storage.delete_file(user.id, file_id) if deleted: # Log successful deletion audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='file_deletion', user_id=user.id, ip_address=client_ip, severity='LOW', details={'file_id': file_id} )) return {"success": True, "message": "File deleted successfully"} else: raise HTTPException(status_code=404, detail="File not found") except PermissionError: audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='unauthorized_file_deletion', user_id=user.id, ip_address=client_ip, severity='HIGH', details={'file_id': file_id} )) raise HTTPException( status_code=403, detail="Access denied to requested file" ) except Exception as e: audit_logger.log_event(SecurityEvent( timestamp=datetime.utcnow(), event_type='file_deletion_error', user_id=user.id, ip_address=client_ip, severity='MEDIUM', details={ 'file_id': file_id, 'error': str(e) } )) raise HTTPException( status_code=500, detail=f"File deletion failed: {str(e)}" ) @router.get("/security-status") async def get_security_status( request: Request, credentials: HTTPAuthorizationCredentials = Depends(security) ) -> Dict: """ Get security status and recent events for the current user. """ # Get current user user = await get_current_user(credentials.credentials) if not user: raise HTTPException(status_code=401, detail="Invalid authentication") client_ip = await get_client_ip(request) # This would typically read from the audit log # For now, return basic security status return { "user_id": user.id, "ip_address": client_ip, "security_level": "HIGH", "last_login": datetime.utcnow().isoformat(), "active_sessions": 1, "recent_uploads": 0, # Would be calculated from audit log "security_alerts": 0 # Would be calculated from audit log } @router.post("/validate-input") async def validate_user_input( request: Request, data: Dict, credentials: HTTPAuthorizationCredentials = Depends(security) ) -> Dict: """ Validate user input for security threats. """ from .security import sql_prevention # Get current user user = await get_current_user(credentials.credentials) if not user: raise HTTPException(status_code=401, detail="Invalid authentication") client_ip = await get_client_ip(request) validation_results = {} overall_safe = True # Validate each field in the input data for field_name, field_value in data.items(): if isinstance(field_value, str): is_safe, threats = sql_prevention.validate_input(field_value, field_name) validation_results[field_name] = { 'is_safe': is_safe, 'threats': threats } if not is_safe: overall_safe = False # Log security threat audit_logger.log_sql_injection_attempt( user.id, client_ip, field_name, threats ) return { 'overall_safe': overall_safe, 'field_results': validation_results, 'timestamp': datetime.utcnow().isoformat() }