forked from hesabix/arc
82 lines
2.6 KiB
Python
Executable file
82 lines
2.6 KiB
Python
Executable file
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import time
|
|
from typing import Awaitable, Callable
|
|
|
|
from fastapi import Request
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.core.rate_limiter import get_client_ip, get_rate_limiter
|
|
from app.services import firewall_service as fw
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def internal_firewall_middleware(request: Request, call_next: Callable[[Request], Awaitable]):
|
|
if fw.is_firewall_globally_disabled():
|
|
return await call_next(request)
|
|
path = request.url.path
|
|
if fw.should_skip_firewall_path(path):
|
|
return await call_next(request)
|
|
|
|
if fw.should_refresh_rules_cache():
|
|
try:
|
|
await asyncio.to_thread(fw.refresh_rules_cache_sync)
|
|
except Exception as e:
|
|
logger.warning("firewall: cache refresh failed: %s", e)
|
|
|
|
if fw.should_refresh_rate_policies_cache():
|
|
try:
|
|
await asyncio.to_thread(fw.refresh_rate_policies_cache_sync)
|
|
except Exception as e:
|
|
logger.warning("firewall: rate policy cache refresh failed: %s", e)
|
|
|
|
client_ip = get_client_ip(request)
|
|
method = request.method
|
|
decision, rule_id = fw.evaluate_request(client_ip, path, method)
|
|
|
|
if decision == "deny":
|
|
ua = request.headers.get("user-agent")
|
|
try:
|
|
await asyncio.to_thread(fw.log_blocked_request_sync, client_ip, path, method, ua, rule_id)
|
|
except Exception as e:
|
|
logger.warning("firewall: async log failed: %s", e)
|
|
return JSONResponse(
|
|
status_code=403,
|
|
content={
|
|
"success": False,
|
|
"error_code": "IP_BLOCKED_BY_FIREWALL",
|
|
"message": "دسترسی شما توسط فایروال سیستم محدود شده است.",
|
|
},
|
|
)
|
|
|
|
policy = fw.find_applicable_rate_policy(path, method)
|
|
if policy is not None:
|
|
limiter = get_rate_limiter()
|
|
rate_key = f"fw_rate:policy{policy['id']}:ip:{client_ip}"
|
|
allowed, _remaining, reset_after = limiter.check_rate_limit(
|
|
rate_key,
|
|
policy["max_requests"],
|
|
policy["window_seconds"],
|
|
)
|
|
if not allowed:
|
|
return JSONResponse(
|
|
status_code=429,
|
|
content={
|
|
"success": False,
|
|
"error_code": "RATE_LIMIT_EXCEEDED",
|
|
"message": "تعداد درخواستهای شما برای این مسیر بیش از حد مجاز است. لطفاً کمی صبر کنید.",
|
|
"detail": {"source": "firewall_rate_policy", "firewall_rate_policy_id": policy["id"]},
|
|
},
|
|
headers={
|
|
"Retry-After": str(reset_after),
|
|
"X-RateLimit-Limit": str(policy["max_requests"]),
|
|
"X-RateLimit-Remaining": "0",
|
|
"X-RateLimit-Reset": str(int(time.time()) + reset_after),
|
|
"X-RateLimit-Policy": f"id={policy['id']}",
|
|
},
|
|
)
|
|
|
|
return await call_next(request)
|