File size: 24,339 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
"""

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."""
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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
    
    @staticmethod
    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