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>
143 lines
4.9 KiB
Python
143 lines
4.9 KiB
Python
from pydantic_settings import BaseSettings
|
|
from pydantic import field_validator
|
|
from typing import List, Optional
|
|
import os
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
# Database
|
|
MYSQL_HOST: str = "localhost"
|
|
MYSQL_PORT: int = 3306
|
|
MYSQL_USER: str = "root"
|
|
MYSQL_PASSWORD: str = ""
|
|
MYSQL_DATABASE: str = "pjctrl"
|
|
|
|
@property
|
|
def DATABASE_URL(self) -> str:
|
|
return f"mysql+pymysql://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DATABASE}"
|
|
|
|
# Redis
|
|
REDIS_HOST: str = "localhost"
|
|
REDIS_PORT: int = 6379
|
|
REDIS_DB: int = 0
|
|
|
|
@property
|
|
def REDIS_URL(self) -> str:
|
|
return f"redis://{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"
|
|
|
|
# JWT - Must be set in environment, no default allowed
|
|
JWT_SECRET_KEY: str = ""
|
|
JWT_ALGORITHM: str = "HS256"
|
|
JWT_EXPIRE_MINUTES: int = 60 # 1 hour (short-lived access token)
|
|
REFRESH_TOKEN_EXPIRE_DAYS: int = 7 # Refresh token valid for 7 days
|
|
|
|
@field_validator("JWT_SECRET_KEY")
|
|
@classmethod
|
|
def validate_jwt_secret_key(cls, v: str) -> str:
|
|
"""Validate that JWT_SECRET_KEY is set and not a placeholder."""
|
|
if not v or v.strip() == "":
|
|
raise ValueError(
|
|
"JWT_SECRET_KEY must be set in environment variables. "
|
|
"Please configure it in the .env file."
|
|
)
|
|
placeholder_values = [
|
|
"your-secret-key-change-in-production",
|
|
"change-me",
|
|
"secret",
|
|
"your-secret-key",
|
|
]
|
|
if v.lower() in placeholder_values:
|
|
raise ValueError(
|
|
"JWT_SECRET_KEY appears to be a placeholder value. "
|
|
"Please set a secure secret key in the .env file."
|
|
)
|
|
return v
|
|
|
|
# Encryption - Master key for encrypting file encryption keys
|
|
# Must be a 32-byte (256-bit) key encoded as base64 for AES-256
|
|
# Generate with: python -c "import secrets, base64; print(base64.urlsafe_b64encode(secrets.token_bytes(32)).decode())"
|
|
ENCRYPTION_MASTER_KEY: Optional[str] = None
|
|
|
|
@field_validator("ENCRYPTION_MASTER_KEY")
|
|
@classmethod
|
|
def validate_encryption_master_key(cls, v: Optional[str]) -> Optional[str]:
|
|
"""Validate that ENCRYPTION_MASTER_KEY is properly formatted if set."""
|
|
if v is None or v.strip() == "":
|
|
return None
|
|
# Basic validation - should be base64 encoded 32 bytes
|
|
import base64
|
|
try:
|
|
decoded = base64.urlsafe_b64decode(v)
|
|
if len(decoded) != 32:
|
|
raise ValueError(
|
|
"ENCRYPTION_MASTER_KEY must be a base64-encoded 32-byte key. "
|
|
"Generate with: python -c \"import secrets, base64; print(base64.urlsafe_b64encode(secrets.token_bytes(32)).decode())\""
|
|
)
|
|
except Exception as e:
|
|
if "must be a base64-encoded" in str(e):
|
|
raise
|
|
raise ValueError(
|
|
"ENCRYPTION_MASTER_KEY must be a valid base64-encoded string. "
|
|
f"Error: {e}"
|
|
)
|
|
return v
|
|
|
|
# External Auth API
|
|
AUTH_API_URL: str = "https://pj-auth-api.vercel.app"
|
|
|
|
# CORS
|
|
CORS_ORIGINS: List[str] = ["http://localhost:3000", "http://localhost:5173"]
|
|
|
|
# System Admin
|
|
SYSTEM_ADMIN_EMAIL: str = "ymirliu@panjit.com.tw"
|
|
|
|
# File Upload
|
|
UPLOAD_DIR: str = "./uploads"
|
|
MAX_FILE_SIZE_MB: int = 50
|
|
|
|
@property
|
|
def MAX_FILE_SIZE(self) -> int:
|
|
return self.MAX_FILE_SIZE_MB * 1024 * 1024
|
|
|
|
# Allowed file extensions (whitelist)
|
|
ALLOWED_EXTENSIONS: List[str] = [
|
|
# Documents
|
|
"pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "csv",
|
|
# Images
|
|
"jpg", "jpeg", "png", "gif", "bmp", "svg", "webp",
|
|
# Archives
|
|
"zip", "rar", "7z", "tar", "gz",
|
|
# Data
|
|
"json", "xml", "yaml", "yml",
|
|
]
|
|
|
|
# Blocked file extensions (dangerous)
|
|
BLOCKED_EXTENSIONS: List[str] = [
|
|
"exe", "bat", "cmd", "sh", "ps1", "dll", "msi", "com", "scr", "vbs", "js"
|
|
]
|
|
|
|
# Rate Limiting Configuration
|
|
# Tiers: standard, sensitive, heavy
|
|
# Format: "{requests}/{period}" (e.g., "60/minute", "20/minute", "5/minute")
|
|
RATE_LIMIT_STANDARD: str = "60/minute" # Task CRUD, comments
|
|
RATE_LIMIT_SENSITIVE: str = "20/minute" # Attachments, password change, report export
|
|
RATE_LIMIT_HEAVY: str = "5/minute" # Report generation, bulk operations
|
|
|
|
# Development Mode Settings
|
|
DEBUG: bool = False # Enable debug mode for development
|
|
QUERY_LOGGING: bool = False # Enable SQLAlchemy query logging
|
|
QUERY_COUNT_THRESHOLD: int = 10 # Warn when query count exceeds this threshold
|
|
|
|
# Environment
|
|
ENVIRONMENT: str = "development" # Options: development, staging, production
|
|
|
|
# WebSocket Settings
|
|
MAX_WEBSOCKET_CONNECTIONS_PER_USER: int = 5 # Maximum concurrent WebSocket connections per user
|
|
|
|
class Config:
|
|
env_file = ".env"
|
|
case_sensitive = True
|
|
|
|
|
|
settings = Settings()
|