1. import re
  2. def validate_request_headers(headers, expected_headers):
  3. """
  4. Sorts request headers and performs validation checks with fallback logic.
  5. Args:
  6. headers (dict): A dictionary of request headers.
  7. expected_headers (dict): A dictionary of expected headers and their values.
  8. Returns:
  9. dict: A dictionary containing validation results for each expected header.
  10. Keys are header names, and values are dictionaries with 'valid' (bool) and 'value' (str).
  11. Returns None if headers is not a dictionary or expected_headers is not a dictionary.
  12. """
  13. if not isinstance(headers, dict) or not isinstance(expected_headers, dict):
  14. return None
  15. sorted_headers = dict(sorted(headers.items())) # Sort headers alphabetically
  16. results = {}
  17. for header_name, expected_value in expected_headers.items():
  18. if header_name in sorted_headers:
  19. actual_value = sorted_headers[header_name]
  20. # Basic validation: Check if the header exists and matches the expected value.
  21. if actual_value == expected_value:
  22. results[header_name] = {'valid': True, 'value': actual_value}
  23. else:
  24. # Fallback logic: Allow for variations in case (e.g., "Content-Type" vs "content-type")
  25. if expected_value.lower() in actual_value.lower(): #Case-insensitive comparison
  26. results[header_name] = {'valid': True, 'value': actual_value}
  27. else:
  28. results[header_name] = {'valid': False, 'value': actual_value}
  29. else:
  30. # Header is missing. Consider it invalid.
  31. results[header_name] = {'valid': False, 'value': None}
  32. return results

Add your comment