import uuid import time import asyncio import logging from datetime import datetime from typing import Any, List, Dict from fastapi import Request, Response from fastapi.responses import JSONResponse from auth.database import SessionLocal from auth.models import User, AuditLog from auth.service import decode_token logger = logging.getLogger("befree.middleware") def _derive_action_label(method: str, path: str) -> str: """Map HTTP method + path to a human-readable action label.""" m = method.upper() p = path.lower() if m == "POST" and p.endswith("/upload") and "statements" in p: return "upload_statement" if m == "POST" and "/process" in p and "statements" in p: return "start_processing" if m == "PATCH" and "/transactions/" in p: return "update_transaction" if m == "DELETE" and "/transactions/" in p: return "delete_transaction" if m == "POST" and p.endswith("/finalise"): return "finalise_statement" if m == "POST" and p.endswith("/export"): return "export_statement" if m == "POST" and p.endswith("/classify") and "statements" in p: return "classify_statement" if m == "PATCH" and "/classify/" in p: return "override_classification" if m == "DELETE" and "/classify/" in p and "/override" in p: return "reset_classification" if m == "POST" and p.endswith("/re-audit"): return "re_audit_page" if m == "POST" and "/review" in p: return "review_page" if m == "POST" and "classify/upload-excel" in p: return "upload_excel_classification" if m == "POST" and p.endswith("/auth/login"): return "login_attempt" if m == "POST" and p.endswith("/auth/logout"): return "logout" parts = [seg for seg in path.split("/") if seg and not seg.startswith("{")] last = parts[-1] if parts else "unknown" return f"view_{last}" def _extract_resource(path: str): """Parse path and return (resource_type, resource_id | None).""" parts = [p for p in path.split("/") if p] try: if "statements" in parts: si = parts.index("statements") stmt_id = parts[si + 1] if si + 1 < len(parts) else None if "transactions" in parts: ti = parts.index("transactions") tx_id = parts[ti + 1] if ti + 1 < len(parts) else None return ("transaction", tx_id) if "classify" in parts: ci = parts.index("classify") if ci + 1 < len(parts) and parts[ci + 1] not in ("status", "upload-excel"): return ("transaction", parts[ci + 1]) return ("statement", stmt_id) return ("statement", stmt_id) if "auth" in parts: return ("session", None) if "classify" in parts: return ("classification", None) except Exception: pass return ("api", None) async def _write_audit_log( user_id, username, action, resource_type, resource_id, http_method, endpoint, response_status, ip_address, user_agent, duration_ms ): """Write an audit log row asynchronously. Never raises — DB failures are silently swallowed.""" try: with SessionLocal() as db: log = AuditLog( user_id=user_id, username=username, action=action, resource_type=resource_type, resource_id=resource_id, http_method=http_method, endpoint=endpoint, response_status=response_status, ip_address=ip_address, user_agent=user_agent, duration_ms=duration_ms, occurred_at=datetime.utcnow(), ) db.add(log) db.commit() except Exception as exc: logger.debug(f"Audit log write failed (non-critical): {exc}") async def add_request_id_handler(request: Request, call_next): request_id = str(uuid.uuid4())[:8] request.state.request_id = request_id response = await call_next(request) response.headers["X-Request-ID"] = request_id return response async def audit_logging_handler(request: Request, call_next): start_time = time.time() response = await call_next(request) duration_ms = int((time.time() - start_time) * 1000) path = request.url.path method = request.method if not path.startswith("/api/v1/"): return response if path.endswith("/processing") or path == "/api/v1/auth/me": return response user_id, username = None, "anonymous" try: auth_header = request.headers.get("Authorization", "") if auth_header.startswith("Bearer "): token = auth_header.split(" ", 1)[1] payload = decode_token(token) uname = payload.get("sub") if uname: with SessionLocal() as db: user = db.query(User).filter(User.username == uname).first() if user: user_id = user.id username = user.username except Exception: pass action = _derive_action_label(method, path) resource_type, resource_id = _extract_resource(path) asyncio.create_task(_write_audit_log( user_id=user_id, username=username, action=action, resource_type=resource_type, resource_id=str(resource_id) if resource_id else None, http_method=method, endpoint=path, response_status=response.status_code, ip_address=request.client.host if request.client else None, user_agent=request.headers.get("user-agent"), duration_ms=duration_ms, )) return response async def global_exception_handler_fn(request: Request, exc: Exception): req_id = getattr(getattr(request, "state", None), "request_id", "unknown") logger.error(f"[{req_id}] Unhandled error: {exc}", exc_info=True) return JSONResponse( status_code=500, content={"detail": "Internal Server Error"}, )