""" Real functionality tests for input validation system. Tests the actual RealInputValidator implementation with real data scenarios, security configurations, and integration with the security config system. No mocks or simulations - tests real behavior. """ import pytest import os import sys import tempfile import json from pathlib import Path from unittest import mock # Add project root to path sys.path.insert(0, str(Path(__file__).parent)) # Import the real implementations directly try: # Import the classes and functions directly from the module import importlib.util spec = importlib.util.spec_from_file_location( "input_validator", Path(__file__).parent / "core" / "security" / "input_validator.py" ) input_validator_module = importlib.util.module_from_spec(spec) # Execute the module to load classes spec.loader.exec_module(input_validator_module) # Extract the classes we need RealInputValidator = input_validator_module.RealInputValidator ValidationResult = input_validator_module.ValidationResult InputValidationError = input_validator_module.InputValidationError SecurityViolationError = input_validator_module.SecurityViolationError validate_string_input = input_validator_module.validate_string_input validate_file_path_input = input_validator_module.validate_file_path_input validate_json_input = input_validator_module.validate_json_input sanitize_for_logging = input_validator_module.sanitize_for_logging # Import security config from core.security.security_config import SecurityConfig, get_security_config except Exception as e: print(f"Import error: {e}") # Fallback - try direct import from core.security.input_validator import * from core.security.security_config import SecurityConfig, get_security_config class TestRealInputValidation: """Test real input validation functionality without mocks.""" def setup_method(self): """Setup real validator instances for each test.""" self.strict_validator = RealInputValidator(strict_mode=True) self.lenient_validator = RealInputValidator(strict_mode=False) def test_real_sql_injection_detection(self): """Test detection of real SQL injection patterns.""" # Real SQL injection attempts from security research real_sql_attacks = [ "'; DROP TABLE users; --", "1' OR '1'='1", "admin'--", "UNION SELECT username, password FROM users", "1; EXEC xp_cmdshell('dir')", "' OR 1=1 --", "'; INSERT INTO users VALUES ('hacker', 'password'); --", "1' AND (SELECT COUNT(*) FROM users) > 0 --" ] for attack in real_sql_attacks: result = self.strict_validator.validate_string(attack) assert not result.is_valid, f"Failed to detect SQL injection: {attack}" assert any("SQL injection" in error for error in result.errors) def test_real_nosql_injection_detection(self): """Test detection of real NoSQL injection patterns.""" # Real NoSQL injection attempts real_nosql_attacks = [ '{"$where": "this.username == this.password"}', '{"$regex": ".*"}', 'function() { return true; }', '{"$ne": null}', 'this.username', '{"$gt": ""}', '{"$exists": true}', 'db.users.find()' ] for attack in real_nosql_attacks: result = self.strict_validator.validate_string(attack) assert not result.is_valid, f"Failed to detect NoSQL injection: {attack}" assert any("injection" in error.lower() for error in result.errors) def test_real_file_path_validation(self): """Test file path validation with real filesystem scenarios.""" # Test with real temporary directory with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Valid paths valid_paths = [ "document.txt", "folder/file.pdf", "data/session.json" ] for path in valid_paths: result = validate_file_path_input(path, allowed_dirs=[temp_dir]) assert result == os.path.normpath(path) # Dangerous paths (path traversal) dangerous_paths = [ "../../../etc/passwd", "..\\..\\windows\\system32\\config\\sam", "folder/../../../secret.txt" ] for path in dangerous_paths: with pytest.raises(SecurityViolationError): validate_file_path_input(path) def test_real_json_validation(self): """Test JSON validation with real JSON data.""" # Valid JSON data valid_json_data = [ {"name": "John", "age": 30}, {"workflow": {"steps": [{"action": "click", "target": "button"}]}}, {"config": {"timeout": 5000, "retries": 3}} ] for data in valid_json_data: # Test dict input result = validate_json_input(data) assert result == data # Test string input json_str = json.dumps(data) result = validate_json_input(json_str) assert result == data # Invalid JSON invalid_json = '{"invalid": json, "missing": quotes}' with pytest.raises(InputValidationError): validate_json_input(invalid_json) def test_real_html_sanitization(self): """Test HTML sanitization with real XSS payloads.""" # Real XSS payloads from security research xss_payloads = [ '', '', '', '', '', '
Click me
' ] for payload in xss_payloads: result = self.strict_validator.validate_string(payload, allow_html=False) # Should be sanitized (escaped) assert result.is_valid assert "