summaryrefslogtreecommitdiffstats
path: root/dom/permission/tests/test_permissions_api.html
blob: 57c45e9d58b0ff215ee1d8f54be959874a31c15a (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
<!--
  Any copyright is dedicated to the Public Domain.
  http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
  <title>Test for Permissions API</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" href="/tests/SimpleTest/test.css">
</head>

<body>
  <pre id="test"></pre>
  <script type="application/javascript">
  /*globals SpecialPowers, SimpleTest, is, ok, */
  'use strict';

  const {
    UNKNOWN_ACTION,
    PROMPT_ACTION,
    ALLOW_ACTION,
    DENY_ACTION
  } = SpecialPowers.Ci.nsIPermissionManager;

  SimpleTest.waitForExplicitFinish();

  const PERMISSIONS = [{
    name: 'geolocation',
    type: 'geo'
  }, {
    name: 'notifications',
    type: 'desktop-notification'
  }, {
    name: 'push',
    type: 'desktop-notification'
  }, {
    name: 'persistent-storage',
    type: 'persistent-storage'
  }, {
    name: 'midi',
    type: 'midi'
  }, ];

  const UNSUPPORTED_PERMISSIONS = [
    'foobarbaz', // Not in spec, for testing only.
  ];

  // Create a closure, so that tests are run on the correct window object.
  function createPermissionTester(iframe) {
    const iframeWindow = iframe.contentWindow;
    return {
      async setPermissions(allow, context = iframeWindow.document) {
        const permissions = PERMISSIONS.map(({ type }) => {
          return {
            type,
            allow,
            context,
          };
        });
        await SpecialPowers.popPermissions();
        return SpecialPowers.pushPermissions(permissions);
      },
      checkPermissions(expectedState) {
        const promisesToQuery = PERMISSIONS.map(({ name: expectedName }) => {
          return iframeWindow.navigator.permissions
            .query({ name: expectedName })
            .then(
              ({ state, name }) => {
                is(state, expectedState, `correct state for '${expectedName}'`)
                is(name, expectedName, `correct name for '${expectedName}'`)
              },
              () => ok(false, `query should not have rejected for '${name}'`)
            );
          });
        return Promise.all(promisesToQuery);
      },
      checkUnsupportedPermissions() {
        const promisesToQuery = UNSUPPORTED_PERMISSIONS.map(({ name }) => {
          return iframeWindow.navigator.permissions
            .query({ name })
            .then(
              () => ok(false, `query should not have resolved for '${name}'`),
              error => {
                is(error.name, 'TypeError',
                  `query should have thrown TypeError for '${name}'`);
              }
            );
          });
        return Promise.all(promisesToQuery);
      },
      promiseStateChanged(name, state) {
        return iframeWindow.navigator.permissions
          .query({ name })
          .then(status => {
            return new Promise( resolve => {
              status.onchange = () => {
                status.onchange = null;
                is(status.state, state, `state changed for '${name}'`);
                resolve();
              };
            });
          },
          () => ok(false, `query should not have rejected for '${name}'`));
      },
      testStatusOnChange() {
        return new Promise((resolve) => {
          SpecialPowers.popPermissions(() => {
            const permission = 'geolocation';
            const promiseGranted = this.promiseStateChanged(permission, 'granted');
            this.setPermissions(ALLOW_ACTION);
            promiseGranted.then(async () => {
              const promisePrompt = this.promiseStateChanged(permission, 'prompt');
              await SpecialPowers.popPermissions();
              return promisePrompt;
            }).then(resolve);
          });
        });
      },
      testInvalidQuery() {
        return iframeWindow.navigator.permissions
          .query({ name: 'invalid' })
          .then(
            () => ok(false, 'invalid query should not have resolved'),
            () => ok(true, 'invalid query should have rejected')
          );
      },
      async testNotFullyActiveDoc() {
        const iframe1 = await createIframe();
        const expectedErrorClass = iframe1.contentWindow.DOMException;
        const permAPI = iframe1.contentWindow.navigator.permissions;
        // Document no longer fully active
        iframe1.remove();
        await new Promise((res) => {
          permAPI.query({ name: "geolocation" }).catch((error) => {
            ok(
              error instanceof expectedErrorClass,
              "DOMException from other realm"
            );
            is(
              error.name,
              "InvalidStateError",
              "Must reject with a InvalidStateError"
            );
            iframe1.remove();
            res();
          });
        });
      },
      async testNotFullyActiveChange() {
        await SpecialPowers.popPermissions();
        const iframe2 = await createIframe();
        const initialStatus = await iframe2.contentWindow.navigator.permissions.query(
          { name: "geolocation" }
        );
        await SpecialPowers.pushPermissions([
          {
            type: "geo",
            allow: PROMPT_ACTION,
            context: iframe2.contentWindow.document,
          },
        ]);
        is(
          initialStatus.state,
          "prompt",
          "Initially the iframe's permission is prompt"
        );

        // Document no longer fully active
        const stolenDoc = iframe2.contentWindow.document;
        iframe2.remove();
        initialStatus.onchange = () => {
          ok(false, "onchange must not fire when document is not fully active.");
        };
        // We set it to grant for this origin, but the PermissionStatus doesn't change.
        await SpecialPowers.pushPermissions([
          {
            type: "geo",
            allow: ALLOW_ACTION,
            context: stolenDoc,
          },
        ]);
        is(
          initialStatus.state,
          "prompt",
          "Inactive document's permission must not change"
        );

        // Re-attach the iframe
        document.body.appendChild(iframe2);
        await new Promise((res) => (iframe2.onload = res));
        // Fully active again
        const newStatus = await iframe2.contentWindow.navigator.permissions.query({
          name: "geolocation",
        });
        is(newStatus.state, "granted", "Reflect that we are granted");

        const newEventPromise = new Promise((res) => (newStatus.onchange = res));
        await SpecialPowers.pushPermissions([
          {
            type: "geo",
            allow: DENY_ACTION,
            context: iframe2.contentWindow.document,
          },
        ]);
        // Event fires...
        await newEventPromise;
        is(initialStatus.state, "prompt", "Remains prompt, as it's actually dead.");
        is(newStatus.state, "denied", "New status must be 'denied'.");
        iframe2.remove();
      },
    };
  }

  function createIframe() {
    return new Promise((resolve) => {
      const iframe = document.createElement('iframe');
      iframe.src = 'file_empty.html';
      iframe.onload = () => resolve(iframe);
      document.body.appendChild(iframe);
    });
  }

  window.onload = () => {
    createIframe()
      .then(createPermissionTester)
      .then((tester) => {
        return tester
          .checkUnsupportedPermissions()
          .then(() => tester.setPermissions(UNKNOWN_ACTION))
          .then(() => tester.checkPermissions('prompt'))
          .then(() => tester.setPermissions(PROMPT_ACTION))
          .then(() => tester.checkPermissions('prompt'))
          .then(() => tester.setPermissions(ALLOW_ACTION))
          .then(() => tester.checkPermissions('granted'))
          .then(() => tester.setPermissions(DENY_ACTION))
          .then(() => tester.checkPermissions('denied'))
          .then(() => tester.testStatusOnChange())
          .then(() => tester.testInvalidQuery())
          .then(() => tester.testNotFullyActiveDoc())
          .then(() => tester.testNotFullyActiveChange());
      })
      .then(SimpleTest.finish)
      .catch((e) => {
        ok(false, `Unexpected error ${e}`);
        SimpleTest.finish();
      });
  };
  </script>
</body>

</html>