summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_script_filenames.js
blob: 8e2f6c7b0d0b341726fe62c1264131d485be9c34 (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
356
357
358
359
360
361
362
363
364
365
366
"use strict";

// There is a rejection emitted when a JS file fails to load. On Android,
// extensions run on the main process and this rejection causes test failures,
// which is essentially why we need to allow the rejection below.
PromiseTestUtils.allowMatchingRejectionsGlobally(
  /Unable to load script.*content_script/
);

const server = createHttpServer();
server.registerDirectory("/data/", do_get_file("data"));

const BASE_URL = `http://localhost:${server.identity.primaryPort}/data`;

function computeSHA256Hash(text) {
  const hasher = Cc["@mozilla.org/security/hash;1"].createInstance(
    Ci.nsICryptoHash
  );
  hasher.init(Ci.nsICryptoHash.SHA256);
  hasher.update(
    text.split("").map(c => c.charCodeAt(0)),
    text.length
  );
  return hasher.finish(true);
}

// This function represents a dummy content or background script that the test
// cases below should attempt to load but it shouldn't be loaded because we
// check the extensions of JavaScript files in `nsJARChannel`.
function scriptThatShouldNotBeLoaded() {
  browser.test.fail("this should not be executed");
}

function scriptThatAlwaysRuns() {
  browser.test.sendMessage("content-script-loaded");
}

// We use these variables in combination with `scriptThatAlwaysRuns()` to send a
// signal to the extension and avoid the page to be closed too soon.
const alwaysRunsFileName = "always_run.js";
const alwaysRunsContentScript = {
  matches: ["<all_urls>"],
  js: [alwaysRunsFileName],
  run_at: "document_start",
};

add_task(async function test_content_script_filename_without_extension() {
  // Filenames without any extension should not be loaded.
  let invalidFileName = "content_script";
  let extensionData = {
    manifest: {
      content_scripts: [
        alwaysRunsContentScript,
        {
          matches: ["<all_urls>"],
          js: [invalidFileName],
        },
      ],
    },
    files: {
      [invalidFileName]: scriptThatShouldNotBeLoaded,
      [alwaysRunsFileName]: scriptThatAlwaysRuns,
    },
  };

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

  let contentPage = await ExtensionTestUtils.loadContentPage(
    `${BASE_URL}/file_sample.html`
  );

  await extension.awaitMessage("content-script-loaded");

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

add_task(async function test_content_script_filename_with_invalid_extension() {
  let validFileName = "content_script.js";
  let invalidFileName = "content_script.xyz";
  let extensionData = {
    manifest: {
      content_scripts: [
        alwaysRunsContentScript,
        {
          matches: ["<all_urls>"],
          js: [validFileName, invalidFileName],
        },
      ],
    },
    files: {
      // This makes sure that, when one of the content scripts fails to load,
      // none of the content scripts are executed.
      [validFileName]: scriptThatShouldNotBeLoaded,
      [invalidFileName]: scriptThatShouldNotBeLoaded,
      [alwaysRunsFileName]: scriptThatAlwaysRuns,
    },
  };

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

  let contentPage = await ExtensionTestUtils.loadContentPage(
    `${BASE_URL}/file_sample.html`
  );

  await extension.awaitMessage("content-script-loaded");

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

add_task(async function test_bg_script_injects_script_with_invalid_ext() {
  function backgroundScript() {
    browser.test.sendMessage("background-script-loaded");
  }

  let validFileName = "background.js";
  let invalidFileName = "invalid_background.xyz";
  let extensionData = {
    background() {
      const script = document.createElement("script");
      script.src = "./invalid_background.xyz";
      document.head.appendChild(script);

      const validScript = document.createElement("script");
      validScript.src = "./background.js";
      document.head.appendChild(validScript);
    },
    files: {
      [invalidFileName]: scriptThatShouldNotBeLoaded,
      [validFileName]: backgroundScript,
    },
  };

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

  await extension.awaitMessage("background-script-loaded");

  await extension.unload();
});

add_task(async function test_background_scripts() {
  function backgroundScript() {
    browser.test.sendMessage("background-script-loaded");
  }

  let validFileName = "background.js";
  let invalidFileName = "invalid_background.xyz";
  let extensionData = {
    manifest: {
      background: {
        scripts: [invalidFileName, validFileName],
      },
    },
    files: {
      [invalidFileName]: scriptThatShouldNotBeLoaded,
      [validFileName]: backgroundScript,
    },
  };

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

  await extension.awaitMessage("background-script-loaded");

  await extension.unload();
});

add_task(async function test_background_page_injects_scripts_inline() {
  function injectedBackgroundScript() {
    browser.test.log(
      "inline script injectedBackgroundScript has been executed"
    );
    browser.test.sendMessage("background-script-loaded");
  }

  let backgroundHtmlPage = "background_page.html";
  let validFileName = "injected_background.js";
  let invalidFileName = "invalid_background.xyz";

  let inlineScript = `(${function () {
    const script = document.createElement("script");
    script.src = "./invalid_background.xyz";
    document.head.appendChild(script);
    const validScript = document.createElement("script");
    validScript.src = "./injected_background.js";
    document.head.appendChild(validScript);
  }})()`;

  const inlineScriptSHA256 = computeSHA256Hash(inlineScript);

  info(
    `Computed sha256 for the inline script injectedBackgroundScript: ${inlineScriptSHA256}`
  );

  let extensionData = {
    manifest: {
      background: { page: backgroundHtmlPage },
      content_security_policy: [
        "script-src",
        "'self'",
        `'sha256-${inlineScriptSHA256}'`,
        ";",
      ].join(" "),
    },
    files: {
      [invalidFileName]: scriptThatShouldNotBeLoaded,
      [validFileName]: injectedBackgroundScript,
      "pre-script.js": () => {
        window.onsecuritypolicyviolation = evt => {
          const { violatedDirective, originalPolicy } = evt;
          browser.test.fail(
            `Unexpected csp violation: ${JSON.stringify({
              violatedDirective,
              originalPolicy,
            })}`
          );
          // Let the test to fail immediately when an unexpected csp violation
          // prevented the inline script from being executed successfully.
          browser.test.sendMessage("background-script-loaded");
        };
      },
      [backgroundHtmlPage]: `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8"></head>
            <script src="pre-script.js"></script>
            <script>${inlineScript}</script>
          </head>
        </html>`,
    },
  };

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

  await extension.awaitMessage("background-script-loaded");

  await extension.unload();
});

add_task(async function test_background_page_injects_scripts() {
  // This is the initial background script loaded in the HTML page.
  function backgroundScript() {
    const script = document.createElement("script");
    script.src = "./invalid_background.xyz";
    document.head.appendChild(script);

    const validScript = document.createElement("script");
    validScript.src = "./injected_background.js";
    document.head.appendChild(validScript);
  }

  // This is the script injected by the script defined in `backgroundScript()`.
  function injectedBackgroundScript() {
    browser.test.sendMessage("background-script-loaded");
  }

  let backgroundHtmlPage = "background_page.html";
  let validFileName = "injected_background.js";
  let invalidFileName = "invalid_background.xyz";
  let extensionData = {
    manifest: {
      background: { page: backgroundHtmlPage },
    },
    files: {
      [invalidFileName]: scriptThatShouldNotBeLoaded,
      [validFileName]: injectedBackgroundScript,
      [backgroundHtmlPage]: `
        <html>
          <head>
            <meta charset="utf-8"></head>
            <script src="./background.js"></script>
          </head>
        </html>`,
      "background.js": backgroundScript,
    },
  };

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

  await extension.awaitMessage("background-script-loaded");

  await extension.unload();
});

add_task(async function test_background_script_registers_content_script() {
  let invalidFileName = "content_script";
  let extensionData = {
    manifest: {
      permissions: ["<all_urls>"],
    },
    async background() {
      await browser.contentScripts.register({
        js: [{ file: "/content_script" }],
        matches: ["<all_urls>"],
      });
      browser.test.sendMessage("background-script-loaded");
    },
    files: {
      [invalidFileName]: scriptThatShouldNotBeLoaded,
    },
  };

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

  let contentPage = await ExtensionTestUtils.loadContentPage(
    `${BASE_URL}/file_sample.html`
  );

  await extension.awaitMessage("background-script-loaded");

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

add_task(async function test_web_accessible_resources() {
  function contentScript() {
    const script = document.createElement("script");
    script.src = browser.runtime.getURL("content_script.css");
    script.onerror = () => {
      browser.test.sendMessage("second-content-script-loaded");
    };

    document.head.appendChild(script);
  }

  let contentScriptFileName = "content_script.js";
  let invalidFileName = "content_script.css";
  let extensionData = {
    manifest: {
      web_accessible_resources: [invalidFileName],
      content_scripts: [
        alwaysRunsContentScript,
        {
          matches: ["<all_urls>"],
          js: [contentScriptFileName],
        },
      ],
    },
    files: {
      [invalidFileName]: scriptThatShouldNotBeLoaded,
      [contentScriptFileName]: contentScript,
      [alwaysRunsFileName]: scriptThatAlwaysRuns,
    },
  };

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

  let contentPage = await ExtensionTestUtils.loadContentPage(
    `${BASE_URL}/file_sample.html`
  );

  await extension.awaitMessage("content-script-loaded");
  await extension.awaitMessage("second-content-script-loaded");

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