summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_api_events_listener_calls_exceptions.js
blob: 02970f9144850b4a4be2cc395bacb778a398b495 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { ExtensionStorageIDB } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionStorageIDB.sys.mjs"
);

// Detect if the current build is still using the legacy storage.sync Kinto-based backend
// (currently only GeckoView builds does have that still enabled).
//
// TODO(Bug 1625257): remove this once the rust-based storage.sync backend has been enabled
// also on GeckoView build and the legacy Kinto-based backend has been ripped off.
const storageSyncKintoEnabled = Services.prefs.getBoolPref(
  "webextensions.storage.sync.kinto"
);

const server = createHttpServer({ hosts: ["example.com"] });
server.registerDirectory("/data/", do_get_file("data"));
server.registerPathHandler("/test-page.html", (req, res) => {
  res.setHeader("Content-Type", "text/html", false);
  res.write(`<!DOCTYPE html>
    <html><body><script>
      window.onerror = (evt) => {
        browser.test.log("webpage page got error event, error property set to: " + String(evt.error) + "::" +
                         evt.error?.stack + "\\n");
        window.postMessage(
          {
            message: evt.message,
            sourceName: evt.filename,
            lineNumber: evt.lineno,
            columnNumber: evt.colno,
            errorIsDefined: !!evt.error,
          },
          "*"
        );
      };
      window.errorListenerReady = true;
    </script></body></html>
  `);
});

add_task(async function test_api_listener_call_exception() {
  const extension = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: [
        "storage",
        "webRequest",
        "webRequestBlocking",
        "http://example.com/*",
      ],
      content_scripts: [
        {
          js: ["contentscript.js"],
          matches: ["http://example.com/test-page.html"],
          run_at: "document_start",
        },
      ],
    },
    files: {
      "contentscript.js": () => {
        window.onload = () => {
          browser.test.assertEq(
            window.wrappedJSObject.errorListenerReady,
            true,
            "Got an onerror listener on the content page side"
          );
          browser.test.sendMessage("contentscript-attached");
        };
        // eslint-disable-next-line mozilla/balanced-listeners
        window.addEventListener("message", evt => {
          browser.test.fail(
            `Webpage got notified on an exception raised from the content script: ${JSON.stringify(
              evt.data
            )}`
          );
        });
        // eslint-disable-next-line mozilla/balanced-listeners
        window.addEventListener("error", evt => {
          const errorDetails = {
            message: evt.message,
            sourceName: evt.filename,
            lineNumber: evt.lineno,
            columnNumber: evt.colno,
            errorIsDefined: !!evt.error,
          };
          browser.test.fail(
            `Webpage got notified on an exception raised from the content script: ${JSON.stringify(
              errorDetails
            )}`
          );
        });
        const throwAnError = () => {
          throw new Error("test-contentscript-error");
        };
        browser.storage.sync.onChanged.addListener(() => {
          throwAnError();
        });

        browser.storage.local.onChanged.addListener(() => {
          throw undefined; // eslint-disable-line no-throw-literal
        });
      },
      "extpage.html": `<!DOCTYPE html><script src="extpage.js"></script>`,
      "extpage.js": () => {
        // eslint-disable-next-line mozilla/balanced-listeners
        window.addEventListener("error", evt => {
          browser.test.log(
            `Extension page got error event, error property set to: ${evt.error} :: ${evt.error?.stack}\n`
          );
          const errorDetails = {
            message: evt.message,
            sourceName: evt.filename,
            lineNumber: evt.lineno,
            columnNumber: evt.colno,
            errorIsDefined: !!evt.error,
          };

          // Theoretically the exception thrown by a listener registered
          // from an extension webpage should be emitting an error event
          // (e.g. like for a DOM Event listener in a similar scenario),
          // but we never emitted it and so it would be better to only emit
          // it after have explicitly accepted the slightly change in behavior.
          browser.test.log(
            `extension page got notified on an exception raised from the API event listener: ${JSON.stringify(
              errorDetails
            )}`
          );
        });
        browser.webRequest.onBeforeRequest.addListener(
          () => {
            throw new Error(`Mock webRequest listener exception`);
          },
          { urls: ["http://example.com/data/*"] },
          ["blocking"]
        );

        // An object with a custom getter for the `message` property and a custom
        // toString method, both are triggering a test failure to make sure we do
        // catch with a failure if we are running the extension code as a side effect
        // of logging the error to the console service.
        const nonError = {
          // eslint-disable-next-line getter-return
          get message() {
            browser.test.fail(`Unexpected extension code executed`);
          },

          toString() {
            browser.test.fail(`Unexpected extension code executed`);
          },
        };
        browser.storage.sync.onChanged.addListener(() => {
          throw nonError;
        });

        // Throwing undefined or null is also allowed and so we cover that here as well
        // to confirm we are not making any assumption about the value being raised to
        // be always defined.
        browser.storage.local.onChanged.addListener(() => {
          throw undefined; // eslint-disable-line no-throw-literal
        });
      },
    },
  });

  await extension.startup();

  const page = await ExtensionTestUtils.loadContentPage(
    extension.extension.baseURI.resolve("extpage.html"),
    { extension }
  );

  // Prepare to collect the error reported for the exception being triggered
  // by the test itself.
  const prepareWaitForConsoleMessage = () => {
    this.content.waitForConsoleMessage = new Promise(resolve => {
      const currInnerWindowID = this.content.windowGlobalChild?.innerWindowId;
      const consoleListener = {
        QueryInterface: ChromeUtils.generateQI(["nsIConsoleListener"]),
        observe: message => {
          if (
            message instanceof Ci.nsIScriptError &&
            message.innerWindowID === currInnerWindowID
          ) {
            resolve({
              message: message.message,
              category: message.category,
              sourceName: message.sourceName,
              hasStack: !!message.stack,
            });
            Services.console.unregisterListener(consoleListener);
          }
        },
      };
      Services.console.registerListener(consoleListener);
    });
  };

  const notifyStorageSyncListener = extensionTestWrapper => {
    // The notifyListeners method from ExtensionStorageSyncKinto does use
    // the Extension class instance as the key for the storage.sync listeners
    // map, whereas ExtensionStorageSync does use the extension id instead.
    //
    // TODO(Bug 1625257): remove this once the rust-based storage.sync backend has been enabled
    // also on GeckoView build and the legacy Kinto-based backend has been ripped off.
    let listenersMapKey = storageSyncKintoEnabled
      ? extensionTestWrapper.extension
      : extensionTestWrapper.id;
    ok(
      ExtensionParent.apiManager.global.extensionStorageSync.listeners.has(
        listenersMapKey
      ),
      "Got a storage.sync onChanged listener for the test extension"
    );
    ExtensionParent.apiManager.global.extensionStorageSync.notifyListeners(
      listenersMapKey,
      {}
    );
  };

  // Retrieve the message collected from the previously created promise.
  const asyncAssertConsoleMessage = async ({
    targetPage,
    expectedErrorRegExp,
    expectedSourceName,
    shouldIncludeStack,
  }) => {
    const { message, category, sourceName, hasStack } = await targetPage.spawn(
      [],
      () => this.content.waitForConsoleMessage
    );

    ok(
      expectedErrorRegExp.test(message),
      `Got the expected error message: ${message}`
    );

    Assert.deepEqual(
      { category, sourceName, hasStack },
      {
        category: "content javascript",
        sourceName: expectedSourceName,
        hasStack: shouldIncludeStack,
      },
      "Expected category and sourceName are set on the nsIScriptError"
    );
  };

  {
    info("Test exception raised by webRequest listener");
    const expectedErrorRegExp = new RegExp(
      `Error: Mock webRequest listener exception`
    );
    const expectedSourceName =
      extension.extension.baseURI.resolve("extpage.js");
    await page.spawn([], prepareWaitForConsoleMessage);
    await ExtensionTestUtils.fetch(
      "http://example.com",
      "http://example.com/data/file_sample.html"
    );
    await asyncAssertConsoleMessage({
      targetPage: page,
      expectedErrorRegExp,
      expectedSourceName,
      // TODO(Bug 1810582): this should be expected to be true.
      shouldIncludeStack: false,
    });
  }

  {
    info("Test exception raised by storage.sync listener");
    // The listener has throw an object that isn't an Error instance and
    // it also has a getter for the message property, we expect it to be
    // logged using the string returned by the native toString method.
    const expectedErrorRegExp = new RegExp(
      `uncaught exception: \\[object Object\\]`
    );
    // TODO(Bug 1810582): this should be expected to be the script url
    // where the exception has been originated from.
    const expectedSourceName =
      extension.extension.baseURI.resolve("extpage.html");

    await page.spawn([], prepareWaitForConsoleMessage);
    notifyStorageSyncListener(extension);
    await asyncAssertConsoleMessage({
      targetPage: page,
      expectedErrorRegExp,
      expectedSourceName,
      // TODO(Bug 1810582): this should be expected to be true.
      shouldIncludeStack: false,
    });
  }

  {
    info("Test exception raised by storage.local listener");
    // The listener has throw an object that isn't an Error instance and
    // it also has a getter for the message property, we expect it to be
    // logged using the string returned by the native toString method.
    const expectedErrorRegExp = new RegExp(`uncaught exception: undefined`);
    // TODO(Bug 1810582): this should be expected to be the script url
    // where the exception has been originated from.
    const expectedSourceName =
      extension.extension.baseURI.resolve("extpage.html");
    await page.spawn([], prepareWaitForConsoleMessage);
    ExtensionStorageIDB.notifyListeners(extension.id, {});
    await asyncAssertConsoleMessage({
      targetPage: page,
      expectedErrorRegExp,
      expectedSourceName,
      // TODO(Bug 1810582): this should be expected to be true.
      shouldIncludeStack: false,
    });
  }

  await page.close();

  info("Test content script API event listeners exception");

  const contentPage = await ExtensionTestUtils.loadContentPage(
    "http://example.com/test-page.html"
  );

  await extension.awaitMessage("contentscript-attached");

  {
    info("Test exception raised by content script storage.sync listener");
    // The listener has throw an object that isn't an Error instance and
    // it also has a getter for the message property, we expect it to be
    // logged using the string returned by the native toString method.
    const expectedErrorRegExp = new RegExp(`Error: test-contentscript-error`);
    const expectedSourceName =
      extension.extension.baseURI.resolve("contentscript.js");

    await contentPage.spawn([], prepareWaitForConsoleMessage);
    notifyStorageSyncListener(extension);
    await asyncAssertConsoleMessage({
      targetPage: contentPage,
      expectedErrorRegExp,
      expectedSourceName,
      // TODO(Bug 1810582): this should be expected to be true.
      shouldIncludeStack: false,
    });
  }

  {
    info("Test exception raised by content script storage.local listener");
    // The listener has throw an object that isn't an Error instance and
    // it also has a getter for the message property, we expect it to be
    // logged using the string returned by the native toString method.
    const expectedErrorRegExp = new RegExp(`uncaught exception: undefined`);
    // TODO(Bug 1810582): this should be expected to be the script url
    // where the exception has been originated from.
    const expectedSourceName = extension.extension.baseURI.resolve("/");

    await contentPage.spawn([], prepareWaitForConsoleMessage);
    ExtensionStorageIDB.notifyListeners(extension.id, {});
    await asyncAssertConsoleMessage({
      targetPage: contentPage,
      expectedErrorRegExp,
      expectedSourceName,
      // TODO(Bug 1810582): this should be expected to be true.
      shouldIncludeStack: false,
    });
  }

  await contentPage.close();

  await extension.unload();
});