"""Tests for the SecurityValidator module.""" import sys from pathlib import Path # Add the parent directory to the path sys.path.insert(0, str(Path(__file__).parent.parent)) from validators.security import SecurityValidator class TestSecurityValidator: """Test cases for SecurityValidator.""" def setup_method(self): """Set up test environment.""" self.validator = SecurityValidator() def test_initialization(self): """Test validator initialization.""" assert self.validator.errors == [] patterns = self.validator.INJECTION_PATTERNS assert len(patterns) > 0 def test_validate_no_injection_safe_inputs(self): """Test that safe inputs pass validation.""" safe_inputs = [ "normal-text", "file.txt", "user@example.com", "feature-branch", "v1.0.0", "my-app-name", "config_value", "BUILD_NUMBER", "2024-03-15", "https://example.com", ] for value in safe_inputs: self.validator.errors = [] result = self.validator.validate_no_injection(value) assert result is True, f"Should accept safe input: {value}" assert len(self.validator.errors) == 0 def test_validate_no_injection_command_injection(self): """Test that command injection attempts are blocked.""" dangerous_inputs = [ "; rm -rf /", "&& rm -rf /", "|| rm -rf /", "` rm -rf /`", "$(rm -rf /)", "${rm -rf /}", "; cat /etc/passwd", "&& cat /etc/passwd", "| cat /etc/passwd", "& whoami", "; shutdown now", "&& reboot", "|| format c:", "; del *.*", ] for value in dangerous_inputs: self.validator.errors = [] result = self.validator.validate_no_injection(value) assert result is False, f"Should block dangerous input: {value}" assert len(self.validator.errors) > 0 def test_validate_no_injection_sql_injection(self): """Test that SQL injection attempts are detected.""" sql_injection_attempts = [ "'; DROP TABLE users; --", "' OR '1'='1", '" OR "1"="1', "admin' --", "' UNION SELECT * FROM passwords --", "1; DELETE FROM users", "' OR 1=1 --", "'; EXEC xp_cmdshell('dir'); --", ] for value in sql_injection_attempts: self.validator.errors = [] result = self.validator.validate_no_injection(value) # SQL injection might be blocked depending on implementation assert isinstance(result, bool) if not result: assert len(self.validator.errors) > 0 def test_validate_no_injection_path_traversal(self): """Test that path traversal attempts are blocked.""" path_traversal_attempts = [ "../../../etc/passwd", "..\\..\\..\\windows\\system32", "....//....//....//etc/passwd", "%2e%2e%2f%2e%2e%2f", # URL encoded "..;/..;/", ] for value in path_traversal_attempts: self.validator.errors = [] result = self.validator.validate_no_injection(value) # Path traversal might be blocked depending on implementation assert isinstance(result, bool) def test_validate_no_injection_script_injection(self): """Test that script injection attempts are blocked.""" script_injection_attempts = [ "", "javascript:alert(1)", "", "