--- a/mercurial/hgweb/common.py Tue Jan 10 20:47:48 2017 -0800
+++ b/mercurial/hgweb/common.py Tue Jan 10 23:37:08 2017 -0800
@@ -8,9 +8,11 @@
from __future__ import absolute_import
+import base64
import errno
import mimetypes
import os
+import uuid
from .. import (
encoding,
@@ -199,3 +201,22 @@
if req.env.get('HTTP_IF_NONE_MATCH') == tag:
raise ErrorResponse(HTTP_NOT_MODIFIED)
req.headers.append(('ETag', tag))
+
+def cspvalues(ui):
+ """Obtain the Content-Security-Policy header and nonce value.
+
+ Returns a 2-tuple of the CSP header value and the nonce value.
+
+ First value is ``None`` if CSP isn't enabled. Second value is ``None``
+ if CSP isn't enabled or if the CSP header doesn't need a nonce.
+ """
+ # Don't allow untrusted CSP setting since it be disable protections
+ # from a trusted/global source.
+ csp = ui.config('web', 'csp', untrusted=False)
+ nonce = None
+
+ if csp and '%nonce%' in csp:
+ nonce = base64.urlsafe_b64encode(uuid.uuid4().bytes).rstrip('=')
+ csp = csp.replace('%nonce%', nonce)
+
+ return csp, nonce