Avoid inline script execution for injecting CSRF token (#7016)

Scripts with type="application/json" or "text/plain" are not executed, so we can
use them to inject dynamic CSRF data, without allowing inline-script execution
in Content-Security-Policy.
This commit is contained in:
Luka Jeran 2022-11-29 17:10:32 +01:00 committed by GitHub
parent f0095b4de2
commit 6ec6ddea9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 13 additions and 12 deletions

View File

@ -38,6 +38,7 @@ function sameOrigin(url) {
!(/^(\/\/|http:|https:).*/.test(url));
}
window.drf = JSON.parse(document.getElementById('drf_csrf').textContent);
var csrftoken = window.drf.csrfToken;
$.ajaxSetup({

View File

@ -244,11 +244,11 @@
{% endif %}
{% block script %}
<script>
window.drf = {
csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
csrfToken: "{{ csrf_token }}"
};
<script type="application/json" id="drf_csrf">
{
"csrfHeaderName": "{{ csrf_header_name|default:'X-CSRFToken' }}",
"csrfToken": "{{ csrf_token }}"
}
</script>
<script src="{% static "rest_framework/js/jquery-3.5.1.min.js" %}"></script>
<script src="{% static "rest_framework/js/ajax-form.js" %}"></script>

View File

@ -287,11 +287,11 @@
{% endif %}
{% block script %}
<script>
window.drf = {
csrfHeaderName: "{{ csrf_header_name|default:'X-CSRFToken' }}",
csrfToken: "{% if request %}{{ csrf_token }}{% endif %}"
};
<script type="application/json" id="drf_csrf">
{
"csrfHeaderName": "{{ csrf_header_name|default:'X-CSRFToken' }}",
"csrfToken": "{% if request %}{{ csrf_token }}{% endif %}"
}
</script>
<script src="{% static "rest_framework/js/jquery-3.5.1.min.js" %}"></script>
<script src="{% static "rest_framework/js/ajax-form.js" %}"></script>

View File

@ -6,7 +6,7 @@ from django.shortcuts import render
def test_base_template_with_context():
context = {'request': True, 'csrf_token': 'TOKEN'}
result = render({}, 'rest_framework/base.html', context=context)
assert re.search(r'\bcsrfToken: "TOKEN"', result.content.decode())
assert re.search(r'"csrfToken": "TOKEN"', result.content.decode())
def test_base_template_with_no_context():
@ -14,4 +14,4 @@ def test_base_template_with_no_context():
# so it can be easily extended.
result = render({}, 'rest_framework/base.html')
# note that this response will not include a valid CSRF token
assert re.search(r'\bcsrfToken: ""', result.content.decode())
assert re.search(r'"csrfToken": ""', result.content.decode())