security.py 1001 B

123456789101112131415161718192021222324
  1. from django.core.exceptions import ImproperlyConfigured
  2. __all__ = (
  3. 'validate_peppers',
  4. )
  5. def validate_peppers(peppers):
  6. """
  7. Validate the given dictionary of cryptographic peppers for type & sufficient length.
  8. """
  9. if not isinstance(peppers, dict):
  10. raise ImproperlyConfigured("API_TOKEN_PEPPERS must be a dictionary.")
  11. for key, pepper in peppers.items():
  12. if type(key) is not int:
  13. raise ImproperlyConfigured(f"Invalid API_TOKEN_PEPPERS key: {key}. All keys must be integers.")
  14. if not 0 <= key <= 32767:
  15. raise ImproperlyConfigured(
  16. f"Invalid API_TOKEN_PEPPERS key: {key}. Key values must be between 0 and 32767, inclusive."
  17. )
  18. if type(pepper) is not str:
  19. raise ImproperlyConfigured(f"Invalid pepper {key}: Pepper value must be a string.")
  20. if len(pepper) < 50:
  21. raise ImproperlyConfigured(f"Invalid pepper {key}: Pepper must be at least 50 characters in length.")