Spaces:
Sleeping
Sleeping
File size: 6,119 Bytes
fbb917f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | 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"},
)
|