summaryrefslogtreecommitdiffstats
path: root/toolkit/mozapps/extensions/test/browser/browser_installtrigger_install.js
blob: cd2c30be7e94c6ac6aff9aa7fa013de49a9abbdf (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
/* 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 { PermissionTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/PermissionTestUtils.sys.mjs"
);

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

AddonTestUtils.initMochitest(this);

AddonTestUtils.hookAMTelemetryEvents();

add_setup(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["extensions.webapi.testing", true],
      ["extensions.install.requireBuiltInCerts", false],
      ["extensions.InstallTrigger.enabled", true],
      ["extensions.InstallTriggerImpl.enabled", true],
      // Relax the user input requirements while running this test.
      ["xpinstall.userActivation.required", false],
    ],
  });

  PermissionTestUtils.add(
    "https://example.com/",
    "install",
    Services.perms.ALLOW_ACTION
  );

  registerCleanupFunction(async () => {
    PermissionTestUtils.remove("https://example.com", "install");
    await SpecialPowers.popPrefEnv();
  });
});

async function testInstallTrigger(
  msg,
  tabURL,
  contentFnArgs,
  contentFn,
  expectedTelemetryInfo,
  expectBlockedOrigin
) {
  await BrowserTestUtils.withNewTab(tabURL, async browser => {
    if (expectBlockedOrigin) {
      const promiseOriginBlocked = TestUtils.topicObserved(
        "addon-install-origin-blocked"
      );
      await SpecialPowers.spawn(browser, contentFnArgs, contentFn);
      const [subject] = await promiseOriginBlocked;
      const installId = subject.wrappedJSObject.installs[0].installId;

      // Select all telemetry events related to the installId.
      const telemetryEvents = AddonTestUtils.getAMTelemetryEvents().filter(
        ev => {
          return (
            ev.method === "install" &&
            ev.value === `${installId}` &&
            ev.extra.step === "site_blocked"
          );
        }
      );
      ok(
        !!telemetryEvents.length,
        "Found telemetry events for the blocked install"
      );

      if (typeof expectedTelemetryInfo === "function") {
        expectedTelemetryInfo(telemetryEvents);
      } else {
        const source = telemetryEvents[0]?.extra.source;
        Assert.deepEqual(
          { source },
          expectedTelemetryInfo,
          `Got expected telemetry on test case "${msg}"`
        );
      }
      return;
    }

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

    let promptPromise = acceptAppMenuNotificationWhenShown(
      "addon-installed",
      XPI_ADDON_ID
    );

    await SpecialPowers.spawn(browser, contentFnArgs, contentFn);

    await Promise.all([installPromptPromise, promptPromise]);

    let addon = await promiseAddonByID(XPI_ADDON_ID);

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

    // Check that the expected installTelemetryInfo has been stored in the
    // addon details.
    AddonTestUtils.checkInstallInfo(
      addon,
      { method: "installTrigger", ...expectedTelemetryInfo },
      `on "${msg}"`
    );

    await addon.uninstall();
  });
}

add_task(function testInstallAfterHistoryPushState() {
  return testInstallTrigger(
    "InstallTrigger after history.pushState",
    SECURE_TESTROOT,
    [SECURE_TESTROOT, XPI_URL],
    (secureTestRoot, xpiURL) => {
      // `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
        `${secureTestRoot}?some=query&par=am`
      );
      content.InstallTrigger.install({ URL: xpiURL });
    },
    {
      source: "test-host",
      sourceURL:
        "https://example.com/browser/toolkit/mozapps/extensions/test/browser/?some=query&par=am",
    }
  );
});

add_task(async function testInstallTriggerFromSubframe() {
  function runTestCase(msg, tabURL, testFrameAttrs, expected) {
    info(
      `InstallTrigger from iframe test: ${msg} - frame attributes ${JSON.stringify(
        testFrameAttrs
      )}`
    );
    return testInstallTrigger(
      msg,
      tabURL,
      [XPI_URL, testFrameAttrs],
      async (xpiURL, frameAttrs) => {
        const frame = content.document.createElement("iframe");
        if (frameAttrs) {
          for (const attr of Object.keys(frameAttrs)) {
            let value = frameAttrs[attr];
            if (value === "blob:") {
              const blob = new content.Blob(["blob-testpage"]);
              value = content.URL.createObjectURL(blob, "text/html");
            }
            frame[attr] = value;
          }
        }
        const promiseLoaded = new Promise(resolve =>
          frame.addEventListener("load", resolve, { once: true })
        );
        content.document.body.appendChild(frame);
        await promiseLoaded;
        frame.contentWindow.InstallTrigger.install({ URL: xpiURL });
      },
      expected.telemetryInfo,
      expected.blockedOrigin
    );
  }

  // On Windows "file:///" does not load the default files index html page
  // and the test would get stuck.
  const fileURL = AppConstants.platform === "win" ? "file:///C:/" : "file:///";

  const expected = {
    http: {
      telemetryInfo: {
        source: "test-host",
        sourceURL:
          "https://example.com/browser/toolkit/mozapps/extensions/test/browser/",
      },
      blockedOrigin: false,
    },
    httpBlob: {
      telemetryInfo: {
        source: "test-host",
        // Example: "blob:https://example.com/BLOB_URL_UUID"
        sourceURL: /^blob:https:\/\/example\.com\//,
      },
      blockedOrigin: false,
    },
    file: {
      telemetryInfo: {
        source: "unknown",
        sourceURL: fileURL,
      },
      blockedOrigin: false,
    },
    fileBlob: {
      telemetryInfo: {
        source: "unknown",
        // Example: "blob:null/BLOB_URL_UUID"
        sourceURL: /^blob:null\//,
      },
      blockedOrigin: false,
    },
    httpBlockedOnOrigin: {
      telemetryInfo: {
        source: "test-host",
      },
      blockedOrigin: true,
    },
    otherBlockedOnOrigin: {
      telemetryInfo: {
        source: "unknown",
      },
      blockedOrigin: true,
    },
  };

  const testCases = [
    ["blank iframe with no attributes", SECURE_TESTROOT, {}, expected.http],

    // These are blocked by a Firefox doorhanger and the user can't allow it neither.
    [
      "http page iframe src='blob:...'",
      SECURE_TESTROOT,
      { src: "blob:" },
      expected.httpBlockedOnOrigin,
    ],
    [
      "file page iframe src='blob:...'",
      fileURL,
      { src: "blob:" },
      expected.otherBlockedOnOrigin,
    ],
    [
      "iframe srcdoc=''",
      SECURE_TESTROOT,
      { srcdoc: "" },
      expected.httpBlockedOnOrigin,
    ],
    [
      "blank iframe embedded into a top-level sandbox page",
      `${SECURE_TESTROOT}sandboxed.html`,
      {},
      expected.httpBlockedOnOrigin,
    ],
    [
      "blank iframe with sandbox='allow-scripts'",
      SECURE_TESTROOT,
      { sandbox: "allow-scripts" },
      expected.httpBlockedOnOrigin,
    ],
    [
      "iframe srcdoc='' sandbox='allow-scripts'",
      SECURE_TESTROOT,
      { srcdoc: "", sandbox: "allow-scripts" },
      expected.httpBlockedOnOrigin,
    ],
    [
      "http page iframe src='blob:...' sandbox='allow-scripts'",
      SECURE_TESTROOT,
      { src: "blob:", sandbox: "allow-scripts" },
      expected.httpBlockedOnOrigin,
    ],
    [
      "iframe src='data:...'",
      SECURE_TESTROOT,
      { src: "data:text/html,data-testpage" },
      expected.httpBlockedOnOrigin,
    ],
    [
      "blank frame embedded in a data url",
      "data:text/html,data-testpage",
      {},
      expected.otherBlockedOnOrigin,
    ],
    [
      "blank frame embedded into a about:blank page",
      "about:blank",
      {},
      expected.otherBlockedOnOrigin,
    ],
  ];

  for (const testCase of testCases) {
    await runTestCase(...testCase);
  }
});

add_task(function testInstallBlankFrameNestedIntoBlobURLPage() {
  return testInstallTrigger(
    "Blank frame nested into a blob url page",
    SECURE_TESTROOT,
    [XPI_URL],
    async xpiURL => {
      const url = content.URL.createObjectURL(
        new content.Blob(["blob-testpage"]),
        "text/html"
      );
      const topframe = content.document.createElement("iframe");
      topframe.src = url;
      const topframeLoaded = new Promise(resolve => {
        topframe.addEventListener("load", resolve, { once: true });
      });
      content.document.body.appendChild(topframe);
      await topframeLoaded;
      const subframe = topframe.contentDocument.createElement("iframe");
      topframe.contentDocument.body.appendChild(subframe);
      subframe.contentWindow.InstallTrigger.install({ URL: xpiURL });
    },
    {
      source: "test-host",
    },
    /* expectBlockedOrigin */ true
  );
});

add_task(function testInstallTriggerTopLevelDataURL() {
  return testInstallTrigger(
    "Blank frame nested into a blob url page",
    "data:text/html,testpage",
    [XPI_URL],
    async xpiURL => {
      this.content.InstallTrigger.install({ URL: xpiURL });
    },
    {
      source: "unknown",
    },
    /* expectBlockedOrigin */ true
  );
});

add_task(function teardown_clearUnexamitedTelemetry() {
  // Clear collected telemetry events when we are not going to run any assertion on them.
  // (otherwise the test will fail because of unexamined telemetry events).
  AddonTestUtils.getAMTelemetryEvents();
});