Skip to content

Commit 6f94e8d

Browse files
author
Emily Stark
committed
Cache csp instead of constructing it each request.
1 parent b5286b9 commit 6f94e8d

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

packages/browser-policy-content/browser-policy-content.js

+12
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
//
3535

3636
var cspSrcs;
37+
var cachedCsp; // Avoid constructing the header out of cspSrcs when possible.
38+
3739
// CSP keywords have to be single-quoted.
3840
var unsafeInline = "'unsafe-inline'";
3941
var unsafeEval = "'unsafe-eval'";
@@ -70,8 +72,11 @@ var removeCspSrc = function (directive, src) {
7072
cspSrcs[directive] = _.without(cspSrcs[directive] || [], src);
7173
};
7274

75+
// Prepare for a change to cspSrcs. Ensure that we have a key in the dictionary
76+
// and clear any cached CSP.
7377
var ensureDirective = function (directive) {
7478
cspSrcs = cspSrcs || {};
79+
cachedCsp = null;
7580
if (! _.has(cspSrcs, directive))
7681
cspSrcs[directive] = _.clone(cspSrcs["default-src"]);
7782
};
@@ -95,6 +100,9 @@ _.extend(BrowserPolicy.content, {
95100
if (! cspSrcs || _.isEmpty(cspSrcs))
96101
return null;
97102

103+
if (cachedCsp)
104+
return cachedCsp;
105+
98106
var header = _.map(cspSrcs, function (srcs, directive) {
99107
srcs = srcs || [];
100108
if (_.isEmpty(srcs))
@@ -107,10 +115,12 @@ _.extend(BrowserPolicy.content, {
107115
return header;
108116
},
109117
_reset: function () {
118+
cachedCsp = null;
110119
setDefaultPolicy();
111120
},
112121

113122
setPolicy: function (csp) {
123+
cachedCsp = null;
114124
parseCsp(csp);
115125
},
116126

@@ -174,6 +184,7 @@ _.extend(BrowserPolicy.content, {
174184
});
175185
},
176186
disallowAll: function () {
187+
cachedCsp = null;
177188
cspSrcs = {
178189
"default-src": []
179190
};
@@ -203,6 +214,7 @@ _.each(["script", "object", "img", "media",
203214
cspSrcs[directive].push(src);
204215
};
205216
BrowserPolicy.content[disallowMethodName] = function () {
217+
cachedCsp = null;
206218
cspSrcs[directive] = [];
207219
};
208220
BrowserPolicy.content[allowDataMethodName] = function () {

0 commit comments

Comments
 (0)