summaryrefslogtreecommitdiffstats
path: root/toolkit/mozapps/extensions/test/browser/browser_webapi_install.js
blob: 7a151347cc3ccaf7f3ee8f7531f6a62faa9e7da5 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

"use strict";

const { AddonTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/AddonTestUtils.sys.mjs"
);

const { EnterprisePolicyTesting } = ChromeUtils.importESModule(
  "resource://testing-common/EnterprisePolicyTesting.sys.mjs"
);

const TESTPATH = "webapi_checkavailable.html";
const TESTPAGE = `${SECURE_TESTROOT}${TESTPATH}`;
const XPI_URL = `${SECURE_TESTROOT}../xpinstall/amosigned.xpi`;
const XPI_ADDON_ID = "amosigned-xpi@tests.mozilla.org";

const XPI_SHA =
  "sha256:91121ed2c27f670f2307b9aebdd30979f147318c7fb9111c254c14ddbb84e4b0";

const ID = "amosigned-xpi@tests.mozilla.org";
// eh, would be good to just stat the real file instead of this...
const XPI_LEN = 4287;

AddonTestUtils.initMochitest(this);

function waitForClear() {
  const MSG = "WebAPICleanup";
  return new Promise(resolve => {
    let listener = {
      receiveMessage(msg) {
        if (msg.name == MSG) {
          Services.mm.removeMessageListener(MSG, listener);
          resolve();
        }
      },
    };

    Services.mm.addMessageListener(MSG, listener, true);
  });
}

add_setup(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["extensions.webapi.testing", true],
      ["extensions.install.requireBuiltInCerts", false],
    ],
  });
  info("added preferences");
});

// Wrapper around a common task to run in the content process to test
// the mozAddonManager API.  Takes a URL for the XPI to install and an
// array of steps, each of which can either be an action to take
// (i.e., start or cancel the install) or an install event to wait for.
// Steps that look for a specific event may also include a "props" property
// with properties that the AddonInstall object is expected to have when
// that event is triggered.
async function testInstall(browser, args, steps, description) {
  let success = await SpecialPowers.spawn(
    browser,
    [{ args, steps }],
    async function (opts) {
      let { args, steps } = opts;
      let install = await content.navigator.mozAddonManager.createInstall(args);
      if (!install) {
        await Promise.reject(
          "createInstall() did not return an install object"
        );
      }

      // Check that the initial state of the AddonInstall is sane.
      if (install.state != "STATE_AVAILABLE") {
        await Promise.reject("new install should be in STATE_AVAILABLE");
      }
      if (install.error != null) {
        await Promise.reject("new install should have null error");
      }

      const events = [
        "onDownloadStarted",
        "onDownloadProgress",
        "onDownloadEnded",
        "onDownloadCancelled",
        "onDownloadFailed",
        "onInstallStarted",
        "onInstallEnded",
        "onInstallCancelled",
        "onInstallFailed",
      ];
      let eventWaiter = null;
      let receivedEvents = [];
      let prevEvent = null;
      events.forEach(event => {
        install.addEventListener(event, e => {
          receivedEvents.push({
            event,
            state: install.state,
            error: install.error,
            progress: install.progress,
            maxProgress: install.maxProgress,
          });
          if (eventWaiter) {
            eventWaiter();
          }
        });
      });

      // Returns a promise that is resolved when the given event occurs
      // or rejects if a different event comes first or if props is supplied
      // and properties on the AddonInstall don't match those in props.
      function expectEvent(event, props) {
        return new Promise((resolve, reject) => {
          function check() {
            let received = receivedEvents.shift();
            // Skip any repeated onDownloadProgress events.
            while (
              received &&
              received.event == prevEvent &&
              prevEvent == "onDownloadProgress"
            ) {
              received = receivedEvents.shift();
            }
            // Wait for more events if we skipped all there were.
            if (!received) {
              eventWaiter = () => {
                eventWaiter = null;
                check();
              };
              return;
            }
            prevEvent = received.event;
            if (received.event != event) {
              let err = new Error(
                `expected ${event} but got ${received.event}`
              );
              reject(err);
            }
            if (props) {
              for (let key of Object.keys(props)) {
                if (received[key] != props[key]) {
                  throw new Error(
                    `AddonInstall property ${key} was ${received[key]} but expected ${props[key]}`
                  );
                }
              }
            }
            resolve();
          }
          check();
        });
      }

      while (steps.length) {
        let nextStep = steps.shift();
        if (nextStep.action) {
          if (nextStep.action == "install") {
            try {
              await install.install();
              if (nextStep.expectError) {
                throw new Error("Expected install to fail but it did not");
              }
            } catch (err) {
              if (!nextStep.expectError) {
                throw new Error("Install failed unexpectedly");
              }
            }
          } else if (nextStep.action == "cancel") {
            await install.cancel();
          } else {
            throw new Error(`unknown action ${nextStep.action}`);
          }
        } else {
          await expectEvent(nextStep.event, nextStep.props);
        }
      }

      return true;
    }
  );

  is(success, true, description);
}

function makeInstallTest(task) {
  return async function () {
    // withNewTab() will close the test tab before returning, at which point
    // the cleanup event will come from the content process.  We need to see
    // that event but don't want to race to install a listener for it after
    // the tab is closed.  So set up the listener now but don't yield the
    // listening promise until below.
    let clearPromise = waitForClear();

    await BrowserTestUtils.withNewTab(TESTPAGE, task);

    await clearPromise;
    is(AddonManager.webAPI.installs.size, 0, "AddonInstall was cleaned up");
  };
}

function makeRegularTest(options, what) {
  return makeInstallTest(async function (browser) {
    let steps = [
      { action: "install" },
      {
        event: "onDownloadStarted",
        props: { state: "STATE_DOWNLOADING" },
      },
      {
        event: "onDownloadProgress",
        props: { maxProgress: XPI_LEN },
      },
      {
        event: "onDownloadEnded",
        props: {
          state: "STATE_DOWNLOADED",
          progress: XPI_LEN,
          maxProgress: XPI_LEN,
        },
      },
      {
        event: "onInstallStarted",
        props: { state: "STATE_INSTALLING" },
      },
      {
        event: "onInstallEnded",
        props: { state: "STATE_INSTALLED" },
      },
    ];

    let installPromptPromise = promisePopupNotificationShown(
      "addon-webext-permissions"
    ).then(panel => {
      panel.button.click();
    });

    let promptPromise = acceptAppMenuNotificationWhenShown(
      "addon-installed",
      options.addonId
    );

    await testInstall(browser, options, steps, what);

    await installPromptPromise;

    await promptPromise;

    // Sanity check to ensure that the test in makeInstallTest() that
    // installs.size == 0 means we actually did clean up.
    ok(
      AddonManager.webAPI.installs.size > 0,
      "webAPI is tracking the AddonInstall"
    );

    let addon = await promiseAddonByID(ID);
    isnot(addon, null, "Found the addon");

    // Check that the expected installTelemetryInfo has been stored in the addon details.
    AddonTestUtils.checkInstallInfo(addon, {
      method: "amWebAPI",
      source: "test-host",
      sourceURL: /https:\/\/example.com\/.*\/webapi_checkavailable.html/,
    });

    await addon.uninstall();

    addon = await promiseAddonByID(ID);
    is(addon, null, "Addon was uninstalled");
  });
}

let addonId = XPI_ADDON_ID;
add_task(makeRegularTest({ url: XPI_URL, addonId }, "a basic install works"));
add_task(
  makeRegularTest(
    { url: XPI_URL, addonId, hash: null },
    "install with hash=null works"
  )
);
add_task(
  makeRegularTest(
    { url: XPI_URL, addonId, hash: "" },
    "install with empty string for hash works"
  )
);
add_task(
  makeRegularTest(
    { url: XPI_URL, addonId, hash: XPI_SHA },
    "install with hash works"
  )
);

add_task(
  makeInstallTest(async function (browser) {
    let steps = [
      { action: "cancel" },
      {
        event: "onDownloadCancelled",
        props: {
          state: "STATE_CANCELLED",
          error: null,
        },
      },
    ];

    await testInstall(
      browser,
      { url: XPI_URL },
      steps,
      "canceling an install works"
    );

    let addons = await promiseAddonsByIDs([ID]);
    is(addons[0], null, "The addon was not installed");

    ok(
      AddonManager.webAPI.installs.size > 0,
      "webAPI is tracking the AddonInstall"
    );
  })
);

add_task(
  makeInstallTest(async function (browser) {
    let steps = [
      { action: "install", expectError: true },
      {
        event: "onDownloadStarted",
        props: { state: "STATE_DOWNLOADING" },
      },
      { event: "onDownloadProgress" },
      {
        event: "onDownloadFailed",
        props: {
          state: "STATE_DOWNLOAD_FAILED",
          error: "ERROR_NETWORK_FAILURE",
        },
      },
    ];

    await testInstall(
      browser,
      { url: XPI_URL + "bogus" },
      steps,
      "install of a bad url fails"
    );

    let addons = await promiseAddonsByIDs([ID]);
    is(addons[0], null, "The addon was not installed");

    ok(
      AddonManager.webAPI.installs.size > 0,
      "webAPI is tracking the AddonInstall"
    );
  })
);

add_task(
  makeInstallTest(async function (browser) {
    let steps = [
      { action: "install", expectError: true },
      {
        event: "onDownloadStarted",
        props: { state: "STATE_DOWNLOADING" },
      },
      { event: "onDownloadProgress" },
      {
        event: "onDownloadFailed",
        props: {
          state: "STATE_DOWNLOAD_FAILED",
          error: "ERROR_INCORRECT_HASH",
        },
      },
    ];

    await testInstall(
      browser,
      { url: XPI_URL, hash: "sha256:bogus" },
      steps,
      "install with bad hash fails"
    );

    let addons = await promiseAddonsByIDs([ID]);
    is(addons[0], null, "The addon was not installed");

    ok(
      AddonManager.webAPI.installs.size > 0,
      "webAPI is tracking the AddonInstall"
    );
  })
);

add_task(async function test_permissions_and_policy() {
  async function testBadUrl(url, pattern, successMessage) {
    gBrowser.selectedTab = await BrowserTestUtils.addTab(gBrowser, TESTPAGE);
    let browser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
    await BrowserTestUtils.browserLoaded(browser);
    let result = await SpecialPowers.spawn(
      browser,
      [{ url, pattern }],
      function (opts) {
        return new Promise(resolve => {
          content.navigator.mozAddonManager
            .createInstall({ url: opts.url })
            .then(
              () => {
                resolve({
                  success: false,
                  message: "createInstall should not have succeeded",
                });
              },
              err => {
                if (err.message.match(new RegExp(opts.pattern))) {
                  resolve({ success: true });
                }
                resolve({
                  success: false,
                  message: `Wrong error message: ${err.message}`,
                });
              }
            );
        });
      }
    );
    is(result.success, true, result.message || successMessage);
  }

  await testBadUrl(
    "i am not a url",
    "NS_ERROR_MALFORMED_URI",
    "Installing from an unparseable URL fails"
  );
  gBrowser.removeTab(gBrowser.selectedTab);

  let popupPromise = promisePopupNotificationShown(
    "addon-install-webapi-blocked"
  );
  await Promise.all([
    testBadUrl(
      "https://addons.not-really-mozilla.org/impostor.xpi",
      "not permitted",
      "Installing from non-approved URL fails"
    ),
    popupPromise,
  ]);

  gBrowser.removeTab(gBrowser.selectedTab);

  const blocked_install_message = "Custom Policy Block Message";

  await EnterprisePolicyTesting.setupPolicyEngineWithJson({
    policies: {
      ExtensionSettings: {
        "*": {
          install_sources: [],
          blocked_install_message,
        },
      },
    },
  });

  popupPromise = promisePopupNotificationShown("addon-install-policy-blocked");

  await testBadUrl(
    XPI_URL,
    "not permitted by policy",
    "Installing from policy blocked origin fails"
  );

  const panel = await popupPromise;
  const description = panel.querySelector(
    ".popup-notification-description"
  ).textContent;
  ok(
    description.startsWith("Your system administrator"),
    "Policy specific error is shown."
  );
  ok(
    description.endsWith(` ${blocked_install_message}`),
    `Found the expected custom blocked message in "${description}"`
  );

  gBrowser.removeTab(gBrowser.selectedTab);

  await EnterprisePolicyTesting.setupPolicyEngineWithJson({
    policies: {
      ExtensionSettings: {
        "*": {
          install_sources: ["<all_urls>"],
        },
      },
    },
  });
});

add_task(
  makeInstallTest(async function (browser) {
    let xpiURL = `${SECURE_TESTROOT}../xpinstall/incompatible.xpi`;
    let id = "incompatible-xpi@tests.mozilla.org";

    let steps = [
      { action: "install", expectError: true },
      {
        event: "onDownloadStarted",
        props: { state: "STATE_DOWNLOADING" },
      },
      { event: "onDownloadProgress" },
      { event: "onDownloadEnded" },
      { event: "onDownloadCancelled" },
    ];

    await testInstall(
      browser,
      { url: xpiURL },
      steps,
      "install of an incompatible XPI fails"
    );

    let addons = await promiseAddonsByIDs([id]);
    is(addons[0], null, "The addon was not installed");
  })
);

add_task(
  makeInstallTest(async function (browser) {
    const options = { url: XPI_URL, addonId };
    let steps = [
      { action: "install" },
      {
        event: "onDownloadStarted",
        props: { state: "STATE_DOWNLOADING" },
      },
      {
        event: "onDownloadProgress",
        props: { maxProgress: XPI_LEN },
      },
      {
        event: "onDownloadEnded",
        props: {
          state: "STATE_DOWNLOADED",
          progress: XPI_LEN,
          maxProgress: XPI_LEN,
        },
      },
      {
        event: "onInstallStarted",
        props: { state: "STATE_INSTALLING" },
      },
      {
        event: "onInstallEnded",
        props: { state: "STATE_INSTALLED" },
      },
    ];

    await SpecialPowers.spawn(browser, [TESTPATH], testPath => {
      // `sourceURL` should match the exact location, even after a location
      // update using the history API. In this case, we update the URL with
      // query parameters and expect `sourceURL` to contain those parameters.
      content.history.pushState(
        {}, // state
        "", // title
        `/${testPath}?some=query&par=am`
      );
    });

    let installPromptPromise = promisePopupNotificationShown(
      "addon-webext-permissions"
    ).then(panel => {
      panel.button.click();
    });

    let promptPromise = acceptAppMenuNotificationWhenShown(
      "addon-installed",
      options.addonId
    );

    await Promise.all([
      testInstall(browser, options, steps, "install to check source URL"),
      installPromptPromise,
      promptPromise,
    ]);

    let addon = await promiseAddonByID(ID);

    registerCleanupFunction(async () => {
      await addon.uninstall();
    });

    // Check that the expected installTelemetryInfo has been stored in the
    // addon details.
    AddonTestUtils.checkInstallInfo(addon, {
      method: "amWebAPI",
      source: "test-host",
      sourceURL:
        "https://example.com/webapi_checkavailable.html?some=query&par=am",
    });
  })
);