"""Validation utilities."""
from typing import Any
def validate_json_schema(data: Any, schema: dict[str, Any]) -> bool:
"""Validate data against JSON schema (basic validation).
Args:
data: Data to validate
schema: JSON schema
Returns:
True if valid, False otherwise
"""
try:
# Basic type validation
if "type" in schema:
expected_type = schema["type"]
if expected_type == "object" and not isinstance(data, dict):
return False
elif expected_type == "array" and not isinstance(data, list):
return False
elif expected_type == "string" and not isinstance(data, str):
return False
elif expected_type == "integer" and not isinstance(data, int):
return False
elif expected_type == "number" and not isinstance(data, (int, float)):
return False
elif expected_type == "boolean" and not isinstance(data, bool):
return False
# Required properties validation for objects
if isinstance(data, dict) and "required" in schema:
for required_prop in schema["required"]:
if required_prop not in data:
return False
return True
except Exception:
return False
def sanitize_input(input_str: str, max_length: int = 1000) -> str:
"""Sanitize input string.
Args:
input_str: Input string to sanitize
max_length: Maximum allowed length
Returns:
Sanitized string
"""
if not isinstance(input_str, str):
input_str = str(input_str)
# Truncate if too long
if len(input_str) > max_length:
input_str = input_str[:max_length]
# Remove potentially harmful characters
forbidden_chars = ["\x00", "\x01", "\x02", "\x03", "\x04", "\x05"]
for char in forbidden_chars:
input_str = input_str.replace(char, "")
return input_str.strip()