From 19f646c31808efef91f700532b229d2af68b9b7a Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Wed, 26 Nov 2025 16:58:54 +0800 Subject: [PATCH] Email captcha rate limiting fix && CORS tightening via configuration --- .../admin_service/services/auth_service.py | 37 +++++++++++++------ services/api_service/controllers/mcp.py | 4 +- services/api_service/main.py | 8 ++-- .../api_service/services/mcp_tool_service.py | 6 +-- services/common/config.py | 1 + services/common/utils/http_utils.py | 9 +++++ 6 files changed, 44 insertions(+), 21 deletions(-) diff --git a/services/admin_service/services/auth_service.py b/services/admin_service/services/auth_service.py index 8464700..b37503c 100644 --- a/services/admin_service/services/auth_service.py +++ b/services/admin_service/services/auth_service.py @@ -33,21 +33,36 @@ class AuthService: def send_email_login_captcha(self, email: str) -> bool: """ - Sends a login captcha code to the specified email address. - The function generates a random 6-digit captcha code, stores it in Redis cache for 10 minutes, - and sends the code to the user's email using HTML template. - Args: - email (str): The recipient's email address. - Returns: - bool: True if email was sent successfully, otherwise False. + Sends a login captcha code to the specified email address with simple rate limiting. + Limit: 5 sends per 10 minutes per email. """ + # Rate limit + try: + from services.common.redis import redis_client + rate_key = f"email_login_rate:{email}" + current = redis_client.get(rate_key) + if current is None: + redis_client.set(rate_key, "1", ex=600) + count = 1 + else: + try: + count = int(current) + 1 + except Exception: + count = 1 + ttl = redis_client.ttl(rate_key) + ttl = int(ttl) if isinstance(ttl, (int, str)) else 600 + if ttl < 1: + ttl = 600 + redis_client.set(rate_key, str(count), ex=ttl) + if count > 5: + logger.warning(f"Email send rate limited for: {email}") + return False + except Exception: + pass + # Generate random 6-digit verification code captcha = str(random.randint(100000, 999999)) - - # Cache to redis CacheUtils.set_cache(RedisKeys.email_login_captcha(email), captcha, 10 * 60) - - # Send verification code using HTML email template return EmailUtils.send_register_code_email(self.db, email, captcha) def email_login_by_captcha(self, email: str, captcha: str) -> Optional[str]: diff --git a/services/api_service/controllers/mcp.py b/services/api_service/controllers/mcp.py index 367a3e2..b557430 100644 --- a/services/api_service/controllers/mcp.py +++ b/services/api_service/controllers/mcp.py @@ -10,6 +10,7 @@ from starlette.responses import Response import asyncio import time import hashlib +import re from mcp.server.sse import SseServerTransport from mcp.server.streamable_http import StreamableHTTPServerTransport from mcp.server.lowlevel import Server @@ -345,7 +346,8 @@ class McpController: return user_id, apikey_id = user_info - client_instance_id = req.headers.get('x-client-instance-id') or req.headers.get('x-client-id') + raw_client_id = req.headers.get('x-client-instance-id') or req.headers.get('x-client-id') + client_instance_id = (re.sub(r'[^a-zA-Z0-9._-]', '', raw_client_id)[:32]) if raw_client_id else None ua = user_agent or "" ua_hash = hashlib.sha1(ua.encode('utf-8')).hexdigest()[:8] client_fingerprint = client_instance_id or f"{client_ip}:{ua_hash}" diff --git a/services/api_service/main.py b/services/api_service/main.py index 39223b9..62843bc 100644 --- a/services/api_service/main.py +++ b/services/api_service/main.py @@ -100,11 +100,11 @@ app.add_middleware(ExceptionHandlingMiddleware) # Add CORS middleware for MCP client cross-origin and reconnection support app.add_middleware( CORSMiddleware, - allow_origins=["*"], # MCP clients may come from different domains - allow_credentials=True, - allow_methods=["GET", "POST", "DELETE", "OPTIONS"], # 添加 DELETE 支持 StreamableHTTP 终止 + allow_origins=Config.ALLOWED_ORIGINS, + allow_credentials=False, + allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["*"], - expose_headers=["*"], # Expose all response headers for SSE reconnection + expose_headers=["*"] ) # Create MCP controller instance diff --git a/services/api_service/services/mcp_tool_service.py b/services/api_service/services/mcp_tool_service.py index 1bda5a6..f0fd35b 100644 --- a/services/api_service/services/mcp_tool_service.py +++ b/services/api_service/services/mcp_tool_service.py @@ -84,11 +84,7 @@ class McpToolService: raise ValueError(f"Unsupported HTTP method: {method}") logger.info(f"HTTP response status code: {response.status_code}") - if response.text != "": - logger.debug(f"Response content: {response.text}") response.raise_for_status() - response_text = response.text - logger.debug(f"Response content length: {len(response_text)} characters") - + logger.debug(f"Response length: {len(response_text)}") return response_text diff --git a/services/common/config.py b/services/common/config.py index bee2713..ff8b7ae 100644 --- a/services/common/config.py +++ b/services/common/config.py @@ -75,3 +75,4 @@ class Config: ] MCP_SESSION_IDLE_TTL_SECONDS = int(os.getenv("MCP_SESSION_IDLE_TTL_SECONDS", 900)) MCP_SESSION_CLEANUP_INTERVAL_SECONDS = int(os.getenv("MCP_SESSION_CLEANUP_INTERVAL_SECONDS", 60)) + ALLOWED_ORIGINS = [s.strip() for s in os.getenv("ALLOWED_ORIGINS", "*").split(",") if s.strip()] diff --git a/services/common/utils/http_utils.py b/services/common/utils/http_utils.py index e9de558..b8d2db2 100644 --- a/services/common/utils/http_utils.py +++ b/services/common/utils/http_utils.py @@ -188,6 +188,15 @@ class HttpUtils: if headers: request_headers.update(headers) + # Basic SSRF protections: only allow http/https and block localhost/private IPs + parsed = urlparse(url) + if parsed.scheme not in ("http", "https"): + raise ValidationException("URL scheme must be http or https") + host = (parsed.hostname or "").lower() + private_prefixes = ("127.", "10.", "192.168.") + if host in ("localhost", "127.0.0.1") or host.startswith(private_prefixes) or host.startswith("172."): + raise ValidationException("Access to local/private addresses is not allowed") + async with aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=timeout), headers=request_headers