csp.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import secrets
  2. from enum import StrEnum
  3. from django.utils.functional import SimpleLazyObject, empty
  4. from django.utils.html import format_html
  5. # Template context key for the CSP nonce.
  6. CONTEXT_KEY = "csp_nonce"
  7. class CSP(StrEnum):
  8. """
  9. Content Security Policy constants for directive values and special tokens.
  10. These constants represent:
  11. 1. Standard quoted string values from the CSP spec (e.g., 'self',
  12. 'unsafe-inline')
  13. 2. Special placeholder tokens (NONCE) that get replaced by the middleware
  14. Using this enum instead of raw strings provides better type checking,
  15. autocompletion, and protection against common mistakes like:
  16. - Typos (e.g., 'noone' instead of 'none')
  17. - Missing quotes (e.g., ["self"] instead of ["'self'"])
  18. - Inconsistent quote styles (e.g., ["'self'", "\"unsafe-inline\""])
  19. Example usage in Django settings:
  20. SECURE_CSP = {
  21. "default-src": [CSP.NONE],
  22. "script-src": [CSP.SELF, CSP.NONCE],
  23. }
  24. """
  25. # HTTP Headers.
  26. HEADER_ENFORCE = "Content-Security-Policy"
  27. HEADER_REPORT_ONLY = "Content-Security-Policy-Report-Only"
  28. # Standard CSP directive values.
  29. NONE = "'none'"
  30. REPORT_SAMPLE = "'report-sample'"
  31. SELF = "'self'"
  32. STRICT_DYNAMIC = "'strict-dynamic'"
  33. UNSAFE_EVAL = "'unsafe-eval'"
  34. UNSAFE_HASHES = "'unsafe-hashes'"
  35. UNSAFE_INLINE = "'unsafe-inline'"
  36. WASM_UNSAFE_EVAL = "'wasm-unsafe-eval'"
  37. # Special placeholder that gets replaced by the middleware.
  38. # The value itself is arbitrary and should not be mistaken for a real
  39. # nonce.
  40. NONCE = "<CSP_NONCE_SENTINEL>"
  41. class LazyNonce(SimpleLazyObject):
  42. """
  43. Lazily generates a cryptographically secure nonce string, for use in CSP
  44. headers.
  45. The nonce is only generated when first accessed (e.g., via string
  46. interpolation or inside a template).
  47. The nonce will evaluate as `True` if it has been generated, and `False` if
  48. it has not. This is useful for third-party Django libraries that want to
  49. support CSP without requiring it.
  50. Example Django template usage with context processors enabled:
  51. <script {% csp_nonce_attr %}></script>
  52. ``{% csp_nonce_attr %}`` will only render the nonce attribute if the nonce
  53. has been evaluated (i.e. accessed) elsewhere in the request/response cycle.
  54. """
  55. def __init__(self):
  56. super().__init__(generate_nonce)
  57. def __bool__(self):
  58. return self._wrapped is not empty
  59. def nonce_attr(context, media=None):
  60. nonce = context.get(CONTEXT_KEY)
  61. if media:
  62. return media.render(attrs={"nonce": nonce} if nonce is not None else None)
  63. if nonce is None:
  64. return ""
  65. return format_html('nonce="{}"', nonce)
  66. def generate_nonce():
  67. return secrets.token_urlsafe(16)
  68. def build_policy(config, nonce=None):
  69. policy = []
  70. for directive, values in config.items():
  71. if values in (None, False):
  72. continue
  73. if values is True:
  74. rendered_value = ""
  75. else:
  76. if isinstance(values, set):
  77. # Sort values for consistency, preventing cache invalidation
  78. # between requests and ensuring reliable browser caching.
  79. values = sorted(values)
  80. elif not isinstance(values, list | tuple):
  81. values = [values]
  82. # Replace the nonce sentinel with the actual nonce values, if the
  83. # sentinel is found and a nonce is provided. Otherwise, remove it.
  84. if (has_sentinel := CSP.NONCE in values) and nonce:
  85. values = [f"'nonce-{nonce}'" if v == CSP.NONCE else v for v in values]
  86. elif has_sentinel:
  87. values = [v for v in values if v != CSP.NONCE]
  88. if not values:
  89. continue
  90. rendered_value = " ".join(values)
  91. policy.append(f"{directive} {rendered_value}".rstrip())
  92. return "; ".join(policy)