#36784: Add CSP support to Django's script object and media objects
--------------------------------+------------------------------------
     Reporter:  Johannes Maron  |                    Owner:  Rish
         Type:  New feature     |                   Status:  assigned
    Component:  Forms           |                  Version:  6.0
     Severity:  Normal          |               Resolution:
     Keywords:                  |             Triage Stage:  Accepted
    Has patch:  0               |      Needs documentation:  0
  Needs tests:  0               |  Patch needs improvement:  0
Easy pickings:  0               |                    UI/UX:  0
--------------------------------+------------------------------------
Comment (by Rob Hudson):

 The challenge seems to be that `form.media` does not have access to the
 context and is stateless. I assume this is by design. Changing this seems
 like a big architectural shift so I looked for other options.

 One idea that I liked has two parts to it:

 1. Extend the `Script` class to add a `with_nonce: bool = False`
 parameter.

 Example:

 {{{
 class MyWidget(forms.TextInput):
     class Media:
         js = [
             "already-in-policy.js",  # No nonce needed
             Script("inline-script.js", with_nonce=True),  # Opt-in to
 nonce
         ]
 }}}

 This would render the script tag with a data attribute - something
 harmless if the next step is forgotten (vs something like a nonce
 attribute with a sentinel):
 {{{
     <script src="..." data-csp-nonce></script>
 }}}

 I like the opt-in nature of this vs outputting all tags with a data
 attribute since, if the media is self served you likely don't need the
 nonce.

 2. Use a template filter to replace data attribute with the actual nonce

 {{{
     {{ form.media|with_nonce }}
 }}}

 The filter:
 - finds and replaces the `data-csp-nonce` attribute with the actual nonce
 from template context.
 - if no nonce in the context, removes the data attribute.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/36784#comment:6>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/django-updates/0107019b0abea13f-b8844336-ad8d-44b3-a1ce-e1882a5a4ca6-000000%40eu-central-1.amazonses.com.

Reply via email to