Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions csp/tests/test_templatetags.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,24 @@ def test_nested_script_tags_are_removed(self):
'var hello=\'world\';</script>')

self.assert_template_eq(*self.process_templates(tpl, expected))

def test_regex_captures_script_content(self):
"""
Ensure that script content get captured properly.
Especially when using angle brackets."""
tpl = """
{% load csp %}
{% script %}
<script type="text/javascript">
let capture_text = "<script></script>"
</script>
{% endscript %}
"""

expected = (
'<script nonce="{}">'
'let capture_text = "<script></script>"'
'</script>')

print(self.process_templates(tpl, expected))
self.assert_template_eq(*self.process_templates(tpl, expected))
2 changes: 1 addition & 1 deletion csp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def _async_attr_mapper(attr_name, val):

def _unwrap_script(text):
"""Extract content defined between script tags"""
matches = re.search(r'<script[\s|\S]*>([\s|\S]+?)</script>', text)
matches = re.search(r'<script[\s|\S]*?>([\s|\S]+)</script>', text)
if matches and len(matches.groups()):
return matches.group(1).strip()

Expand Down
30 changes: 30 additions & 0 deletions docs/nonce.rst
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,36 @@ This tag will output a properly nonced script every time. For the sake of syntax

Django:

To enable the loading of the 'csp' tag in templates, you'll need to add the CSP template tags to the TEMPLATES section of your settings file..

.. code-block:: python

TEMPLATES = [
{
"OPTIONS": {
'libraries': {
'csp': 'csp.templatetags.csp',
}
},
}
]

Then you can load the 'csp' template tags and use 'script' in the template:

To enable the loading of the 'csp' tag in templates, you'll need to add the CSP template tags to the TEMPLATES settings.

.. code-block:: python

TEMPLATES = [
{
"OPTIONS": {
'libraries': {
'csp': 'csp.templatetags.csp',
}
},
}
]

.. code-block:: jinja

{% load csp %}
Expand Down