summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_legacy_extension_embedding.js
blob: ea5d7852402b5100f51848e5f125ff10d5145091 (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
"use strict";

/* globals browser */

Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm");

// Import EmbeddedExtensionManager to be able to check that the
// tacked instances are cleared after the embedded extension shutdown.
const {
  EmbeddedExtensionManager,
} = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm", {});

/**
 * This test case ensures that the LegacyExtensionsUtils.EmbeddedExtension:
 *  - load the embedded webextension resources from a "/webextension/" dir
 *    inside the XPI.
 *  - EmbeddedExtension.prototype.api returns an API object which exposes
 *    a working `runtime.onConnect` event object (e.g. the API can receive a port
 *    when the embedded webextension is started  and it can exchange messages
 *    with the background page).
 *  - EmbeddedExtension.prototype.startup/shutdown methods manage the embedded
 *    webextension lifecycle as expected.
 */
add_task(function* test_embedded_webextension_utils() {
  function backgroundScript() {
    let port = browser.runtime.connect();

    port.onMessage.addListener((msg) => {
      if (msg == "legacy_extension -> webextension") {
        port.postMessage("webextension -> legacy_extension");
        port.disconnect();
      }
    });
  }

  const id = "@test.embedded.web.extension";

  // Extensions.generateXPI is used here (and in the other hybrid addons tests in this same
  // test dir) to be able to generate an xpi with the directory layout that we expect from
  // an hybrid legacy+webextension addon (where all the embedded webextension resources are
  // loaded from a 'webextension/' directory).
  let fakeHybridAddonFile = Extension.generateZipFile({
    "webextension/manifest.json": {
      applications: {gecko: {id}},
      name: "embedded webextension name",
      manifest_version: 2,
      version: "1.0",
      background: {
        scripts: ["bg.js"],
      },
    },
    "webextension/bg.js": `new ${backgroundScript}`,
  });

  // Remove the generated xpi file and flush the its jar cache
  // on cleanup.
  do_register_cleanup(() => {
    Services.obs.notifyObservers(fakeHybridAddonFile, "flush-cache-entry", null);
    fakeHybridAddonFile.remove(false);
  });

  let fileURI = Services.io.newFileURI(fakeHybridAddonFile);
  let resourceURI = Services.io.newURI(`jar:${fileURI.spec}!/`, null, null);

  let embeddedExtension = LegacyExtensionsUtils.getEmbeddedExtensionFor({
    id, resourceURI,
  });

  ok(embeddedExtension, "Got the embeddedExtension object");

  equal(EmbeddedExtensionManager.embeddedExtensionsByAddonId.size, 1,
        "Got the expected number of tracked embedded extension instances");

  do_print("waiting embeddedExtension.startup");
  let embeddedExtensionAPI = yield embeddedExtension.startup();
  ok(embeddedExtensionAPI, "Got the embeddedExtensionAPI object");

  let waitConnectPort = new Promise(resolve => {
    let {browser} = embeddedExtensionAPI;
    browser.runtime.onConnect.addListener(port => {
      resolve(port);
    });
  });

  let port = yield waitConnectPort;

  ok(port, "Got the Port API object");

  let waitPortMessage = new Promise(resolve => {
    port.onMessage.addListener((msg) => {
      resolve(msg);
    });
  });

  port.postMessage("legacy_extension -> webextension");

  let msg = yield waitPortMessage;

  equal(msg, "webextension -> legacy_extension",
     "LegacyExtensionContext received the expected message from the webextension");

  let waitForDisconnect = new Promise(resolve => {
    port.onDisconnect.addListener(resolve);
  });

  do_print("Wait for the disconnect port event");
  yield waitForDisconnect;
  do_print("Got the disconnect port event");

  yield embeddedExtension.shutdown();

  equal(EmbeddedExtensionManager.embeddedExtensionsByAddonId.size, 0,
        "EmbeddedExtension instances has been untracked from the EmbeddedExtensionManager");
});

function* createManifestErrorTestCase(id, xpi, expectedError) {
  // Remove the generated xpi file and flush the its jar cache
  // on cleanup.
  do_register_cleanup(() => {
    Services.obs.notifyObservers(xpi, "flush-cache-entry", null);
    xpi.remove(false);
  });

  let fileURI = Services.io.newFileURI(xpi);
  let resourceURI = Services.io.newURI(`jar:${fileURI.spec}!/`, null, null);

  let embeddedExtension = LegacyExtensionsUtils.getEmbeddedExtensionFor({
    id, resourceURI,
  });

  yield Assert.rejects(embeddedExtension.startup(), expectedError,
                       "embedded extension startup rejected");

  // Shutdown a "never-started" addon with an embedded webextension should not
  // raise any exception, and if it does this test will fail.
  yield embeddedExtension.shutdown();
}

add_task(function* test_startup_error_empty_manifest() {
  const id = "empty-manifest@test.embedded.web.extension";
  const files = {
    "webextension/manifest.json": ``,
  };
  const expectedError = "(NS_BASE_STREAM_CLOSED)";

  let fakeHybridAddonFile = Extension.generateZipFile(files);

  yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError);
});

add_task(function* test_startup_error_invalid_json_manifest() {
  const id = "invalid-json-manifest@test.embedded.web.extension";
  const files = {
    "webextension/manifest.json": `{ "name": }`,
  };
  const expectedError = "JSON.parse:";

  let fakeHybridAddonFile = Extension.generateZipFile(files);

  yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError);
});

add_task(function* test_startup_error_blocking_validation_errors() {
  const id = "blocking-manifest-validation-error@test.embedded.web.extension";
  const files = {
    "webextension/manifest.json": {
      name: "embedded webextension name",
      manifest_version: 2,
      version: "1.0",
      background: {
        scripts: {},
      },
    },
  };

  function expectedError(actual) {
    if (actual.errors && actual.errors.length == 1 &&
        actual.errors[0].startsWith("Reading manifest:")) {
      return true;
    }

    return false;
  }

  let fakeHybridAddonFile = Extension.generateZipFile(files);

  yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError);
});