"""
Comprehensive security tests for the MCP AI Data Scientist system.
Tests file upload security, SQL injection prevention, rate limiting, and audit logging.
"""
import pytest
import asyncio
import tempfile
import os
import time
from pathlib import Path
from unittest.mock import Mock, patch, AsyncMock
from datetime import datetime, timedelta
from shared.security import (
FileSecurityValidator, SQLInjectionPrevention, RateLimiter,
SecureFileStorage, SecurityAuditLogger, FileValidationResult
)
from shared.security_middleware import SecurityMiddleware
from shared.secure_endpoints import router
from fastapi.testclient import TestClient
from fastapi import FastAPI
# Test data
MALICIOUS_CSV = b"""name,email,command
John,john@test.com,=cmd|'/c calc'
Jane,jane@test.com,normal_data
Bob,bob@test.com,@SUM(1+1)*cmd|'/c notepad'"""
CLEAN_CSV = b"""name,email,age
John,john@test.com,25
Jane,jane@test.com,30
Bob,bob@test.com,35"""
EXECUTABLE_CONTENT = b'MZ\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00'
SQL_INJECTION_PAYLOADS = [
"'; DROP TABLE users; --",
"1' OR '1'='1",
"admin'/*",
"1; SELECT * FROM information_schema.tables",
"UNION SELECT username, password FROM users",
"'; EXEC xp_cmdshell('dir'); --"
]
class TestFileSecurityValidator:
"""Test file upload security validation."""
@pytest.fixture
def validator(self):
return FileSecurityValidator()
@pytest.mark.asyncio
async def test_valid_csv_file(self, validator):
"""Test validation of clean CSV file."""
result = await validator.validate_file(CLEAN_CSV, "test.csv", "user123")
assert result.is_valid
assert result.file_type == "text/csv"
assert len(result.threats_detected) == 0
assert result.size_bytes == len(CLEAN_CSV)
@pytest.mark.asyncio
async def test_malicious_csv_file(self, validator):
"""Test detection of formula injection in CSV."""
result = await validator.validate_file(MALICIOUS_CSV, "malicious.csv", "user123")
assert not result.is_valid
assert any("formula injection" in threat.lower() for threat in result.threats_detected)
@pytest.mark.asyncio
async def test_executable_file_detection(self, validator):
"""Test detection of executable files."""
result = await validator.validate_file(EXECUTABLE_CONTENT, "malware.exe", "user123")
assert not result.is_valid
assert any("executable" in threat.lower() for threat in result.threats_detected)
@pytest.mark.asyncio
async def test_file_size_limit(self, validator):
"""Test file size limit enforcement."""
large_content = b'x' * (validator.MAX_FILE_SIZE + 1)
result = await validator.validate_file(large_content, "large.csv", "user123")
assert not result.is_valid
assert any("size" in threat.lower() for threat in result.threats_detected)
@pytest.mark.asyncio
async def test_empty_file_rejection(self, validator):
"""Test rejection of empty files."""
result = await validator.validate_file(b'', "empty.csv", "user123")
assert not result.is_valid
assert any("empty" in threat.lower() for threat in result.threats_detected)
@pytest.mark.asyncio
async def test_dangerous_file_extensions(self, validator):
"""Test rejection of dangerous file extensions."""
for ext in ['.exe', '.bat', '.cmd', '.scr', '.vbs']:
result = await validator.validate_file(b'test content', f"file{ext}", "user123")
assert not result.is_valid
assert any("dangerous" in threat.lower() for threat in result.threats_detected)
@pytest.mark.asyncio
async def test_mime_type_validation(self, validator):
"""Test MIME type validation."""
# Test with content that doesn't match allowed types
html_content = b''
result = await validator.validate_file(html_content, "test.html", "user123")
assert not result.is_valid
assert any("not allowed" in threat.lower() for threat in result.threats_detected)
@pytest.mark.asyncio
async def test_suspicious_content_patterns(self, validator):
"""Test detection of suspicious content patterns."""
suspicious_content = b''
result = await validator.validate_file(suspicious_content, "test.txt", "user123")
assert not result.is_valid
assert any("suspicious" in threat.lower() for threat in result.threats_detected)
class TestSQLInjectionPrevention:
"""Test SQL injection prevention mechanisms."""
def test_sql_injection_detection(self):
"""Test detection of various SQL injection patterns."""
for payload in SQL_INJECTION_PAYLOADS:
is_safe, threats = SQLInjectionPrevention.validate_input(payload, "test_field")
assert not is_safe, f"Failed to detect SQL injection: {payload}"
assert len(threats) > 0
def test_clean_input_validation(self):
"""Test validation of clean input."""
clean_inputs = [
"john@example.com",
"Normal text input",
"123456",
"Product Name - Version 1.0"
]
for clean_input in clean_inputs:
is_safe, threats = SQLInjectionPrevention.validate_input(clean_input, "test_field")
assert is_safe, f"False positive for clean input: {clean_input}"
assert len(threats) == 0
def test_input_sanitization(self):
"""Test input sanitization functionality."""
malicious_input = "'; DROP TABLE users; -- comment"
sanitized = SQLInjectionPrevention.sanitize_input(malicious_input)
assert "--" not in sanitized
assert len(sanitized) <= 1000
def test_null_byte_detection(self):
"""Test detection of null byte injection."""
null_byte_input = "normal_input\x00malicious_part"
is_safe, threats = SQLInjectionPrevention.validate_input(null_byte_input, "test_field")
assert not is_safe
assert any("null byte" in threat.lower() for threat in threats)
def test_excessive_length_detection(self):
"""Test detection of excessively long input."""
long_input = "x" * 15000
is_safe, threats = SQLInjectionPrevention.validate_input(long_input, "test_field")
assert not is_safe
assert any("too long" in threat.lower() for threat in threats)
class TestRateLimiter:
"""Test rate limiting and DDoS protection."""
@pytest.fixture
def rate_limiter(self):
limiter = RateLimiter()
# Reset for testing
limiter.requests.clear()
limiter.blocked_ips.clear()
return limiter
def test_normal_request_rate(self, rate_limiter):
"""Test normal request rate is allowed."""
ip = "192.168.1.1"
# Make normal number of requests
for _ in range(10):
is_allowed, reason = rate_limiter.is_allowed(ip)
assert is_allowed, f"Normal request blocked: {reason}"
def test_rate_limit_enforcement(self, rate_limiter):
"""Test rate limit enforcement."""
ip = "192.168.1.2"
# Exceed per-minute limit
for _ in range(rate_limiter.limits['per_minute'] + 5):
rate_limiter.is_allowed(ip)
# Next request should be blocked
is_allowed, reason = rate_limiter.is_allowed(ip)
assert not is_allowed
assert "rate limit exceeded" in reason.lower()
def test_ip_blocking_duration(self, rate_limiter):
"""Test IP blocking duration."""
ip = "192.168.1.3"
# Trigger rate limit
for _ in range(rate_limiter.limits['per_minute'] + 1):
rate_limiter.is_allowed(ip)
# Should be blocked
is_allowed, reason = rate_limiter.is_allowed(ip)
assert not is_allowed
# Check that IP is in blocked list
assert ip in rate_limiter.blocked_ips
def test_different_ips_isolated(self, rate_limiter):
"""Test that different IPs are isolated."""
ip1 = "192.168.1.4"
ip2 = "192.168.1.5"
# Exhaust limit for IP1
for _ in range(rate_limiter.limits['per_minute'] + 1):
rate_limiter.is_allowed(ip1)
# IP1 should be blocked
is_allowed, _ = rate_limiter.is_allowed(ip1)
assert not is_allowed
# IP2 should still be allowed
is_allowed, _ = rate_limiter.is_allowed(ip2)
assert is_allowed
def test_old_requests_cleanup(self, rate_limiter):
"""Test cleanup of old requests."""
ip = "192.168.1.6"
# Add old request (simulate by manipulating time)
old_time = time.time() - 90000 # 25 hours ago
rate_limiter.requests[ip].append(old_time)
# Make new request
rate_limiter.is_allowed(ip)
# Old request should be cleaned up
assert old_time not in rate_limiter.requests[ip]
class TestSecureFileStorage:
"""Test secure file storage with access controls."""
@pytest.fixture
def storage(self):
with tempfile.TemporaryDirectory() as temp_dir:
yield SecureFileStorage(temp_dir)
def test_user_directory_isolation(self, storage):
"""Test user directory isolation."""
user1_dir = storage.get_user_directory("user1")
user2_dir = storage.get_user_directory("user2")
assert user1_dir != user2_dir
assert user1_dir.exists()
assert user2_dir.exists()
def test_file_storage_and_retrieval(self, storage):
"""Test secure file storage and retrieval."""
user_id = "test_user"
filename = "test.csv"
content = b"test,data\n1,2\n3,4"
# Store file
stored_path = storage.store_file(user_id, filename, content)
assert stored_path
# Retrieve file
retrieved_content = storage.get_file(user_id, stored_path)
assert retrieved_content == content
def test_cross_user_access_prevention(self, storage):
"""Test prevention of cross-user file access."""
user1_id = "user1"
user2_id = "user2"
filename = "secret.csv"
content = b"secret,data"
# User1 stores file
stored_path = storage.store_file(user1_id, filename, content)
# User2 tries to access user1's file
with pytest.raises(PermissionError):
storage.get_file(user2_id, stored_path)
def test_filename_sanitization(self, storage):
"""Test filename sanitization."""
user_id = "test_user"
dangerous_filename = "../../../etc/passwd"
content = b"test content"
stored_path = storage.store_file(user_id, dangerous_filename, content)
# Should not contain path traversal
assert "../" not in stored_path
assert stored_path.startswith(user_id)
def test_file_deletion(self, storage):
"""Test secure file deletion."""
user_id = "test_user"
filename = "delete_me.csv"
content = b"temporary content"
# Store and delete file
stored_path = storage.store_file(user_id, filename, content)
deleted = storage.delete_file(user_id, stored_path)
assert deleted
# File should no longer exist
with pytest.raises(FileNotFoundError):
storage.get_file(user_id, stored_path)
def test_invalid_user_id_rejection(self, storage):
"""Test rejection of invalid user IDs."""
invalid_user_ids = [
"../admin",
"user/with/slashes",
"user.csv",
"javascript:alert('xss').csv",
"data:text/html,.csv"
]
storage = SecureFileStorage()
for xss_filename in xss_filenames:
sanitized = storage._sanitize_filename(xss_filename)
# Should not contain dangerous characters
assert "<" not in sanitized
assert ">" not in sanitized
assert "javascript:" not in sanitized
@pytest.mark.asyncio
async def test_polyglot_file_detection(self, validator):
"""Test detection of polyglot files (files that are valid in multiple formats)."""
# A file that could be both a CSV and contain executable code
polyglot_content = b'''name,email
John,john@test.com'''
result = await validator.validate_file(polyglot_content, "polyglot.csv", "user123")
# Should detect suspicious content
assert not result.is_valid
assert len(result.threats_detected) > 0
if __name__ == "__main__":
pytest.main([__file__, "-v"])