From ae398dc48bbd30d7a4274f7567a4c422409042bd Mon Sep 17 00:00:00 2001 From: Aditya Bansal Date: Mon, 16 Apr 2018 15:59:53 +0530 Subject: [PATCH] csp_nonce: Add nonce to script tags loading minified JS. --- templates/zerver/app/index.html | 2 +- zerver/templatetags/minified_js.py | 8 +++++--- zproject/jinja2/compressors.py | 4 ++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/templates/zerver/app/index.html b/templates/zerver/app/index.html index cc940eccbc..c62596d713 100644 --- a/templates/zerver/app/index.html +++ b/templates/zerver/app/index.html @@ -35,7 +35,7 @@ {% else %} {% stylesheet 'app' %} {% endif %} - {{ minified_js('app')|safe }} + {{ minified_js('app', csp_nonce)|safe }} {{ render_bundle('translations') }} diff --git a/zerver/templatetags/minified_js.py b/zerver/templatetags/minified_js.py index 75e2cb4795..b3a8b19587 100644 --- a/zerver/templatetags/minified_js.py +++ b/zerver/templatetags/minified_js.py @@ -9,8 +9,9 @@ from django.template.base import Parser, Token register = Library() class MinifiedJSNode(Node): - def __init__(self, sourcefile: str) -> None: + def __init__(self, sourcefile: str, csp_nonce: str) -> None: self.sourcefile = sourcefile + self.csp_nonce = csp_nonce def render(self, context: Dict[str, Any]) -> str: if settings.DEBUG: @@ -24,6 +25,7 @@ class MinifiedJSNode(Node): else: scripts = [settings.JS_SPECS[self.sourcefile]['output_filename']] script_urls = [staticfiles_storage.url(script) for script in scripts] - script_tags = ['' - % url for url in script_urls] + script_tags = [('') % (self.csp_nonce, url) + for url in script_urls] return '\n'.join(script_tags) diff --git a/zproject/jinja2/compressors.py b/zproject/jinja2/compressors.py index 3c89388414..8af952b165 100644 --- a/zproject/jinja2/compressors.py +++ b/zproject/jinja2/compressors.py @@ -10,9 +10,9 @@ from django.template import TemplateSyntaxError from zerver.templatetags.minified_js import MinifiedJSNode -def minified_js(sourcefile: str) -> Text: +def minified_js(sourcefile: str, csp_nonce: str) -> Text: if sourcefile not in settings.JS_SPECS: raise TemplateSyntaxError( "Invalid argument: no JS file %s".format(sourcefile)) - return MinifiedJSNode(sourcefile).render({}) + return MinifiedJSNode(sourcefile, csp_nonce).render({})