Spaces:
Sleeping
Sleeping
Download processing_result.py from tekodu/bauform-tool-b68a2016d8ca: direct link, hf CLI and curl.
- Browser
- Download file 24.6 kB
-
https://huggingface.co/spaces/tekodu/bauform-tool-b68a2016d8ca/resolve/main/processing_result.py
- Command line
-
hf download hf://spaces/tekodu/bauform-tool-b68a2016d8ca/processing_result.py
-
curl -L -o processing_result.py https://huggingface.co/spaces/tekodu/bauform-tool-b68a2016d8ca/resolve/main/processing_result.py
24.6 kB
| # 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() | |
| 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 |