summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/mochitest/test_ext_contentscript_activeTab.html
blob: 28bbe3b253f5d7487fa1a5ebeeb1a32469a1b22f (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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
<!DOCTYPE HTML>
<html>
<head>
  <title>Test for content script</title>
  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
  <script type="text/javascript" src="head.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>

<script type="text/javascript">
"use strict";

add_task(async function setup() {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["extensions.manifestV3.enabled", true],
      ["extensions.originControls.grantByDefault", false],
    ],
  });
});

// Create a test extension with the provided function as the background
// script.  The background script will have a few helpful functions
// available.
/* global awaitLoad, gatherFrameSources */
function makeExtension({
  background,
  useScriptingAPI = false,
  manifest_version = 2,
  host_permissions,
}) {
  // Wait for a webNavigation.onCompleted event where the details for the
  // loaded page match the attributes of `filter`.
  function awaitLoad(filter) {
    return new Promise(resolve => {
      const listener = details => {
        if (Object.keys(filter).every(key => details[key] === filter[key])) {
          browser.webNavigation.onCompleted.removeListener(listener);
          resolve();
        }
      };
      browser.webNavigation.onCompleted.addListener(listener);
    });
  }

  // Return a string with a (sorted) list of the source of all frames
  // in the given tab into which this extension can inject scripts
  // (ie all frames for which it has the activeTab permission).
  // Source is the hostname for frames in http sources, or the full
  // location href in other documents (eg about: pages)
  const gatherFrameSources = useScriptingAPI ?
    async function gatherFrameSources(tabid) {
      let results = await browser.scripting.executeScript({
        target: { tabId: tabid, allFrames: true },
        func: () => window.location.hostname || window.location.href,
      });
      // Adjust `result` so that it looks like the one returned by
      // `tabs.executeScript()`.
      let result = results.map(res => res.result);

      return String(result.sort());
    } : async function gatherFrameSources(tabid) {
      let result = await browser.tabs.executeScript(tabid, {
        allFrames: true,
        matchAboutBlank: true,
        code: "window.location.hostname || window.location.href;",
      });

      return String(result.sort());
    };

  const permissions = ["webNavigation"];
  if (useScriptingAPI) {
    permissions.push("scripting");
  }

  // When host_permissions is passed, test "automatic activeTab" for ungranted
  // host_permissions in mv3, else test with the normal activeTab permission.
  if (!host_permissions) {
    permissions.push("activeTab");
  }

  return ExtensionTestUtils.loadExtension({
    manifest: {
      manifest_version,
      permissions,
      host_permissions,
    },
    background: [
      `const useScriptingAPI = ${useScriptingAPI};`,
      `const manifest_version = ${manifest_version};`,
      `${awaitLoad}`,
      `${gatherFrameSources}`,
      `${ExtensionTestCommon.serializeScript(background)}`,
    ].join("\n")
  });
}

// Helper function to verify that executeScript() fails without the activeTab
// permission (or any specific origin permissions).
const verifyNoActiveTab = async ({ useScriptingAPI, manifest_version, host_permissions }) => {
  let extension = makeExtension({
    async background() {
      const URL = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_contentscript_activeTab.html";

      let [tab] = await Promise.all([
        browser.tabs.create({url: URL}),
        awaitLoad({frameId: 0}),
      ]);

      await browser.test.assertRejects(
        gatherFrameSources(tab.id),
        /^Missing host permission/,
        "executeScript should fail without activeTab permission"
      );

      await browser.tabs.remove(tab.id);

      browser.test.notifyPass("no-active-tab");
    },
    useScriptingAPI,
    manifest_version,
    host_permissions,
  });

  await extension.startup();
  await extension.awaitFinish("no-active-tab");
  await extension.unload();
};

add_task(async function test_no_activeTab_tabs() {
  await verifyNoActiveTab({ useScriptingAPI: false });
});

add_task(async function test_no_activeTab_scripting() {
  await verifyNoActiveTab({ useScriptingAPI: true });
});

add_task(async function test_no_activeTab_scripting_mv3() {
  await verifyNoActiveTab({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: null,
  });
});

add_task(async function test_no_activeTab_scripting_mv3_autoActiveTab() {
  await verifyNoActiveTab({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: ["http://mochi.test/"],
  });
});

// Test helper to verify that dynamically created iframes do not get the
// activeTab permission, unless same-origin with the top page.
const verifyDynamicFrames = async ({ useScriptingAPI, manifest_version, host_permissions }) => {
  let extension = makeExtension({
    async background() {
      const BASE_HOST = "www.example.com";

      let [tab] = await Promise.all([
        browser.tabs.create({url: `https://${BASE_HOST}/`}),
        awaitLoad({frameId: 0}),
      ]);

      function inject() {
        let nframes = 4;
        function frameLoaded() {
          nframes--;
          if (nframes == 0) {
            browser.runtime.sendMessage("frames-loaded");
          }
        }

        // about:blank
        let frame = document.createElement("iframe");
        frame.addEventListener("load", frameLoaded, {once: true});
        document.body.appendChild(frame);

        let div = document.createElement("div");
        div.innerHTML = "<iframe src='https://test1.example.com/'></iframe>";
        let framelist = div.getElementsByTagName("iframe");
        browser.test.assertEq(1, framelist.length, "Found 1 frame inside div");
        framelist[0].addEventListener("load", frameLoaded, {once: true});
        document.body.appendChild(div);

        // about:srcdoc containing cross-origin frame.
        let div2 = document.createElement("div");
        div2.innerHTML = "<iframe srcdoc=\"<iframe src='https://test2.example.com/'&gt;</iframe&gt;\"></iframe>";
        framelist = div2.getElementsByTagName("iframe");
        browser.test.assertEq(1, framelist.length, "Found 1 frame inside div");
        framelist[0].addEventListener("load", frameLoaded, {once: true});
        document.body.appendChild(div2);

        // Note: URL's host is BASE_HOST (same as top).
        const URL = "https://www.example.com/tests/toolkit/components/extensions/test/mochitest/file_contentscript_iframe.html";

        let xhr = new XMLHttpRequest();
        xhr.open("GET", URL);
        xhr.responseType = "document";
        xhr.overrideMimeType("text/html");

        xhr.addEventListener("load", () => {
          if (xhr.readyState != 4) {
            return;
          }
          if (xhr.status != 200) {
            browser.runtime.sendMessage("error");
          }

          let frame = xhr.response.getElementById("frame");
          browser.test.assertEq(
            "https://test2.example.com/",
            frame?.src,
            "Found frame in response document with cross-origin URL"
          );
          frame.addEventListener("load", frameLoaded, {once: true});
          document.body.appendChild(frame);
        }, {once: true});
        xhr.addEventListener("error", () => {
          browser.runtime.sendMessage("error");
        }, {once: true});
        xhr.send();
      }

      browser.test.onMessage.addListener(async msg => {
        if (msg !== "go") {
          browser.test.fail(`unexpected message received: ${msg}`);
          return;
        }

        let loadedPromise = new Promise((resolve, reject) => {
          let listener = msg => {
            let unlisten = () => browser.runtime.onMessage.removeListener(listener);
            if (msg == "frames-loaded") {
              unlisten();
              resolve();
            } else if (msg == "error") {
              unlisten();
              reject();
            }
          };
          browser.runtime.onMessage.addListener(listener);
        });

        if (useScriptingAPI) {
          await browser.scripting.executeScript({
            target: { tabId: tab.id },
            func: inject,
          });
        } else {
          await browser.tabs.executeScript(tab.id, {
            code: `(${inject})();`,
          });
        }

        await loadedPromise;

        let result = await gatherFrameSources(tab.id);

        browser.test.assertEq(
          String(["about:blank", "about:srcdoc", BASE_HOST]),
          result,
          `Script injected only into (same origin) about:blank-ish dynamically created frames`
        );

        await browser.tabs.remove(tab.id);

        browser.test.notifyPass("dynamic-frames");
      });

      browser.test.sendMessage("ready", tab.id);
    },
    useScriptingAPI,
    manifest_version,
    host_permissions,
  });

  await extension.startup();

  let tabId = await extension.awaitMessage("ready");
  extension.grantActiveTab(tabId);

  extension.sendMessage("go");
  await extension.awaitFinish("dynamic-frames");

  await extension.unload();
};

add_task(async function test_dynamic_frames_tabs() {
  await verifyDynamicFrames({ useScriptingAPI: false });
});

add_task(async function test_dynamic_frames_scripting() {
  await verifyDynamicFrames({ useScriptingAPI: true });
});

add_task(async function test_dynamic_frames_scripting_mv3() {
  await verifyDynamicFrames({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: null,
  });
});

add_task(async function test_dynamic_frames_scripting_mv3_autoActiveTab() {
  await verifyDynamicFrames({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: ["https://www.example.com/"],
  });
});

// Test helper to verify that an iframe created from an <iframe srcdoc> gets
// the activeTab permission.
const verifySrcdoc = async ({ useScriptingAPI, manifest_version, host_permissions }) => {
  let extension = makeExtension({
    async background() {
      const URL = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_contentscript_activeTab2.html";
      const OUTER_SOURCE = "about:srcdoc";
      const PAGE_SOURCE = "mochi.test";
      const FRAME_SOURCE = "test1.example.com";

      let [tab] = await Promise.all([
        browser.tabs.create({url: URL}),
        awaitLoad({frameId: 0}),
      ]);

      browser.test.onMessage.addListener(async msg => {
        if (msg !== "go") {
          browser.test.fail(`unexpected message received: ${msg}`);
          return;
        }

        let result = await gatherFrameSources(tab.id);

        if (manifest_version < 3) {
          browser.test.assertEq(
            String([OUTER_SOURCE, PAGE_SOURCE, FRAME_SOURCE]),
            result,
            "Script is injected into frame created from <iframe srcdoc>"
          );
        } else {
          browser.test.assertEq(
            String([OUTER_SOURCE, PAGE_SOURCE]),
            result,
            "Script is not injected into cross-origin frame created from <iframe srcdoc>"
          );
        }

        await browser.tabs.remove(tab.id);

        browser.test.notifyPass("srcdoc");
      });

      browser.test.sendMessage("ready", tab.id);
    },
    useScriptingAPI,
    manifest_version,
    host_permissions,
  });

  await extension.startup();

  let tabId = await extension.awaitMessage("ready");
  extension.grantActiveTab(tabId);

  extension.sendMessage("go");
  await extension.awaitFinish("srcdoc");

  await extension.unload();
};

add_task(async function test_srcdoc_tabs() {
  await verifySrcdoc({ useScriptingAPI: false });
});

add_task(async function test_srcdoc_scripting() {
  await verifySrcdoc({ useScriptingAPI: true });
});

add_task(async function test_srcdoc_scripting_mv3() {
  await verifySrcdoc({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: null,
  });
});

add_task(async function test_srcdoc_scripting_mv3_autoActiveTab() {
  await verifySrcdoc({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: ["http://mochi.test/"],
  });
});

// Test helper to verify that navigating frames by setting the src attribute
// from the parent page does not grant the activeTab permission to the frame,
// unless the frame is same-origin to the top page.
const verifyNavigateBySrc = async ({ useScriptingAPI, manifest_version, host_permissions }) => {
  let extension = makeExtension({
    async background() {
      const URL = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_contentscript_activeTab.html";
      const PAGE_SOURCE = "mochi.test";
      const EMPTY_SOURCE = "about:blank";
      const FRAME_SOURCE = "test1.example.com";

      let [tab] = await Promise.all([
        browser.tabs.create({url: URL}),
        awaitLoad({frameId: 0}),
      ]);

      browser.test.onMessage.addListener(async msg => {
        if (msg !== "go") {
          browser.test.fail(`unexpected message received: ${msg}`);
          return;
        }

        let result = await gatherFrameSources(tab.id);
        if (manifest_version < 3) {
          browser.test.assertEq(
            String([EMPTY_SOURCE, PAGE_SOURCE, FRAME_SOURCE]),
            result,
            "In original page, script is injected into base page and original frames"
          );
        } else {
          browser.test.assertEq(
            String([EMPTY_SOURCE, PAGE_SOURCE]),
            result,
            "In original page, script is injected into same-origin frames"
          );
        }

        let loadedPromise = awaitLoad({tabId: tab.id});

        let func = () => {
          document.getElementById('emptyframe').src = 'http://test2.example.com/';
        };

        if (useScriptingAPI) {
          await browser.scripting.executeScript({
            target: { tabId: tab.id },
            func,
          });
        } else {
          await browser.tabs.executeScript(tab.id, { code: `(${func})();` });
        }

        await loadedPromise;


        result = await gatherFrameSources(tab.id);
        if (manifest_version < 3) {
          browser.test.assertEq(
            String([PAGE_SOURCE, FRAME_SOURCE]),
            result,
            "Script is not injected into initially empty frame after cross-origin navigation"
          );
        } else {
          browser.test.assertEq(
            String([PAGE_SOURCE]),
            result,
            "Script is not injected into initially empty frame after cross-origin navigation"
          );
        }

        loadedPromise = awaitLoad({tabId: tab.id});

        func = () => {
          document.getElementById('regularframe').src = 'http://mochi.test:8888/';
        };

        if (useScriptingAPI) {
          await browser.scripting.executeScript({
            target: { tabId: tab.id },
            func,
          });
        } else {
          await browser.tabs.executeScript(tab.id, { code: `(${func})();` });
        }

        await loadedPromise;

        result = await gatherFrameSources(tab.id);

        browser.test.assertEq(
          String([PAGE_SOURCE, PAGE_SOURCE]),
          result,
          "Script injected into frame after navigating to same-origin"
        );

        await browser.tabs.remove(tab.id);
        browser.test.notifyPass("test-scripts");
      });

      browser.test.sendMessage("ready", tab.id);
    },
    useScriptingAPI,
    manifest_version,
    host_permissions,
  });

  await extension.startup();

  let tabId = await extension.awaitMessage("ready");
  extension.grantActiveTab(tabId);

  extension.sendMessage("go");
  await extension.awaitFinish("test-scripts");

  await extension.unload();
};

add_task(async function test_navigate_by_src_tabs() {
  await verifyNavigateBySrc({ useScriptingAPI: false });
});

add_task(async function test_navigate_by_src_scripting() {
  await verifyNavigateBySrc({ useScriptingAPI: true });
});

add_task(async function test_navigate_by_src_scripting_mv3() {
  await verifyNavigateBySrc({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: null,
  });
});

add_task(async function test_navigate_by_src_scripting_mv3_autoActiveTab() {
  await verifyNavigateBySrc({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: ["http://mochi.test/"],
  });
});

// Test helper to verify that navigating frames by setting window.location from
// inside the frame revokes the activeTab permission.
const verifyNavigateByWindowLocation = async ({ useScriptingAPI, manifest_version, host_permissions }) => {
  let extension = makeExtension({
    async background() {
      const URL = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/file_contentscript_activeTab.html";
      const PAGE_SOURCE = "mochi.test";
      const EMPTY_SOURCE = "about:blank";
      const FRAME_SOURCE = "test1.example.com";

      let [tab] = await Promise.all([
        browser.tabs.create({url: URL}),
        awaitLoad({frameId: 0}),
      ]);

      browser.test.onMessage.addListener(async msg => {
        if (msg !== "go") {
          browser.test.fail(`unexpected message received: ${msg}`);
          return;
        }

        let result = await gatherFrameSources(tab.id);

        if (manifest_version < 3) {
          browser.test.assertEq(
            String([EMPTY_SOURCE, PAGE_SOURCE, FRAME_SOURCE]),
            result,
            "Script initially injected into all frames"
          );
        } else {
          browser.test.assertEq(
            String([EMPTY_SOURCE, PAGE_SOURCE]),
            result,
            "Script initially injected into all same-origin frames"
          );
        }

        let nframes = 0;
        let frames = await browser.webNavigation.getAllFrames({tabId: tab.id});
        for (let frame of frames) {
          if (frame.parentFrameId == -1) {
            continue;
          }

          if (manifest_version >= 3 && frame.url.includes(FRAME_SOURCE)) {
            // In MV3, can't access cross-origin iframes from the start.

            let invalidPromise = browser.scripting.executeScript({
              target: { tabId: tab.id, frameIds: [frame.frameId] },
              func: () => window.location.hostname,
            });
            await browser.test.assertRejects(
              invalidPromise,
              /^Missing host permission for the tab or frames/,
              "executeScript should fail on cross-origin frame"
            );

            continue;
          }

          let loadPromise = awaitLoad({
            tabId: tab.id,
            frameId: frame.frameId,
          });

          let func = () => {
            window.location.href = 'https://test2.example.com/';
          };

          if (useScriptingAPI) {
            await browser.scripting.executeScript({
              target: { tabId: tab.id, frameIds: [frame.frameId] },
              func,
            });
          } else {
            await browser.tabs.executeScript(tab.id, {
              frameId: frame.frameId,
              matchAboutBlank: true,
              code: `(${func})();`,
            });
          }

          await loadPromise;

          let executePromise;
          func = () => window.location.hostname;

          if (useScriptingAPI) {
            executePromise = browser.scripting.executeScript({
              target: { tabId: tab.id, frameIds: [frame.frameId] },
              func,
            });
          } else {
            executePromise = browser.tabs.executeScript(tab.id, {
              frameId: frame.frameId,
              matchAboutBlank: true,
              code: `(${func})();`,
            });
          }

          await browser.test.assertRejects(
            executePromise,
            /^Missing host permission for the tab or frames/,
            "executeScript should have failed on navigated frame"
          );

          nframes++;
        }

        if (manifest_version < 3) {
          browser.test.assertEq(2, nframes, "Found 2 frames");
        } else {
          browser.test.assertEq(1, nframes, "Found 1 frame");
        }

        await browser.tabs.remove(tab.id);
        browser.test.notifyPass("scripted-navigation");
      });

      browser.test.sendMessage("ready", tab.id);
    },
    useScriptingAPI,
    manifest_version,
    host_permissions,
  });

  await extension.startup();

  let tabId = await extension.awaitMessage("ready");
  extension.grantActiveTab(tabId);

  extension.sendMessage("go");
  await extension.awaitFinish("scripted-navigation");

  await extension.unload();
};

add_task(async function test_navigate_by_window_location_tabs() {
  await verifyNavigateByWindowLocation({ useScriptingAPI: false });
});

add_task(async function test_navigate_by_window_location_scripting() {
  await verifyNavigateByWindowLocation({ useScriptingAPI: true });
});

add_task(async function test_navigate_by_window_location_scripting_mv3() {
  await verifyNavigateByWindowLocation({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: null,
   });
});

add_task(async function test_navigate_by_window_location_scripting_mv3_autoActiveTab() {
  await verifyNavigateByWindowLocation({
    useScriptingAPI: true,
    manifest_version: 3,
    host_permissions: ["http://mochi.test/"],
   });
});

</script>

</body>
</html>