Spaces:
Paused
Paused
Download shared/validation.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 24.3 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/validation.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/shared/validation.py
-
curl -L -o validation.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/shared/validation.py
24.3 kB
| """ | |
| Comprehensive input validation for MCP AI Data Scientist system. | |
| Provides validation schemas and utilities for all API endpoints and MCP tools. | |
| """ | |
| import re | |
| import mimetypes | |
| from typing import Any, Dict, List, Optional, Union | |
| from pathlib import Path | |
| from .error_handling import ( | |
| InputValidator, ValidationRule, RequiredRule, TypeRule, | |
| RangeRule, LengthRule, PatternRule, EmailRule, FileExtensionRule, | |
| ValidationError, ErrorContext | |
| ) | |
| class FileSizeRule(ValidationRule): | |
| """Validates file size in bytes.""" | |
| def __init__(self, field_name: str, max_size_bytes: int, error_message: str = None): | |
| self.max_size_bytes = max_size_bytes | |
| super().__init__(field_name, error_message) | |
| def validate(self, value: Any) -> bool: | |
| if value is None: | |
| return True | |
| if isinstance(value, int): | |
| return value <= self.max_size_bytes | |
| elif isinstance(value, bytes): | |
| return len(value) <= self.max_size_bytes | |
| elif hasattr(value, '__len__'): | |
| return len(value) <= self.max_size_bytes | |
| return False | |
| def get_error_message(self, value: Any) -> str: | |
| max_mb = self.max_size_bytes / (1024 * 1024) | |
| return f"{self.field_name} size must not exceed {max_mb:.1f}MB" | |
| class MimeTypeRule(ValidationRule): | |
| """Validates file MIME type.""" | |
| def __init__(self, field_name: str, allowed_types: List[str], error_message: str = None): | |
| self.allowed_types = allowed_types | |
| super().__init__(field_name, error_message) | |
| def validate(self, value: Any) -> bool: | |
| if value is None or not isinstance(value, str): | |
| return True | |
| mime_type, _ = mimetypes.guess_type(value) | |
| return mime_type in self.allowed_types if mime_type else False | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} must be one of these types: {', '.join(self.allowed_types)}" | |
| class JSONRule(ValidationRule): | |
| """Validates JSON string format.""" | |
| def validate(self, value: Any) -> bool: | |
| if value is None: | |
| return True | |
| if not isinstance(value, str): | |
| return False | |
| try: | |
| import json | |
| json.loads(value) | |
| return True | |
| except (json.JSONDecodeError, ValueError): | |
| return False | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} must be valid JSON" | |
| class UUIDRule(ValidationRule): | |
| """Validates UUID format.""" | |
| def validate(self, value: Any) -> bool: | |
| if value is None: | |
| return True | |
| if not isinstance(value, str): | |
| return False | |
| try: | |
| from uuid import UUID | |
| UUID(value) | |
| return True | |
| except ValueError: | |
| return False | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} must be a valid UUID" | |
| class BusinessContextRule(ValidationRule): | |
| """Validates business context content.""" | |
| def __init__(self, field_name: str, min_words: int = 5, max_words: int = 1000): | |
| self.min_words = min_words | |
| self.max_words = max_words | |
| super().__init__(field_name) | |
| def validate(self, value: Any) -> bool: | |
| if value is None or not isinstance(value, str): | |
| return False | |
| words = value.strip().split() | |
| return self.min_words <= len(words) <= self.max_words | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} must contain between {self.min_words} and {self.max_words} words" | |
| class AnalysisParametersRule(ValidationRule): | |
| """Validates analysis parameters JSON.""" | |
| def validate(self, value: Any) -> bool: | |
| if value is None: | |
| return True | |
| if isinstance(value, dict): | |
| # Already parsed | |
| return self._validate_parameters_dict(value) | |
| if isinstance(value, str): | |
| try: | |
| import json | |
| params = json.loads(value) | |
| return self._validate_parameters_dict(params) | |
| except (json.JSONDecodeError, ValueError): | |
| return False | |
| return False | |
| def _validate_parameters_dict(self, params: dict) -> bool: | |
| """Validate parameters dictionary structure.""" | |
| allowed_keys = { | |
| 'target_column', 'test_size', 'random_state', 'cv_folds', | |
| 'max_features', 'feature_selection_method', 'scaling_method', | |
| 'handle_missing', 'outlier_method', 'confidence_level' | |
| } | |
| # Check for unknown keys | |
| unknown_keys = set(params.keys()) - allowed_keys | |
| if unknown_keys: | |
| return False | |
| # Validate specific parameter types and ranges | |
| if 'test_size' in params: | |
| test_size = params['test_size'] | |
| if not isinstance(test_size, (int, float)) or not (0.1 <= test_size <= 0.5): | |
| return False | |
| if 'cv_folds' in params: | |
| cv_folds = params['cv_folds'] | |
| if not isinstance(cv_folds, int) or not (2 <= cv_folds <= 10): | |
| return False | |
| if 'confidence_level' in params: | |
| confidence = params['confidence_level'] | |
| if not isinstance(confidence, (int, float)) or not (0.8 <= confidence <= 0.99): | |
| return False | |
| return True | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} contains invalid analysis parameters" | |
| class DatasetContentRule(ValidationRule): | |
| """Validates dataset content structure and quality.""" | |
| def __init__(self, field_name: str, min_rows: int = 10, min_columns: int = 2, max_size_mb: int = 100): | |
| self.min_rows = min_rows | |
| self.min_columns = min_columns | |
| self.max_size_mb = max_size_mb | |
| super().__init__(field_name) | |
| def validate(self, value: Any) -> bool: | |
| if value is None: | |
| return True | |
| # Expect a dictionary with dataset info | |
| if not isinstance(value, dict): | |
| return False | |
| rows = value.get('rows', 0) | |
| columns = value.get('columns', 0) | |
| size_mb = value.get('size_mb', 0) | |
| if rows < self.min_rows: | |
| return False | |
| if columns < self.min_columns: | |
| return False | |
| if size_mb > self.max_size_mb: | |
| return False | |
| return True | |
| def get_error_message(self, value: Any) -> str: | |
| if isinstance(value, dict): | |
| rows = value.get('rows', 0) | |
| columns = value.get('columns', 0) | |
| size_mb = value.get('size_mb', 0) | |
| if rows < self.min_rows: | |
| return f"Dataset must have at least {self.min_rows} rows, got {rows}" | |
| if columns < self.min_columns: | |
| return f"Dataset must have at least {self.min_columns} columns, got {columns}" | |
| if size_mb > self.max_size_mb: | |
| return f"Dataset size must not exceed {self.max_size_mb}MB, got {size_mb}MB" | |
| return f"{self.field_name} contains invalid dataset structure" | |
| class SQLInjectionRule(ValidationRule): | |
| """Validates input against SQL injection patterns.""" | |
| def __init__(self, field_name: str): | |
| # Common SQL injection patterns | |
| self.dangerous_patterns = [ | |
| r"(\b(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC|EXECUTE)\b)", | |
| r"(--|#|/\*|\*/)", | |
| r"(\b(UNION|OR|AND)\b.*\b(SELECT|INSERT|UPDATE|DELETE)\b)", | |
| r"(\b(SCRIPT|JAVASCRIPT|VBSCRIPT)\b)", | |
| r"(<script|<iframe|<object|<embed)", | |
| ] | |
| super().__init__(field_name) | |
| def validate(self, value: Any) -> bool: | |
| if value is None or not isinstance(value, str): | |
| return True | |
| value_upper = value.upper() | |
| for pattern in self.dangerous_patterns: | |
| if re.search(pattern, value_upper, re.IGNORECASE): | |
| return False | |
| return True | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} contains potentially dangerous content" | |
| class XSSRule(ValidationRule): | |
| """Validates input against XSS (Cross-Site Scripting) patterns.""" | |
| def __init__(self, field_name: str): | |
| # Common XSS patterns | |
| self.xss_patterns = [ | |
| r"<script[^>]*>.*?</script>", | |
| r"javascript:", | |
| r"vbscript:", | |
| r"onload\s*=", | |
| r"onerror\s*=", | |
| r"onclick\s*=", | |
| r"onmouseover\s*=", | |
| r"<iframe[^>]*>", | |
| r"<object[^>]*>", | |
| r"<embed[^>]*>", | |
| ] | |
| super().__init__(field_name) | |
| def validate(self, value: Any) -> bool: | |
| if value is None or not isinstance(value, str): | |
| return True | |
| for pattern in self.xss_patterns: | |
| if re.search(pattern, value, re.IGNORECASE): | |
| return False | |
| return True | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} contains potentially malicious script content" | |
| class PathTraversalRule(ValidationRule): | |
| """Validates input against path traversal attacks.""" | |
| def validate(self, value: Any) -> bool: | |
| if value is None or not isinstance(value, str): | |
| return True | |
| # Check for path traversal patterns | |
| dangerous_patterns = [ | |
| "..", | |
| "~", | |
| "/etc/", | |
| "/proc/", | |
| "/sys/", | |
| "\\windows\\", | |
| "\\system32\\", | |
| "%2e%2e", # URL encoded .. | |
| "%2f", # URL encoded / | |
| "%5c", # URL encoded \ | |
| ] | |
| value_lower = value.lower() | |
| for pattern in dangerous_patterns: | |
| if pattern in value_lower: | |
| return False | |
| return True | |
| def get_error_message(self, value: Any) -> str: | |
| return f"{self.field_name} contains invalid path characters" | |
| # Validation schemas for different endpoints | |
| class ValidationSchemas: | |
| """Pre-defined validation schemas for common use cases.""" | |
| def get_file_upload_validator() -> InputValidator: | |
| """Validator for file upload endpoints.""" | |
| validator = InputValidator() | |
| # File validation | |
| validator.add_rules("filename", [ | |
| RequiredRule("filename"), | |
| TypeRule("filename", str), | |
| LengthRule("filename", min_length=1, max_length=255), | |
| FileExtensionRule("filename", ['.csv', '.xlsx', '.xls', '.json', '.parquet']) | |
| ]) | |
| # File size validation (100MB limit) | |
| validator.add_rule("file_size", FileSizeRule("file_size", 100 * 1024 * 1024)) | |
| # Business context validation | |
| validator.add_rules("business_context", [ | |
| RequiredRule("business_context"), | |
| TypeRule("business_context", str), | |
| BusinessContextRule("business_context") | |
| ]) | |
| # Optional analysis name | |
| validator.add_rules("analysis_name", [ | |
| TypeRule("analysis_name", str), | |
| LengthRule("analysis_name", max_length=200) | |
| ]) | |
| # Optional parameters | |
| validator.add_rule("parameters", AnalysisParametersRule("parameters")) | |
| return validator | |
| def get_session_id_validator() -> InputValidator: | |
| """Validator for session ID parameters.""" | |
| validator = InputValidator() | |
| validator.add_rules("session_id", [ | |
| RequiredRule("session_id"), | |
| TypeRule("session_id", str), | |
| UUIDRule("session_id") | |
| ]) | |
| return validator | |
| def get_dataset_id_validator() -> InputValidator: | |
| """Validator for dataset ID parameters.""" | |
| validator = InputValidator() | |
| validator.add_rules("dataset_id", [ | |
| RequiredRule("dataset_id"), | |
| TypeRule("dataset_id", str), | |
| UUIDRule("dataset_id") | |
| ]) | |
| return validator | |
| def get_pagination_validator() -> InputValidator: | |
| """Validator for pagination parameters.""" | |
| validator = InputValidator() | |
| validator.add_rules("limit", [ | |
| TypeRule("limit", int), | |
| RangeRule("limit", min_val=1, max_val=100) | |
| ]) | |
| validator.add_rules("offset", [ | |
| TypeRule("offset", int), | |
| RangeRule("offset", min_val=0) | |
| ]) | |
| return validator | |
| def get_data_cleaning_validator() -> InputValidator: | |
| """Validator for data cleaning operations.""" | |
| validator = InputValidator() | |
| validator.add_rules("dataset_id", [ | |
| RequiredRule("dataset_id"), | |
| TypeRule("dataset_id", str), | |
| UUIDRule("dataset_id") | |
| ]) | |
| # Operations validation would be more complex | |
| validator.add_rules("operations", [ | |
| RequiredRule("operations"), | |
| TypeRule("operations", list) | |
| ]) | |
| return validator | |
| def get_hypothesis_testing_validator() -> InputValidator: | |
| """Validator for hypothesis testing parameters.""" | |
| validator = InputValidator() | |
| validator.add_rules("dataset_id", [ | |
| RequiredRule("dataset_id"), | |
| TypeRule("dataset_id", str), | |
| UUIDRule("dataset_id") | |
| ]) | |
| validator.add_rules("business_context", [ | |
| RequiredRule("business_context"), | |
| TypeRule("business_context", str), | |
| BusinessContextRule("business_context") | |
| ]) | |
| return validator | |
| def get_model_training_validator() -> InputValidator: | |
| """Validator for model training parameters.""" | |
| validator = InputValidator() | |
| validator.add_rules("dataset_id", [ | |
| RequiredRule("dataset_id"), | |
| TypeRule("dataset_id", str), | |
| UUIDRule("dataset_id") | |
| ]) | |
| validator.add_rules("target_column", [ | |
| RequiredRule("target_column"), | |
| TypeRule("target_column", str), | |
| LengthRule("target_column", min_length=1, max_length=100), | |
| SQLInjectionRule("target_column"), | |
| PathTraversalRule("target_column") | |
| ]) | |
| return validator | |
| def get_secure_input_validator() -> InputValidator: | |
| """Validator for general secure input validation.""" | |
| validator = InputValidator() | |
| # Common security validations | |
| validator.add_rules("user_input", [ | |
| TypeRule("user_input", str), | |
| LengthRule("user_input", max_length=10000), | |
| SQLInjectionRule("user_input"), | |
| XSSRule("user_input"), | |
| PathTraversalRule("user_input") | |
| ]) | |
| return validator | |
| def get_api_key_validator() -> InputValidator: | |
| """Validator for API keys and tokens.""" | |
| validator = InputValidator() | |
| validator.add_rules("api_key", [ | |
| RequiredRule("api_key"), | |
| TypeRule("api_key", str), | |
| LengthRule("api_key", min_length=10, max_length=500), | |
| PatternRule("api_key", r"^[A-Za-z0-9\-_\.]+$") | |
| ]) | |
| return validator | |
| def get_comprehensive_file_validator() -> InputValidator: | |
| """Enhanced validator for file uploads with security checks.""" | |
| validator = InputValidator() | |
| # Enhanced file validation | |
| validator.add_rules("filename", [ | |
| RequiredRule("filename"), | |
| TypeRule("filename", str), | |
| LengthRule("filename", min_length=1, max_length=255), | |
| FileExtensionRule("filename", ['.csv', '.xlsx', '.xls', '.json', '.parquet']), | |
| PathTraversalRule("filename"), | |
| PatternRule("filename", r"^[a-zA-Z0-9\-_\.\s]+$") # Safe characters only | |
| ]) | |
| # File size validation (100MB limit) | |
| validator.add_rule("file_size", FileSizeRule("file_size", 100 * 1024 * 1024)) | |
| # MIME type validation | |
| validator.add_rule("mime_type", MimeTypeRule("mime_type", [ | |
| 'text/csv', | |
| 'application/vnd.ms-excel', | |
| 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', | |
| 'application/json', | |
| 'application/octet-stream' # For parquet files | |
| ])) | |
| # Business context validation with security | |
| validator.add_rules("business_context", [ | |
| RequiredRule("business_context"), | |
| TypeRule("business_context", str), | |
| BusinessContextRule("business_context"), | |
| XSSRule("business_context"), | |
| SQLInjectionRule("business_context") | |
| ]) | |
| # Dataset content validation | |
| validator.add_rule("dataset_content", DatasetContentRule("dataset_content")) | |
| return validator | |
| # Validation decorators for FastAPI endpoints | |
| def validate_request_data(validator: InputValidator): | |
| """Decorator to validate request data.""" | |
| def decorator(func): | |
| async def wrapper(*args, **kwargs): | |
| # Extract request data from kwargs | |
| request_data = {} | |
| # Common parameter extraction | |
| for key in ['file', 'business_context', 'analysis_name', 'parameters', | |
| 'session_id', 'dataset_id', 'limit', 'offset']: | |
| if key in kwargs: | |
| request_data[key] = kwargs[key] | |
| # Special handling for file uploads | |
| if 'file' in kwargs and hasattr(kwargs['file'], 'filename'): | |
| request_data['filename'] = kwargs['file'].filename | |
| if hasattr(kwargs['file'], 'size'): | |
| request_data['file_size'] = kwargs['file'].size | |
| # Validate the data | |
| try: | |
| validator.validate_and_raise(request_data) | |
| except ValidationError as e: | |
| from fastapi import HTTPException | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| return await func(*args, **kwargs) | |
| return wrapper | |
| return decorator | |
| # Utility functions for validation | |
| def validate_file_content(file_content: bytes, filename: str) -> List[str]: | |
| """Validate file content integrity.""" | |
| issues = [] | |
| # Check if file is empty | |
| if len(file_content) == 0: | |
| issues.append("File is empty") | |
| return issues | |
| # Check file extension and try to validate content | |
| file_ext = Path(filename).suffix.lower() | |
| if file_ext == '.csv': | |
| issues.extend(_validate_csv_content(file_content)) | |
| elif file_ext in ['.xlsx', '.xls']: | |
| issues.extend(_validate_excel_content(file_content)) | |
| elif file_ext == '.json': | |
| issues.extend(_validate_json_content(file_content)) | |
| elif file_ext == '.parquet': | |
| issues.extend(_validate_parquet_content(file_content)) | |
| return issues | |
| def _validate_csv_content(file_content: bytes) -> List[str]: | |
| """Validate CSV file content.""" | |
| issues = [] | |
| try: | |
| import pandas as pd | |
| import io | |
| # Try to read as CSV | |
| df = pd.read_csv(io.BytesIO(file_content)) | |
| if df.empty: | |
| issues.append("CSV file contains no data") | |
| elif len(df.columns) == 0: | |
| issues.append("CSV file contains no columns") | |
| except Exception as e: | |
| issues.append(f"Invalid CSV format: {str(e)}") | |
| return issues | |
| def _validate_excel_content(file_content: bytes) -> List[str]: | |
| """Validate Excel file content.""" | |
| issues = [] | |
| try: | |
| import pandas as pd | |
| import io | |
| # Try to read as Excel | |
| df = pd.read_excel(io.BytesIO(file_content)) | |
| if df.empty: | |
| issues.append("Excel file contains no data") | |
| elif len(df.columns) == 0: | |
| issues.append("Excel file contains no columns") | |
| except Exception as e: | |
| issues.append(f"Invalid Excel format: {str(e)}") | |
| return issues | |
| def _validate_json_content(file_content: bytes) -> List[str]: | |
| """Validate JSON file content.""" | |
| issues = [] | |
| try: | |
| import json | |
| import pandas as pd | |
| # Try to parse JSON | |
| json_data = json.loads(file_content.decode('utf-8')) | |
| # Try to convert to DataFrame | |
| df = pd.DataFrame(json_data) | |
| if df.empty: | |
| issues.append("JSON file contains no data") | |
| except json.JSONDecodeError as e: | |
| issues.append(f"Invalid JSON format: {str(e)}") | |
| except Exception as e: | |
| issues.append(f"Cannot convert JSON to tabular data: {str(e)}") | |
| return issues | |
| def _validate_parquet_content(file_content: bytes) -> List[str]: | |
| """Validate Parquet file content.""" | |
| issues = [] | |
| try: | |
| import pandas as pd | |
| import io | |
| # Try to read as Parquet | |
| df = pd.read_parquet(io.BytesIO(file_content)) | |
| if df.empty: | |
| issues.append("Parquet file contains no data") | |
| elif len(df.columns) == 0: | |
| issues.append("Parquet file contains no columns") | |
| except Exception as e: | |
| issues.append(f"Invalid Parquet format: {str(e)}") | |
| return issues | |
| def sanitize_filename(filename: str) -> str: | |
| """Sanitize filename to prevent path traversal and other issues.""" | |
| # Remove path components | |
| filename = Path(filename).name | |
| # Remove or replace dangerous characters | |
| filename = re.sub(r'[<>:"/\\|?*]', '_', filename) | |
| # Limit length | |
| if len(filename) > 255: | |
| name, ext = Path(filename).stem, Path(filename).suffix | |
| max_name_length = 255 - len(ext) | |
| filename = name[:max_name_length] + ext | |
| return filename | |
| def validate_column_names(column_names: List[str]) -> List[str]: | |
| """Validate DataFrame column names.""" | |
| issues = [] | |
| # Check for empty column names | |
| empty_columns = [i for i, name in enumerate(column_names) if not str(name).strip()] | |
| if empty_columns: | |
| issues.append(f"Empty column names at positions: {empty_columns}") | |
| # Check for duplicate column names | |
| seen = set() | |
| duplicates = [] | |
| for name in column_names: | |
| if name in seen: | |
| duplicates.append(name) | |
| seen.add(name) | |
| if duplicates: | |
| issues.append(f"Duplicate column names: {duplicates}") | |
| # Check for problematic column names | |
| problematic = [] | |
| for name in column_names: | |
| name_str = str(name).strip() | |
| if len(name_str) > 100: | |
| problematic.append(f"'{name_str[:20]}...' (too long)") | |
| elif name_str.startswith(('_', ' ')) or name_str.endswith(('_', ' ')): | |
| problematic.append(f"'{name_str}' (starts/ends with underscore or space)") | |
| if problematic: | |
| issues.append(f"Problematic column names: {problematic}") | |
| return issues |