""" Basic security tests to validate core functionality. """ import pytest import tempfile import os from pathlib import Path def test_sql_injection_prevention(): """Test basic SQL injection prevention.""" from shared.security import SQLInjectionPrevention # Test malicious input malicious_input = "'; DROP TABLE users; --" is_safe, threats = SQLInjectionPrevention.validate_input(malicious_input, "test_field") assert not is_safe assert len(threats) > 0 assert any("SQL" in threat or "injection" in threat for threat in threats) def test_sql_injection_clean_input(): """Test that clean input passes validation.""" from shared.security import SQLInjectionPrevention # Test clean input clean_input = "john@example.com" is_safe, threats = SQLInjectionPrevention.validate_input(clean_input, "email") assert is_safe assert len(threats) == 0 def test_rate_limiter_basic(): """Test basic rate limiting functionality.""" from shared.security import RateLimiter rate_limiter = RateLimiter() rate_limiter.requests.clear() rate_limiter.blocked_ips.clear() ip = "192.168.1.100" # Normal requests should be allowed for _ in range(10): is_allowed, reason = rate_limiter.is_allowed(ip) assert is_allowed, f"Normal request blocked: {reason}" def test_secure_file_storage(): """Test secure file storage functionality.""" from shared.security import SecureFileStorage with tempfile.TemporaryDirectory() as temp_dir: storage = SecureFileStorage(temp_dir) 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_filename_sanitization(): """Test filename sanitization.""" from shared.security import SecureFileStorage storage = SecureFileStorage() # Test dangerous filename dangerous_filename = "../../../etc/passwd" safe_filename = storage._sanitize_filename(dangerous_filename) assert "../" not in safe_filename assert safe_filename != dangerous_filename def test_security_audit_logger(): """Test security audit logging.""" from shared.security import SecurityAuditLogger, SecurityEvent from datetime import datetime # Use a simple test that doesn't require file cleanup temp_log = "test_security_audit.log" try: audit_logger = SecurityAuditLogger(temp_log) # Log authentication event audit_logger.log_authentication_event("test_user", "192.168.1.1", True) # Close the logger to release file handle for handler in audit_logger.logger.handlers[:]: handler.close() audit_logger.logger.removeHandler(handler) # Check log file exists and has content assert Path(temp_log).exists() log_content = Path(temp_log).read_text() assert "test_user" in log_content assert "192.168.1.1" in log_content finally: # Clean up if Path(temp_log).exists(): try: Path(temp_log).unlink() except: pass # Ignore cleanup errors if __name__ == "__main__": pytest.main([__file__, "-v"])