summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/mochitest/test_chrome_ext_permissions.html
blob: 98a9fed30e01909cab822889e27ec5f02b1d958f (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
<!DOCTYPE HTML>
<html>
<head>
  <title>Test for permissions</title>
  <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
  <script src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
  <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
  <link rel="stylesheet" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
</head>
<body>

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

function makeTest(manifestPermissions, optionalPermissions, checkFetch = true) {
  return async function() {
    function pageScript() {
      /* global PERMISSIONS */
      browser.test.onMessage.addListener(async msg => {
        if (msg == "set-cookie") {
          try {
            await browser.cookies.set({
              url: "http://example.com/",
              name: "COOKIE",
              value: "NOM NOM",
            });
            browser.test.sendMessage("set-cookie.result", {success: true});
          } catch (err) {
            dump(`set cookie failed with ${err.message}\n`);
            browser.test.sendMessage("set-cookie.result",
                                     {success: false, message: err.message});
          }
        } else if (msg == "remove") {
          browser.permissions.remove(PERMISSIONS).then(result => {
            browser.test.sendMessage("remove.result", result);
          });
        } else if (msg == "request") {
          browser.test.withHandlingUserInput(() => {
            browser.permissions.request(PERMISSIONS).then(result => {
              browser.test.sendMessage("request.result", result);
            });
          });
        }
      });

      browser.test.sendMessage("page-ready");
    }

    let extension = ExtensionTestUtils.loadExtension({
      background() {
        browser.test.sendMessage("ready", browser.runtime.getURL("page.html"));
      },

      manifest: {
        permissions: manifestPermissions,
        optional_permissions: [...(optionalPermissions.permissions || []),
                               ...(optionalPermissions.origins || [])],

        content_scripts: [{
          matches: ["http://mochi.test/*/file_sample.html"],
          js: ["content_script.js"],
        }],
      },

      files: {
        "content_script.js": async () => {
          let url = new URL(window.location.pathname, "http://example.com/");
          fetch(url, {}).then(response => {
            browser.test.sendMessage("fetch.result", response.ok);
          }).catch(() => {
            browser.test.sendMessage("fetch.result", false);
          });
        },

        "page.html": `<html><head>
          <script src="page.js"><\/script>
        </head></html>`,

        "page.js": `const PERMISSIONS = ${JSON.stringify(optionalPermissions)}; (${pageScript})();`,
      },
    });

    await extension.startup();

    function call(method) {
      extension.sendMessage(method);
      return extension.awaitMessage(`${method}.result`);
    }

    let base = window.location.href.replace(/^chrome:\/\/mochitests\/content/,
                                            "http://mochi.test:8888");
    let file = new URL("file_sample.html", base);

    async function testContentScript() {
      let win = window.open(file);
      let result = await extension.awaitMessage("fetch.result");
      win.close();
      return result;
    }

    let url = await extension.awaitMessage("ready");
    let win = window.open();
    win.location.href = url;
    await extension.awaitMessage("page-ready");

    // Using the cookies API from an extension page should fail
    let result = await call("set-cookie");
    is(result.success, false, "setting cookie failed");
    if (manifestPermissions.includes("cookies")) {
      ok(/^Permission denied/.test(result.message),
         "setting cookie failed with an appropriate error due to missing host permission");
    } else {
      ok(/browser\.cookies is undefined/.test(result.message),
         "setting cookie failed since cookies API is not present");
    }

    // Making a cross-origin request from a content script should fail
    if (checkFetch) {
      result = await testContentScript();
      is(result, false, "fetch() failed from content script due to lack of host permission");
    }

    result = await call("request");
    is(result, true, "permissions.request() succeeded");

    // Using the cookies API from an extension page should succeed
    result = await call("set-cookie");
    is(result.success, true, "setting cookie succeeded");

    // Making a cross-origin request from a content script should succeed
    if (checkFetch) {
      result = await testContentScript();
      is(result, true, "fetch() succeeded from content script due to lack of host permission");
    }

    // Now revoke our permissions
    result = await call("remove");

    // The cookies API should once again fail
    result = await call("set-cookie");
    is(result.success, false, "setting cookie failed");

    // As should the cross-origin request from a content script
    if (checkFetch) {
      result = await testContentScript();
      is(result, false, "fetch() failed from content script due to lack of host permission");
    }

    await extension.unload();
  };
}

add_task(function setup() {
  // Don't bother with prompts in this test.
  return SpecialPowers.pushPrefEnv({
    set: [["extensions.webextOptionalPermissionPrompts", false]],
  });
});

const ORIGIN = "*://example.com/";
add_task(makeTest([], {
  permissions: ["cookies"],
  origins: [ORIGIN],
}));

add_task(makeTest(["cookies"], {origins: [ORIGIN]}));
add_task(makeTest([ORIGIN], {permissions: ["cookies"]}, false));

</script>

</body>
</html>