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:
@@ -3,12 +3,28 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import get_db
|
||||
from app.core.security import create_access_token, create_token_payload
|
||||
from app.core.security import (
|
||||
create_access_token,
|
||||
create_token_payload,
|
||||
generate_refresh_token,
|
||||
store_refresh_token,
|
||||
validate_refresh_token,
|
||||
invalidate_refresh_token,
|
||||
invalidate_all_user_refresh_tokens,
|
||||
decode_refresh_token_user_id,
|
||||
)
|
||||
from app.core.redis import get_redis
|
||||
from app.core.rate_limiter import limiter
|
||||
from app.models.user import User
|
||||
from app.models.audit_log import AuditAction
|
||||
from app.schemas.auth import LoginRequest, LoginResponse, UserInfo, CSRFTokenResponse
|
||||
from app.schemas.auth import (
|
||||
LoginRequest,
|
||||
LoginResponse,
|
||||
UserInfo,
|
||||
CSRFTokenResponse,
|
||||
RefreshTokenRequest,
|
||||
RefreshTokenResponse,
|
||||
)
|
||||
from app.services.auth_client import (
|
||||
verify_credentials,
|
||||
AuthAPIError,
|
||||
@@ -119,6 +135,9 @@ async def login(
|
||||
# Create access token
|
||||
access_token = create_access_token(token_data)
|
||||
|
||||
# Generate refresh token
|
||||
refresh_token = generate_refresh_token()
|
||||
|
||||
# Store session in Redis (sync with JWT expiry)
|
||||
redis_client.setex(
|
||||
f"session:{user.id}",
|
||||
@@ -126,6 +145,9 @@ async def login(
|
||||
access_token,
|
||||
)
|
||||
|
||||
# Store refresh token in Redis with user binding
|
||||
store_refresh_token(redis_client, user.id, refresh_token)
|
||||
|
||||
# Log successful login
|
||||
AuditService.log_event(
|
||||
db=db,
|
||||
@@ -141,6 +163,8 @@ async def login(
|
||||
|
||||
return LoginResponse(
|
||||
access_token=access_token,
|
||||
refresh_token=refresh_token,
|
||||
expires_in=settings.JWT_EXPIRE_MINUTES * 60,
|
||||
user=UserInfo(
|
||||
id=user.id,
|
||||
email=user.email,
|
||||
@@ -158,14 +182,114 @@ async def logout(
|
||||
redis_client=Depends(get_redis),
|
||||
):
|
||||
"""
|
||||
Logout user and invalidate session.
|
||||
Logout user and invalidate session and all refresh tokens.
|
||||
"""
|
||||
# Remove session from Redis
|
||||
redis_client.delete(f"session:{current_user.id}")
|
||||
|
||||
# Invalidate all refresh tokens for this user
|
||||
invalidate_all_user_refresh_tokens(redis_client, current_user.id)
|
||||
|
||||
return {"detail": "Successfully logged out"}
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=RefreshTokenResponse)
|
||||
@limiter.limit("10/minute")
|
||||
async def refresh_access_token(
|
||||
request: Request,
|
||||
refresh_request: RefreshTokenRequest,
|
||||
db: Session = Depends(get_db),
|
||||
redis_client=Depends(get_redis),
|
||||
):
|
||||
"""
|
||||
Refresh access token using a valid refresh token.
|
||||
|
||||
This endpoint implements refresh token rotation:
|
||||
- Validates the provided refresh token
|
||||
- Issues a new access token
|
||||
- Issues a new refresh token (rotating the old one)
|
||||
- Invalidates the old refresh token
|
||||
|
||||
This provides enhanced security by ensuring refresh tokens are single-use.
|
||||
"""
|
||||
old_refresh_token = refresh_request.refresh_token
|
||||
|
||||
# Find the user ID associated with this refresh token
|
||||
user_id = decode_refresh_token_user_id(old_refresh_token, redis_client)
|
||||
|
||||
if user_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired refresh token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Validate the refresh token is still valid and bound to this user
|
||||
if not validate_refresh_token(redis_client, user_id, old_refresh_token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired refresh token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Get user from database
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
if user is None:
|
||||
# Invalidate the token since user no longer exists
|
||||
invalidate_refresh_token(redis_client, user_id, old_refresh_token)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
if not user.is_active:
|
||||
# Invalidate all tokens for disabled user
|
||||
invalidate_all_user_refresh_tokens(redis_client, user_id)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="User account is disabled",
|
||||
)
|
||||
|
||||
# Invalidate the old refresh token (rotation)
|
||||
invalidate_refresh_token(redis_client, user_id, old_refresh_token)
|
||||
|
||||
# Get role name
|
||||
role_name = user.role.name if user.role else None
|
||||
|
||||
# Create new token payload
|
||||
token_data = create_token_payload(
|
||||
user_id=user.id,
|
||||
email=user.email,
|
||||
role=role_name,
|
||||
department_id=user.department_id,
|
||||
is_system_admin=user.is_system_admin,
|
||||
)
|
||||
|
||||
# Create new access token
|
||||
new_access_token = create_access_token(token_data)
|
||||
|
||||
# Generate new refresh token (rotation)
|
||||
new_refresh_token = generate_refresh_token()
|
||||
|
||||
# Store new session in Redis
|
||||
redis_client.setex(
|
||||
f"session:{user.id}",
|
||||
settings.JWT_EXPIRE_MINUTES * 60,
|
||||
new_access_token,
|
||||
)
|
||||
|
||||
# Store new refresh token
|
||||
store_refresh_token(redis_client, user.id, new_refresh_token)
|
||||
|
||||
return RefreshTokenResponse(
|
||||
access_token=new_access_token,
|
||||
refresh_token=new_refresh_token,
|
||||
expires_in=settings.JWT_EXPIRE_MINUTES * 60,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserInfo)
|
||||
async def get_current_user_info(
|
||||
current_user: User = Depends(get_current_user),
|
||||
|
||||
@@ -9,6 +9,7 @@ from sqlalchemy.orm import Session
|
||||
from app.core import database
|
||||
from app.core.security import decode_access_token
|
||||
from app.core.redis import get_redis_sync
|
||||
from app.core.config import settings
|
||||
from app.models import User, Notification, Project
|
||||
from app.services.websocket_manager import manager
|
||||
from app.core.redis_pubsub import NotificationSubscriber, ProjectTaskSubscriber
|
||||
@@ -72,14 +73,24 @@ async def authenticate_websocket(
|
||||
Supports two authentication methods:
|
||||
1. First message authentication (preferred, more secure)
|
||||
- Client sends: {"type": "auth", "token": "<jwt_token>"}
|
||||
2. Query parameter authentication (deprecated, for backward compatibility)
|
||||
2. Query parameter authentication (disabled in production, for backward compatibility only)
|
||||
- Client connects with: ?token=<jwt_token>
|
||||
|
||||
Returns:
|
||||
Tuple of (user_id, error_reason). user_id is None if authentication fails.
|
||||
Error reasons: "invalid_token", "invalid_message", "missing_token",
|
||||
"timeout", "error", "query_auth_disabled"
|
||||
"""
|
||||
# If token provided via query parameter (backward compatibility)
|
||||
if query_token:
|
||||
# Reject query parameter auth in production for security
|
||||
if settings.ENVIRONMENT == "production":
|
||||
logger.warning(
|
||||
"WebSocket query parameter authentication attempted in production environment. "
|
||||
"This is disabled for security reasons."
|
||||
)
|
||||
return None, "query_auth_disabled"
|
||||
|
||||
logger.warning(
|
||||
"WebSocket authentication via query parameter is deprecated. "
|
||||
"Please use first-message authentication for better security."
|
||||
@@ -195,9 +206,21 @@ async def websocket_notifications(
|
||||
user_id, error_reason = await authenticate_websocket(websocket, token)
|
||||
|
||||
if user_id is None:
|
||||
if error_reason == "invalid_token":
|
||||
if error_reason == "query_auth_disabled":
|
||||
await websocket.send_json({"type": "error", "message": "Query parameter auth disabled in production"})
|
||||
await websocket.close(code=4002, reason="Query parameter auth disabled in production")
|
||||
elif error_reason == "invalid_token":
|
||||
await websocket.send_json({"type": "error", "message": "Invalid or expired token"})
|
||||
await websocket.close(code=4001, reason="Invalid or expired token")
|
||||
await websocket.close(code=4001, reason="Invalid or expired token")
|
||||
else:
|
||||
await websocket.close(code=4001, reason="Invalid or expired token")
|
||||
return
|
||||
|
||||
# Check connection limit before accepting
|
||||
can_connect, reject_reason = await manager.check_connection_limit(user_id)
|
||||
if not can_connect:
|
||||
await websocket.send_json({"type": "error", "message": reject_reason})
|
||||
await websocket.close(code=4005, reason=reject_reason)
|
||||
return
|
||||
|
||||
await manager.connect(websocket, user_id)
|
||||
@@ -394,9 +417,21 @@ async def websocket_project_sync(
|
||||
user_id, error_reason = await authenticate_websocket(websocket, token)
|
||||
|
||||
if user_id is None:
|
||||
if error_reason == "invalid_token":
|
||||
if error_reason == "query_auth_disabled":
|
||||
await websocket.send_json({"type": "error", "message": "Query parameter auth disabled in production"})
|
||||
await websocket.close(code=4002, reason="Query parameter auth disabled in production")
|
||||
elif error_reason == "invalid_token":
|
||||
await websocket.send_json({"type": "error", "message": "Invalid or expired token"})
|
||||
await websocket.close(code=4001, reason="Invalid or expired token")
|
||||
await websocket.close(code=4001, reason="Invalid or expired token")
|
||||
else:
|
||||
await websocket.close(code=4001, reason="Invalid or expired token")
|
||||
return
|
||||
|
||||
# Check connection limit before accepting
|
||||
can_connect, reject_reason = await manager.check_connection_limit(user_id)
|
||||
if not can_connect:
|
||||
await websocket.send_json({"type": "error", "message": reject_reason})
|
||||
await websocket.close(code=4005, reason=reject_reason)
|
||||
return
|
||||
|
||||
# Verify user has access to the project
|
||||
|
||||
Reference in New Issue
Block a user