import re
def validate_request_headers(headers, expected_headers):
"""
Sorts request headers and performs validation checks with fallback logic.
Args:
headers (dict): A dictionary of request headers.
expected_headers (dict): A dictionary of expected headers and their values.
Returns:
dict: A dictionary containing validation results for each expected header.
Keys are header names, and values are dictionaries with 'valid' (bool) and 'value' (str).
Returns None if headers is not a dictionary or expected_headers is not a dictionary.
"""
if not isinstance(headers, dict) or not isinstance(expected_headers, dict):
return None
sorted_headers = dict(sorted(headers.items())) # Sort headers alphabetically
results = {}
for header_name, expected_value in expected_headers.items():
if header_name in sorted_headers:
actual_value = sorted_headers[header_name]
# Basic validation: Check if the header exists and matches the expected value.
if actual_value == expected_value:
results[header_name] = {'valid': True, 'value': actual_value}
else:
# Fallback logic: Allow for variations in case (e.g., "Content-Type" vs "content-type")
if expected_value.lower() in actual_value.lower(): #Case-insensitive comparison
results[header_name] = {'valid': True, 'value': actual_value}
else:
results[header_name] = {'valid': False, 'value': actual_value}
else:
# Header is missing. Consider it invalid.
results[header_name] = {'valid': False, 'value': None}
return results
Add your comment