summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_contentscript_csp.js
blob: cf770d91b4f08c36df0ebe6059244464cdd40e79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";

const { TestUtils } = ChromeUtils.import(
  "resource://testing-common/TestUtils.jsm"
);

Services.prefs.setBoolPref("extensions.manifestV3.enabled", true);

const server = createHttpServer({
  hosts: ["example.com", "csplog.example.net"],
});
server.registerDirectory("/data/", do_get_file("data"));

var gDefaultCSP = `default-src 'self' 'report-sample'; script-src 'self' 'report-sample';`;
var gCSP = gDefaultCSP;
const pageContent = `<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
  <img id="testimg">
  </body>
  </html>`;

server.registerPathHandler("/plain.html", (request, response) => {
  response.setStatusLine(request.httpVersion, 200, "OK");
  response.setHeader("Content-Type", "text/html");
  if (gCSP) {
    info(`Content-Security-Policy: ${gCSP}`);
    response.setHeader("Content-Security-Policy", gCSP);
  }
  response.write(pageContent);
});

const BASE_URL = `http://example.com`;
const pageURL = `${BASE_URL}/plain.html`;

const CSP_REPORT_PATH = "/csp-report.sjs";

function readUTF8InputStream(stream) {
  let buffer = NetUtil.readInputStream(stream, stream.available());
  return new TextDecoder().decode(buffer);
}

server.registerPathHandler(CSP_REPORT_PATH, (request, response) => {
  response.setStatusLine(request.httpVersion, 204, "No Content");
  let data = readUTF8InputStream(request.bodyInputStream);
  Services.obs.notifyObservers(null, "extension-test-csp-report", data);
});

async function promiseCSPReport(test) {
  let res = await TestUtils.topicObserved("extension-test-csp-report", test);
  return JSON.parse(res[1]);
}

// Test functions loaded into extension content script.
function testImage(data = {}) {
  return new Promise(resolve => {
    let img = window.document.getElementById("testimg");
    img.onload = () => resolve(true);
    img.onerror = () => {
      browser.test.log(`img error: ${img.src}`);
      resolve(false);
    };
    img.src = data.image_url;
  });
}

function testFetch(data = {}) {
  let f = data.content ? content.fetch : fetch;
  return f(data.url)
    .then(() => true)
    .catch(e => {
      browser.test.assertEq(
        e.message,
        "NetworkError when attempting to fetch resource.",
        "expected fetch failure"
      );
      return false;
    });
}

async function testEval(data = {}) {
  try {
    // eslint-disable-next-line no-eval
    let ev = data.content ? window.eval : eval;
    return ev("true");
  } catch (e) {
    return false;
  }
}

async function testFunction(data = {}) {
  try {
    // eslint-disable-next-line no-eval
    let fn = data.content ? window.Function : Function;
    let sum = new fn("a", "b", "return a + b");
    return sum(1, 1);
  } catch (e) {
    return 0;
  }
}

function testScriptTag(data) {
  return new Promise(resolve => {
    let script = document.createElement("script");
    script.src = data.url;
    script.onload = () => {
      resolve(true);
    };
    script.onerror = () => {
      resolve(false);
    };
    document.body.appendChild(script);
  });
}

// If the violation source is the extension the securitypolicyviolation event is not fired.
// If the page is the source, the event is fired and both the content script or page scripts
// will receive the event.  If we're expecting a moz-extension report  we'll  fail in the
// event listener if we receive a report.  Otherwise we want to resolve in the listener to
// ensure we've received the event for the test.
function contentScript(report) {
  return new Promise(resolve => {
    if (!report || report["document-uri"] === "moz-extension") {
      resolve();
    }
    // eslint-disable-next-line mozilla/balanced-listeners
    document.addEventListener("securitypolicyviolation", e => {
      browser.test.assertTrue(
        e.documentURI !== "moz-extension",
        `securitypolicyviolation: ${e.violatedDirective} ${e.documentURI}`
      );
      resolve();
    });
  });
}

let TESTS = [
  // Image Tests
  {
    description:
      "Image from content script using default extension csp. Image is allowed.",
    pageCSP: `${gDefaultCSP} img-src 'none';`,
    script: testImage,
    data: { image_url: `${BASE_URL}/data/file_image_good.png` },
    expect: true,
  },
  // Fetch Tests
  {
    description: "Fetch url in content script uses default extension csp.",
    pageCSP: `${gDefaultCSP} connect-src 'none';`,
    script: testFetch,
    data: { url: `${BASE_URL}/data/file_image_good.png` },
    expect: true,
  },
  {
    description: "Fetch full url from content script uses page csp.",
    pageCSP: `${gDefaultCSP} connect-src 'none';`,
    script: testFetch,
    data: {
      content: true,
      url: `${BASE_URL}/data/file_image_good.png`,
    },
    expect: false,
    report: {
      "blocked-uri": `${BASE_URL}/data/file_image_good.png`,
      "document-uri": `${BASE_URL}/plain.html`,
      "violated-directive": "connect-src",
    },
  },
  {
    description: "Fetch url from content script uses page csp.",
    pageCSP: `${gDefaultCSP} connect-src *;`,
    script: testFetch,
    version: 3,
    data: {
      content: true,
      url: `${BASE_URL}/data/file_image_good.png`,
    },
    expect: true,
  },

  // Eval tests.
  {
    description: "Eval from content script uses page csp with unsafe-eval.",
    pageCSP: `default-src 'none'; script-src 'unsafe-eval';`,
    script: testEval,
    data: { content: true },
    expect: true,
  },
  {
    description: "Eval from content script uses page csp.",
    pageCSP: `default-src 'self' 'report-sample'; script-src 'self';`,
    version: 3,
    script: testEval,
    data: { content: true },
    expect: false,
    report: {
      "blocked-uri": "eval",
      "document-uri": "http://example.com/plain.html",
      "violated-directive": "script-src",
    },
  },
  {
    description: "Eval in content script allowed by v2 csp.",
    pageCSP: `script-src 'self' 'unsafe-eval';`,
    script: testEval,
    expect: true,
  },
  {
    description: "Eval in content script disallowed by v3 csp.",
    pageCSP: `script-src 'self' 'unsafe-eval';`,
    version: 3,
    script: testEval,
    expect: false,
  },
  {
    description: "Wrapped Eval in content script uses page csp.",
    pageCSP: `script-src 'self' 'unsafe-eval';`,
    version: 3,
    script: async () => {
      return window.wrappedJSObject.eval("true");
    },
    expect: true,
  },
  {
    description: "Wrapped Eval in content script denied by page csp.",
    pageCSP: `script-src 'self';`,
    version: 3,
    script: async () => {
      try {
        return window.wrappedJSObject.eval("true");
      } catch (e) {
        return false;
      }
    },
    expect: false,
  },

  {
    description: "Function from content script uses page csp.",
    pageCSP: `default-src 'self'; script-src 'self' 'unsafe-eval';`,
    script: testFunction,
    data: { content: true },
    expect: 2,
  },
  {
    description: "Function from content script uses page csp.",
    pageCSP: `default-src 'self' 'report-sample'; script-src 'self';`,
    version: 3,
    script: testFunction,
    data: { content: true },
    expect: 0,
    report: {
      "blocked-uri": "eval",
      "document-uri": "http://example.com/plain.html",
      "violated-directive": "script-src",
    },
  },
  {
    description: "Function in content script uses extension csp.",
    pageCSP: `default-src 'self'; script-src 'self' 'unsafe-eval';`,
    version: 3,
    script: testFunction,
    expect: 0,
  },

  // The javascript url tests are not included as we do not execute those,
  // aparently even with the urlbar filtering pref flipped.
  // (browser.urlbar.filter.javascript)
  // https://bugzilla.mozilla.org/show_bug.cgi?id=866522

  // script tag injection tests
  {
    description: "remote script in content script passes in v2",
    version: 2,
    pageCSP: "script-src http://example.com:*;",
    script: testScriptTag,
    data: { url: `${BASE_URL}/data/file_script_good.js` },
    expect: true,
  },
  {
    description: "remote script in content script fails in v3",
    version: 3,
    pageCSP: "script-src http://example.com:*;",
    script: testScriptTag,
    data: { url: `${BASE_URL}/data/file_script_good.js` },
    expect: false,
  },
];

async function runCSPTest(test) {
  // Set the CSP for the page loaded into the tab.
  gCSP = `${test.pageCSP || gDefaultCSP} report-uri ${CSP_REPORT_PATH}`;
  let data = {
    manifest: {
      manifest_version: test.version || 2,
      content_scripts: [
        {
          matches: ["http://*/plain.html"],
          run_at: "document_idle",
          js: ["content_script.js"],
        },
      ],
      permissions: ["<all_urls>"],
    },

    files: {
      "content_script.js": `
      (${contentScript})(${JSON.stringify(test.report)}).then(() => {
        browser.test.sendMessage("violationEvent");
      });
      (${test.script})(${JSON.stringify(test.data)}).then(result => {
        browser.test.sendMessage("result", result);
      });
      `,
    },
  };

  let extension = ExtensionTestUtils.loadExtension(data);
  await extension.startup();

  let reportPromise = test.report && promiseCSPReport();
  let contentPage = await ExtensionTestUtils.loadContentPage(pageURL);

  info(`running: ${test.description}`);
  await extension.awaitMessage("violationEvent");
  let result = await extension.awaitMessage("result");
  equal(result, test.expect, test.description);
  if (test.report) {
    let report = await reportPromise;
    for (let key of Object.keys(test.report)) {
      equal(
        report["csp-report"][key],
        test.report[key],
        `csp-report ${key} matches`
      );
    }
  }

  await extension.unload();
  await contentPage.close();
  clearCache();
}

add_task(async function test_contentscript_csp() {
  for (let test of TESTS) {
    await runCSPTest(test);
  }
});