Spaces:
Sleeping
Sleeping
File size: 24,567 Bytes
5a5c0ca | 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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | # CSV to JSON Converter - Production-Ready Implementation (Security Hardened)
import csv
import json
import logging
import threading
from pathlib import Path
from typing import Dict, List, Any, Optional, Callable
from dataclasses import dataclass
from datetime import datetime, timedelta
from collections import defaultdict
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Constants
MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024 # 100MB
MAX_ROWS = 1000000 # 1 million rows
CHUNK_SIZE = 10000 # Process in chunks of 10k rows
LARGE_FILE_THRESHOLD = 10 * 1024 * 1024 # 10MB
ALLOWED_EXTENSIONS = {'.csv', '.txt'}
DEFAULT_ENCODING = 'utf-8'
FALLBACK_ENCODING = 'latin-1'
# Security: Dangerous keys that could cause prototype pollution in JavaScript
DANGEROUS_KEYS = {
'__proto__', 'constructor', 'prototype',
'__defineGetter__', '__defineSetter__',
'__lookupGetter__', '__lookupSetter__',
'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf',
'__parent__', '__count__', '__noSuchMethod__',
'watch', 'unwatch'
}
# Security: Characters that can trigger CSV injection
CSV_INJECTION_CHARS = ('=', '+', '-', '@', '\t', '\r')
# Security: Dangerous formula patterns
DANGEROUS_FORMULA_PATTERNS = [
'=CMD|', '=HYPERLINK', '=IMPORTXML', '=WEBSERVICE',
'@SUM', '+CMD|', '-CMD|', '=DDE', '=MSEXCEL|'
]
# Security: Sensitive system paths to block
SENSITIVE_PATHS = ['/etc', '/sys', '/proc', '/root', '/var', 'C:\\Windows', 'C:\\Program Files']
# Rate limiting and concurrency control
_processing_locks = defaultdict(threading.Lock)
_processing_count = {"current": 0, "max": 5}
_rate_limit = {"requests": [], "max_per_minute": 20}
_rate_limit_lock = threading.Lock()
@dataclass
class ProcessingResult:
"""Result of CSV processing operation."""
status: str
data: Optional[List[Dict[str, Any]]] = None
message: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
def process_csv_file(
file_path: str,
max_rows: int = MAX_ROWS,
allowed_base_dir: Optional[str] = None,
progress_callback: Optional[Callable[[int, int], None]] = None
) -> dict:
"""Process a single CSV file and convert it to JSON format with validation.
This function implements comprehensive security measures including:
- Path traversal prevention with base directory enforcement
- File size validation to prevent memory exhaustion
- Row limit enforcement to prevent DoS attacks
- CSV injection prevention by sanitizing formula characters
- Prototype pollution prevention by sanitizing dictionary keys
- Rate limiting and concurrency control
- Proper error handling without information leakage
Args:
file_path (str): Path to the CSV file to process
max_rows (int): Maximum number of rows to process (default: 1,000,000)
allowed_base_dir (Optional[str]): Base directory to restrict file access.
If provided, file_path must be within this directory.
progress_callback (Optional[Callable]): Function(current_row, total_rows)
called periodically to report progress
Returns:
dict: Processing result with structure:
{
"status": "success" | "error",
"data": [...], # List of dictionaries (only on success)
"message": "...", # Error message (only on error)
"metadata": { # Processing statistics (only on success)
"total_rows": int,
"sanitized_values": int,
"sanitized_keys": int,
"columns": [...],
"encoding_used": str
}
}
"""
# Validate max_rows parameter
if not isinstance(max_rows, int) or max_rows < 1 or max_rows > MAX_ROWS:
return {
"status": "error",
"message": f"Invalid max_rows parameter. Must be between 1 and {MAX_ROWS:,}"
}
# Rate limiting check
if not _check_rate_limit():
logger.warning("Rate limit exceeded")
return {
"status": "error",
"message": "Rate limit exceeded. Please try again later."
}
# Concurrency limiting
if _processing_count["current"] >= _processing_count["max"]:
logger.warning("Concurrency limit reached")
return {
"status": "error",
"message": "Server is currently processing maximum number of files. Please try again in a moment."
}
_processing_count["current"] += 1
try:
# Validate and sanitize file path
validation_result = _validate_file_path(file_path, allowed_base_dir)
if validation_result is not None:
return validation_result
# Resolve path after validation
path_obj = Path(file_path).resolve()
# Validate file extension
if path_obj.suffix.lower() not in ALLOWED_EXTENSIONS:
logger.warning(f"Invalid file extension: {path_obj.suffix}")
return {
"status": "error",
"message": f"Invalid file type. Allowed types: {', '.join(ALLOWED_EXTENSIONS)}"
}
# Validate file size before processing
file_size = path_obj.stat().st_size
if file_size > MAX_FILE_SIZE_BYTES:
logger.warning(f"File too large: {file_size} bytes")
return {
"status": "error",
"message": f"File too large. Maximum size: {MAX_FILE_SIZE_BYTES // (1024*1024)}MB"
}
if file_size == 0:
logger.warning("Empty file provided")
return {
"status": "error",
"message": "File is empty."
}
# Process the CSV file with streaming for large files
result = _process_csv_content(path_obj, max_rows, progress_callback)
if result.status == "success":
logger.info(f"Successfully processed {result.metadata['total_rows']} rows")
return _result_to_dict(result)
except PermissionError:
logger.error("Permission denied accessing file")
return {
"status": "error",
"message": "Permission denied. Unable to read the file."
}
except Exception as e:
logger.exception("Unexpected error processing file")
return {
"status": "error",
"message": "An unexpected error occurred during processing. Please contact support."
}
finally:
_processing_count["current"] -= 1
def _check_rate_limit() -> bool:
"""Check if request is within rate limits.
Returns:
bool: True if request is allowed, False if rate limit exceeded
"""
with _rate_limit_lock:
now = datetime.now()
# Remove requests older than 1 minute
_rate_limit["requests"] = [
ts for ts in _rate_limit["requests"]
if now - ts < timedelta(minutes=1)
]
# Check if limit exceeded
if len(_rate_limit["requests"]) >= _rate_limit["max_per_minute"]:
return False
# Add current request
_rate_limit["requests"].append(now)
return True
def _validate_file_path(file_path: str, allowed_base_dir: Optional[str]) -> Optional[dict]:
"""Validate file path to prevent path traversal attacks.
Args:
file_path (str): Path to validate
allowed_base_dir (Optional[str]): Base directory restriction
Returns:
Optional[dict]: Error dict if validation fails, None if valid
"""
try:
# Resolve to absolute path to handle symlinks and relative paths
path_obj = Path(file_path).resolve()
# Check if file exists
if not path_obj.exists():
logger.warning("File not found")
return {
"status": "error",
"message": "File not found. Please check the file path."
}
# Check if it's a file (not a directory)
if not path_obj.is_file():
logger.warning("Path is not a file")
return {
"status": "error",
"message": "Path must point to a file, not a directory."
}
# Enforce base directory restriction if provided
if allowed_base_dir:
base_path = Path(allowed_base_dir).resolve()
try:
path_obj.relative_to(base_path)
except ValueError:
logger.warning(f"Path traversal attempt blocked: outside allowed directory")
return {
"status": "error",
"message": "Access denied: File must be within allowed directory."
}
# Block access to sensitive system directories
path_str = str(path_obj)
for sensitive_path in SENSITIVE_PATHS:
if path_str.startswith(sensitive_path):
logger.warning(f"Sensitive path access blocked: {sensitive_path}")
return {
"status": "error",
"message": "Access denied: Cannot access system directories."
}
return None # Validation passed
except Exception as e:
logger.error(f"Path validation error: {e}")
return {
"status": "error",
"message": "Invalid file path."
}
def _process_csv_content(
file_path: Path,
max_rows: int,
progress_callback: Optional[Callable[[int, int], None]] = None
) -> ProcessingResult:
"""Process CSV file content with proper encoding handling and streaming.
Args:
file_path (Path): Path object for the CSV file
max_rows (int): Maximum number of rows to process
progress_callback (Optional[Callable]): Progress reporting function
Returns:
ProcessingResult: Result object with processed data or error
"""
file_size = file_path.stat().st_size
# Use streaming for large files to prevent memory exhaustion
if file_size > LARGE_FILE_THRESHOLD:
return _process_csv_streaming(file_path, max_rows, progress_callback)
else:
return _process_csv_standard(file_path, max_rows, progress_callback)
def _process_csv_standard(
file_path: Path,
max_rows: int,
progress_callback: Optional[Callable[[int, int], None]] = None
) -> ProcessingResult:
"""Process small to medium CSV files (< 10MB) by loading into memory.
Args:
file_path (Path): Path object for the CSV file
max_rows (int): Maximum number of rows to process
progress_callback (Optional[Callable]): Progress reporting function
Returns:
ProcessingResult: Result object with processed data or error
"""
# Try UTF-8 first, fallback to latin-1
for encoding in [DEFAULT_ENCODING, FALLBACK_ENCODING]:
try:
with open(file_path, mode='r', newline='', encoding=encoding) as file:
# Detect CSV dialect for better compatibility
dialect = _detect_csv_dialect(file)
reader = csv.DictReader(file, dialect=dialect)
# Process rows
sanitized_rows = []
row_count = 0
sanitized_value_count = 0
sanitized_key_count = 0
for row in reader:
if row_count >= max_rows:
logger.warning(f"Row limit exceeded: {max_rows}")
return ProcessingResult(
status="error",
message=f"Row limit exceeded. Maximum allowed: {max_rows:,} rows"
)
sanitized_row, value_changes, key_changes = _sanitize_row(row)
if sanitized_row: # Only add non-empty rows
sanitized_rows.append(sanitized_row)
sanitized_value_count += value_changes
sanitized_key_count += key_changes
row_count += 1
# Report progress every 1000 rows
if progress_callback and row_count % 1000 == 0:
progress_callback(row_count, max_rows)
# Validate that we have data
if not sanitized_rows:
return ProcessingResult(
status="error",
message="CSV file contains no valid data rows."
)
# Extract column names from first row
columns = list(sanitized_rows[0].keys()) if sanitized_rows else []
return ProcessingResult(
status="success",
data=sanitized_rows,
metadata={
"total_rows": len(sanitized_rows),
"sanitized_values": sanitized_value_count,
"sanitized_keys": sanitized_key_count,
"columns": columns,
"encoding_used": encoding
}
)
except UnicodeDecodeError:
if encoding == FALLBACK_ENCODING:
logger.error("Unable to decode file with UTF-8 or Latin-1")
return ProcessingResult(
status="error",
message="File encoding error. Please ensure the file is UTF-8 or Latin-1 encoded."
)
continue
except csv.Error as e:
logger.error(f"CSV parsing error: {e}")
return ProcessingResult(
status="error",
message="Invalid CSV format. Please check that the file is properly formatted."
)
return ProcessingResult(
status="error",
message="Unable to process file."
)
def _process_csv_streaming(
file_path: Path,
max_rows: int,
progress_callback: Optional[Callable[[int, int], None]] = None
) -> ProcessingResult:
"""Process large CSV files (>= 10MB) using chunked streaming to prevent memory exhaustion.
Args:
file_path (Path): Path object for the CSV file
max_rows (int): Maximum number of rows to process
progress_callback (Optional[Callable]): Progress reporting function
Returns:
ProcessingResult: Result object with processed data or error
"""
for encoding in [DEFAULT_ENCODING, FALLBACK_ENCODING]:
try:
with open(file_path, mode='r', newline='', encoding=encoding) as file:
dialect = _detect_csv_dialect(file)
reader = csv.DictReader(file, dialect=dialect)
# Process in chunks to limit memory usage
chunks = []
current_chunk = []
row_count = 0
sanitized_value_count = 0
sanitized_key_count = 0
for row in reader:
if row_count >= max_rows:
logger.warning(f"Row limit exceeded: {max_rows}")
return ProcessingResult(
status="error",
message=f"Row limit exceeded. Maximum allowed: {max_rows:,} rows"
)
sanitized_row, value_changes, key_changes = _sanitize_row(row)
if sanitized_row:
current_chunk.append(sanitized_row)
sanitized_value_count += value_changes
sanitized_key_count += key_changes
# When chunk is full, store it and start new chunk
if len(current_chunk) >= CHUNK_SIZE:
chunks.append(current_chunk)
current_chunk = []
row_count += 1
# Report progress every 1000 rows
if progress_callback and row_count % 1000 == 0:
progress_callback(row_count, max_rows)
# Add remaining rows
if current_chunk:
chunks.append(current_chunk)
# Flatten chunks
all_rows = [row for chunk in chunks for row in chunk]
if not all_rows:
return ProcessingResult(
status="error",
message="CSV file contains no valid data rows."
)
columns = list(all_rows[0].keys()) if all_rows else []
return ProcessingResult(
status="success",
data=all_rows,
metadata={
"total_rows": len(all_rows),
"sanitized_values": sanitized_value_count,
"sanitized_keys": sanitized_key_count,
"columns": columns,
"encoding_used": encoding,
"processing_mode": "streaming"
}
)
except UnicodeDecodeError:
if encoding == FALLBACK_ENCODING:
logger.error("Unable to decode file with UTF-8 or Latin-1")
return ProcessingResult(
status="error",
message="File encoding error. Please ensure the file is UTF-8 or Latin-1 encoded."
)
continue
except csv.Error as e:
logger.error(f"CSV parsing error: {e}")
return ProcessingResult(
status="error",
message="Invalid CSV format. Please check that the file is properly formatted."
)
return ProcessingResult(
status="error",
message="Unable to process file."
)
def _detect_csv_dialect(file) -> csv.Dialect:
"""Detect CSV dialect with fallback to default.
Args:
file: Open file object
Returns:
csv.Dialect: Detected or default dialect
"""
try:
sample = file.read(8192)
file.seek(0)
dialect = csv.Sniffer().sniff(sample)
return dialect
except csv.Error:
logger.info("CSV dialect detection failed, using default")
file.seek(0)
return csv.excel
def _sanitize_row(row: Dict[str, Any]) -> tuple[Dict[str, Any], int, int]:
"""Sanitize a single CSV row to prevent injection attacks.
Args:
row (Dict[str, Any]): Raw row from CSV reader
Returns:
tuple: (sanitized_row, value_changes_count, key_changes_count)
"""
sanitized_row = {}
value_changes = 0
key_changes = 0
for key, value in row.items():
# Sanitize the key to prevent prototype pollution
clean_key, key_was_changed = _sanitize_key(key)
if not clean_key:
# Skip invalid keys
key_changes += 1
continue
if key_was_changed:
key_changes += 1
# Sanitize the value to prevent CSV injection
clean_value, value_was_changed = _sanitize_value(value)
if value_was_changed:
value_changes += 1
sanitized_row[clean_key] = clean_value
return sanitized_row, value_changes, key_changes
def _sanitize_key(key: str) -> tuple[str, bool]:
"""Sanitize dictionary keys to prevent prototype pollution and injection.
Args:
key (str): Original key from CSV header
Returns:
tuple: (sanitized_key, was_changed)
"""
if not key or not isinstance(key, str):
return "", True
original_key = key
# Remove control characters and limit length
clean_key = ''.join(c for c in key if c.isprintable())[:100]
if not clean_key:
return "", True
# Check for dangerous keys that could cause prototype pollution
if clean_key.lower() in DANGEROUS_KEYS:
clean_key = f"sanitized_{clean_key}"
# Ensure key doesn't start with special characters that could cause issues
if clean_key[0] in ('$', '_', '.'):
clean_key = 'field_' + clean_key
return clean_key, clean_key != original_key
def _sanitize_value(value: Any) -> tuple[Any, bool]:
"""Sanitize cell values to prevent CSV injection attacks.
CSV injection occurs when spreadsheet applications interpret cell values
starting with =, +, -, @, \t, or \r as formulas. This function also checks
for dangerous formula patterns anywhere in the string.
Args:
value (Any): Original cell value
Returns:
tuple: (sanitized_value, was_changed)
"""
if not isinstance(value, str):
return value, False
if not value:
return value, False
# Strip leading whitespace to detect hidden injection attempts
stripped_value = value.lstrip()
if not stripped_value:
return value, False
# Check if value starts with dangerous characters (after stripping whitespace)
if stripped_value[0] in CSV_INJECTION_CHARS:
# Prefix with single quote and escape existing quotes
sanitized = "'" + value.replace("'", "''")
logger.debug("CSV injection character detected and sanitized")
return sanitized, True
# Additional check: detect dangerous formula patterns anywhere in string
value_upper = value.upper()
for pattern in DANGEROUS_FORMULA_PATTERNS:
if pattern in value_upper:
# Prefix with single quote and escape existing quotes
sanitized = "'" + value.replace("'", "''")
logger.warning(f"Potential formula injection pattern detected: {pattern}")
return sanitized, True
return value, False
def _result_to_dict(result: ProcessingResult) -> dict:
"""Convert ProcessingResult to dictionary format.
Args:
result (ProcessingResult): Processing result object
Returns:
dict: Dictionary representation of the result
"""
response = {"status": result.status}
if result.status == "success":
response["data"] = result.data
if result.metadata:
response["metadata"] = result.metadata
else:
response["message"] = result.message
return response
def convert_to_json_string(
file_path: str,
max_rows: int = MAX_ROWS,
indent: int = 2,
allowed_base_dir: Optional[str] = None,
progress_callback: Optional[Callable[[int, int], None]] = None
) -> dict:
"""Process CSV file and return JSON as a formatted string.
This is a convenience function for cases where JSON string output is needed.
Args:
file_path (str): Path to the CSV file
max_rows (int): Maximum number of rows to process
indent (int): JSON indentation level (default: 2)
allowed_base_dir (Optional[str]): Base directory to restrict file access
progress_callback (Optional[Callable]): Progress reporting function
Returns:
dict: Result with JSON string in 'json_output' field
"""
result = process_csv_file(file_path, max_rows, allowed_base_dir, progress_callback)
if result["status"] == "success":
try:
json_string = json.dumps(
result["data"],
ensure_ascii=False,
indent=indent
)
return {
"status": "success",
"json_output": json_string,
"metadata": result.get("metadata")
}
except (TypeError, ValueError) as e:
logger.error(f"JSON serialization error: {e}")
return {
"status": "error",
"message": "Unable to serialize data to JSON format."
}
return result |