import re
def normalize_headers(headers):
"""
Normalizes request headers, handling case, whitespace, and basic sanity checks.
Args:
headers (dict): A dictionary of request headers.
Returns:
dict: A dictionary of normalized headers. Returns an empty dictionary if input is invalid.
"""
if not isinstance(headers, dict):
print("Error: Input must be a dictionary.")
return {}
normalized_headers = {}
for key, value in headers.items():
if not isinstance(key, str):
print(f"Warning: Invalid header key: {key}. Skipping.") #Log warning instead of error
continue
if not isinstance(value, str):
normalized_headers[key] = str(value) #Convert to string if not already
continue
# Normalize case to lowercase
normalized_key = key.lower()
normalized_value = value.lower()
# Remove leading/trailing whitespace
normalized_key = normalized_key.strip()
normalized_value = normalized_value.strip()
#Sanity check: Remove potentially problematic characters
normalized_key = re.sub(r'[^a-z0-9_]+', '', normalized_key)
normalized_value = re.sub(r'[^a-z0-9_.,\s-]+', '', normalized_value) #Allow periods, commas, spaces and hyphens
if not normalized_key:
print(f"Warning: Empty header key after sanitization: {key}. Skipping.")
continue
normalized_headers[normalized_key] = normalized_value
return normalized_headers
Add your comment