feat: implement 5 QA-driven security and quality proposals

Implemented proposals from comprehensive QA review:

1. extend-csrf-protection
   - Add POST to CSRF protected methods in frontend
   - Global CSRF middleware for all state-changing operations
   - Update tests with CSRF token fixtures

2. tighten-cors-websocket-security
   - Replace wildcard CORS with explicit method/header lists
   - Disable query parameter auth in production (code 4002)
   - Add per-user WebSocket connection limit (max 5, code 4005)

3. shorten-jwt-expiry
   - Reduce JWT expiry from 7 days to 60 minutes
   - Add refresh token support with 7-day expiry
   - Implement token rotation on refresh
   - Frontend auto-refresh when token near expiry (<5 min)

4. fix-frontend-quality
   - Add React.lazy() code splitting for all pages
   - Fix useCallback dependency arrays (Dashboard, Comments)
   - Add localStorage data validation in AuthContext
   - Complete i18n for AttachmentUpload component

5. enhance-backend-validation
   - Add SecurityAuditMiddleware for access denied logging
   - Add ErrorSanitizerMiddleware for production error messages
   - Protect /health/detailed with admin authentication
   - Add input length validation (comment 5000, desc 10000)

All 521 backend tests passing. Frontend builds successfully.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
beabigegg
2026-01-12 23:19:05 +08:00
parent df50d5e7f8
commit 35c90fe76b
48 changed files with 2132 additions and 403 deletions

View File

@@ -4,6 +4,7 @@ import logging
from typing import Dict, Set, Optional, Tuple
from fastapi import WebSocket
from app.core.redis import get_redis_sync
from app.core.config import settings
logger = logging.getLogger(__name__)
@@ -19,13 +20,48 @@ class ConnectionManager:
self._lock = asyncio.Lock()
self._project_lock = asyncio.Lock()
async def check_connection_limit(self, user_id: str) -> Tuple[bool, Optional[str]]:
"""
Check if user can create a new WebSocket connection.
Args:
user_id: The user's ID
Returns:
Tuple of (can_connect: bool, reject_reason: str | None)
- can_connect: True if user is within connection limit
- reject_reason: Error message if connection should be rejected
"""
max_connections = settings.MAX_WEBSOCKET_CONNECTIONS_PER_USER
async with self._lock:
current_count = len(self.active_connections.get(user_id, set()))
if current_count >= max_connections:
logger.warning(
f"User {user_id} exceeded WebSocket connection limit "
f"({current_count}/{max_connections})"
)
return False, "Too many connections"
return True, None
def get_user_connection_count(self, user_id: str) -> int:
"""Get the current number of WebSocket connections for a user."""
return len(self.active_connections.get(user_id, set()))
async def connect(self, websocket: WebSocket, user_id: str):
"""Accept and track a new WebSocket connection."""
await websocket.accept()
"""
Track a new WebSocket connection.
Note: WebSocket must already be accepted before calling this method.
Connection limit should be checked via check_connection_limit() before calling.
"""
async with self._lock:
if user_id not in self.active_connections:
self.active_connections[user_id] = set()
self.active_connections[user_id].add(websocket)
logger.debug(
f"User {user_id} connected. Total connections: "
f"{len(self.active_connections[user_id])}"
)
async def disconnect(self, websocket: WebSocket, user_id: str):
"""Remove a WebSocket connection."""