Spaces:
Runtime error
Runtime error
File size: 12,706 Bytes
330b6e4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | """
Message validation and sanitization for WebSocket communications.
This module provides validation and sanitization for incoming WebSocket messages
to ensure security and data integrity.
"""
import re
import html
import logging
from typing import Dict, Any, List, Optional
from datetime import datetime, timedelta
logger = logging.getLogger(__name__)
class MessageValidator:
"""Validates and sanitizes WebSocket messages for security."""
# Maximum message length (characters)
MAX_MESSAGE_LENGTH = 10000
# Maximum messages per minute per connection
MAX_MESSAGES_PER_MINUTE = 30
# Supported programming languages
SUPPORTED_LANGUAGES = {
'python', 'javascript', 'java', 'cpp', 'c', 'csharp', 'go',
'rust', 'typescript', 'php', 'ruby', 'swift', 'kotlin', 'scala'
}
# Patterns for potentially malicious content
MALICIOUS_PATTERNS = [
r'<script[^>]*>.*?</script>', # Script tags
r'javascript:', # JavaScript URLs
r'on\w+\s*=', # Event handlers
r'<iframe[^>]*>.*?</iframe>', # Iframes
r'<object[^>]*>.*?</object>', # Objects
r'<embed[^>]*>.*?</embed>', # Embeds
]
def __init__(self):
"""Initialize the message validator."""
self.rate_limit_tracker = {} # Track message rates per connection
self.compiled_patterns = [re.compile(pattern, re.IGNORECASE | re.DOTALL)
for pattern in self.MALICIOUS_PATTERNS]
def validate_message(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate and sanitize a chat message.
Args:
data: Message data from WebSocket
Returns:
Dict containing validation result and sanitized content
"""
errors = []
# Check required fields
if not isinstance(data, dict):
return {
'valid': False,
'errors': ['Message data must be a dictionary'],
'sanitized_content': None
}
if 'content' not in data:
errors.append('Message content is required')
if 'session_id' not in data:
errors.append('Session ID is required')
if errors:
return {
'valid': False,
'errors': errors,
'sanitized_content': None
}
content = data['content']
session_id = data['session_id']
# Validate content type
if not isinstance(content, str):
errors.append('Message content must be a string')
# Validate session_id type
if not isinstance(session_id, str):
errors.append('Session ID must be a string')
if errors:
return {
'valid': False,
'errors': errors,
'sanitized_content': None
}
# Check message length
if len(content) > self.MAX_MESSAGE_LENGTH:
errors.append(f'Message too long (max {self.MAX_MESSAGE_LENGTH} characters)')
# Check for empty content
if not content.strip():
errors.append('Message content cannot be empty')
# Check rate limiting
rate_limit_error = self._check_rate_limit(session_id)
if rate_limit_error:
errors.append(rate_limit_error)
if errors:
return {
'valid': False,
'errors': errors,
'sanitized_content': None
}
# Check for malicious patterns before sanitization
malicious_patterns = self._check_malicious_patterns(content)
if malicious_patterns:
errors.extend(malicious_patterns)
return {
'valid': False,
'errors': errors,
'sanitized_content': None
}
# Sanitize content
sanitized_content = self._sanitize_content(content)
return {
'valid': True,
'errors': [],
'sanitized_content': sanitized_content
}
def validate_language_switch(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate a language switch request.
Args:
data: Language switch data from WebSocket
Returns:
Dict containing validation result and validated language
"""
errors = []
# Check required fields
if not isinstance(data, dict):
return {
'valid': False,
'errors': ['Language switch data must be a dictionary'],
'language': None
}
if 'language' not in data:
errors.append('Language is required')
if 'session_id' not in data:
errors.append('Session ID is required')
if errors:
return {
'valid': False,
'errors': errors,
'language': None
}
language = data['language']
session_id = data['session_id']
# Validate types
if not isinstance(language, str):
errors.append('Language must be a string')
if not isinstance(session_id, str):
errors.append('Session ID must be a string')
if errors:
return {
'valid': False,
'errors': errors,
'language': None
}
# Normalize language
normalized_language = language.lower().strip()
# Check if language is supported
if normalized_language not in self.SUPPORTED_LANGUAGES:
errors.append(f'Unsupported language: {language}. Supported languages: {", ".join(sorted(self.SUPPORTED_LANGUAGES))}')
# Check rate limiting
rate_limit_error = self._check_rate_limit(session_id)
if rate_limit_error:
errors.append(rate_limit_error)
if errors:
return {
'valid': False,
'errors': errors,
'language': None
}
return {
'valid': True,
'errors': [],
'language': normalized_language
}
def validate_typing_event(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate a typing event.
Args:
data: Typing event data from WebSocket
Returns:
Dict containing validation result
"""
errors = []
# Check data type
if not isinstance(data, dict):
return {
'valid': False,
'errors': ['Typing event data must be a dictionary']
}
# Session ID is optional for typing events but if present, validate it
if 'session_id' in data and not isinstance(data['session_id'], str):
errors.append('Session ID must be a string')
if errors:
return {
'valid': False,
'errors': errors
}
return {
'valid': True,
'errors': []
}
def _sanitize_content(self, content: str) -> str:
"""
Sanitize message content to prevent XSS and other attacks.
Args:
content: Raw message content
Returns:
str: Sanitized content
"""
# HTML escape to prevent XSS
sanitized = html.escape(content)
# Remove null bytes
sanitized = sanitized.replace('\x00', '')
# Normalize whitespace but preserve code formatting
lines = sanitized.split('\n')
normalized_lines = []
for line in lines:
# Preserve leading whitespace for code blocks
stripped = line.rstrip()
normalized_lines.append(stripped)
# Remove excessive empty lines (more than 3 consecutive)
result_lines = []
empty_count = 0
for line in normalized_lines:
if not line.strip():
empty_count += 1
if empty_count <= 3:
result_lines.append(line)
else:
empty_count = 0
result_lines.append(line)
return '\n'.join(result_lines)
def _check_malicious_patterns(self, content: str) -> List[str]:
"""
Check for potentially malicious patterns in content.
Args:
content: Content to check
Returns:
List[str]: List of detected malicious patterns
"""
detected_patterns = []
for pattern in self.compiled_patterns:
if pattern.search(content):
detected_patterns.append(f'Potentially malicious content detected')
break # Don't reveal specific patterns for security
return detected_patterns
def _check_rate_limit(self, session_id: str) -> Optional[str]:
"""
Check if the session is exceeding rate limits.
Args:
session_id: Session identifier
Returns:
Optional[str]: Error message if rate limit exceeded, None otherwise
"""
now = datetime.utcnow()
minute_key = now.strftime('%Y-%m-%d-%H-%M')
# Initialize tracking for this session if needed
if session_id not in self.rate_limit_tracker:
self.rate_limit_tracker[session_id] = {}
session_tracker = self.rate_limit_tracker[session_id]
# Clean up old entries (keep only current and previous minute)
current_minute = minute_key
previous_minute = (now.replace(second=0, microsecond=0) -
timedelta(minutes=1)).strftime('%Y-%m-%d-%H-%M')
keys_to_keep = {current_minute, previous_minute}
keys_to_remove = [k for k in session_tracker.keys() if k not in keys_to_keep]
for key in keys_to_remove:
del session_tracker[key]
# Check current minute count
current_count = session_tracker.get(current_minute, 0)
if current_count >= self.MAX_MESSAGES_PER_MINUTE:
return f'Rate limit exceeded. Maximum {self.MAX_MESSAGES_PER_MINUTE} messages per minute.'
# Increment counter
session_tracker[current_minute] = current_count + 1
return None
def get_supported_languages(self) -> List[str]:
"""
Get list of supported programming languages.
Returns:
List[str]: Sorted list of supported languages
"""
return sorted(list(self.SUPPORTED_LANGUAGES))
def cleanup_rate_limit_tracker(self) -> None:
"""Clean up old rate limit tracking data."""
now = datetime.utcnow()
cutoff_time = now - timedelta(minutes=5)
cutoff_key = cutoff_time.strftime('%Y-%m-%d-%H-%M')
sessions_to_clean = []
for session_id, session_tracker in self.rate_limit_tracker.items():
keys_to_remove = [k for k in session_tracker.keys() if k < cutoff_key]
for key in keys_to_remove:
del session_tracker[key]
# Remove empty session trackers
if not session_tracker:
sessions_to_clean.append(session_id)
for session_id in sessions_to_clean:
del self.rate_limit_tracker[session_id]
logger.debug(f"Cleaned up rate limit tracker, removed {len(sessions_to_clean)} empty sessions")
def create_message_validator() -> MessageValidator:
"""
Factory function to create a MessageValidator instance.
Returns:
MessageValidator: Configured message validator
"""
return MessageValidator() |