summaryrefslogtreecommitdiffstats
path: root/toolkit/mozapps/webextensions/test/xpcshell/test_json_updatecheck.js
blob: adf789afbefb15c554576c8de9062ecc67a6ed07 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */
"use strict";

// This verifies that AddonUpdateChecker works correctly for JSON
// update manifests, particularly for behavior which does not
// cleanly overlap with RDF manifests.

const TOOLKIT_ID = "toolkit@mozilla.org";
const TOOLKIT_MINVERSION = "42.0a1";

createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "42.0a2", "42.0a2");

Components.utils.import("resource://gre/modules/addons/AddonUpdateChecker.jsm");

let testserver = createHttpServer();
gPort = testserver.identity.primaryPort;

let gUpdateManifests = {};

function mapManifest(aPath, aManifestData) {
  gUpdateManifests[aPath] = aManifestData;
  testserver.registerPathHandler(aPath, serveManifest);
}

function serveManifest(request, response) {
  let manifest = gUpdateManifests[request.path];

  response.setHeader("Content-Type", manifest.contentType, false);
  response.write(manifest.data);
}

const extensionsDir = gProfD.clone();
extensionsDir.append("extensions");


function checkUpdates(aData) {
  // Registers JSON update manifest for it with the testing server,
  // checks for updates, and yields the list of updates on
  // success.

  let extension = aData.manifestExtension || "json";

  let path = `/updates/${aData.id}.${extension}`;
  let updateUrl = `http://localhost:${gPort}${path}`

  let addonData = {};
  if ("updates" in aData)
    addonData.updates = aData.updates;

  let manifestJSON = {
    "addons": {
      [aData.id]: addonData
    }
  };

  mapManifest(path.replace(/\?.*/, ""),
              { data: JSON.stringify(manifestJSON),
                contentType: aData.contentType || "application/json" });


  return new Promise((resolve, reject) => {
    AddonUpdateChecker.checkForUpdates(aData.id, aData.updateKey, updateUrl, {
      onUpdateCheckComplete: resolve,

      onUpdateCheckError: function(status) {
        reject(new Error("Update check failed with status " + status));
      }
    });
  });
}


add_task(function* test_default_values() {
  // Checks that the appropriate defaults are used for omitted values.

  startupManager();

  let updates = yield checkUpdates({
    id: "updatecheck-defaults@tests.mozilla.org",
    version: "0.1",
    updates: [{
      version: "0.2"
    }]
  });

  equal(updates.length, 1);
  let update = updates[0];

  equal(update.targetApplications.length, 1);
  let targetApp = update.targetApplications[0];

  equal(targetApp.id, TOOLKIT_ID);
  equal(targetApp.minVersion, TOOLKIT_MINVERSION);
  equal(targetApp.maxVersion, "*");

  equal(update.version, "0.2");
  equal(update.multiprocessCompatible, true, "multiprocess_compatible flag");
  equal(update.strictCompatibility, false, "inferred strictConpatibility flag");
  equal(update.updateURL, null, "updateURL");
  equal(update.updateHash, null, "updateHash");
  equal(update.updateInfoURL, null, "updateInfoURL");

  // If there's no applications property, we default to using one
  // containing "gecko". If there is an applications property, but
  // it doesn't contain "gecko", the update is skipped.
  updates = yield checkUpdates({
    id: "updatecheck-defaults@tests.mozilla.org",
    version: "0.1",
    updates: [{
      version: "0.2",
      applications: { "foo": {} }
    }]
  });

  equal(updates.length, 0);

  // Updates property is also optional. No updates, but also no error.
  updates = yield checkUpdates({
    id: "updatecheck-defaults@tests.mozilla.org",
    version: "0.1",
  });

  equal(updates.length, 0);
});


add_task(function* test_explicit_values() {
  // Checks that the appropriate explicit values are used when
  // provided.

  let updates = yield checkUpdates({
    id: "updatecheck-explicit@tests.mozilla.org",
    version: "0.1",
    updates: [{
      version: "0.2",
      update_link: "https://example.com/foo.xpi",
      update_hash: "sha256:0",
      update_info_url: "https://example.com/update_info.html",
      multiprocess_compatible: false,
      applications: {
        gecko: {
          strict_min_version: "42.0a2.xpcshell",
          strict_max_version: "43.xpcshell"
        }
      }
    }]
  });

  equal(updates.length, 1);
  let update = updates[0];

  equal(update.targetApplications.length, 1);
  let targetApp = update.targetApplications[0];

  equal(targetApp.id, TOOLKIT_ID);
  equal(targetApp.minVersion, "42.0a2.xpcshell");
  equal(targetApp.maxVersion, "43.xpcshell");

  equal(update.version, "0.2");
  equal(update.multiprocessCompatible, false, "multiprocess_compatible flag");
  equal(update.strictCompatibility, true, "inferred strictCompatibility flag");
  equal(update.updateURL, "https://example.com/foo.xpi", "updateURL");
  equal(update.updateHash, "sha256:0", "updateHash");
  equal(update.updateInfoURL, "https://example.com/update_info.html", "updateInfoURL");
});


add_task(function* test_secure_hashes() {
  // Checks that only secure hash functions are accepted for
  // non-secure update URLs.

  let hashFunctions = ["sha512",
                       "sha256",
                       "sha1",
                       "md5",
                       "md4",
                       "xxx"];

  let updateItems = hashFunctions.map((hash, idx) => ({
    version: `0.${idx}`,
    update_link: `http://localhost:${gPort}/updates/${idx}-${hash}.xpi`,
    update_hash: `${hash}:08ac852190ecd81f40a514ea9299fe9143d9ab5e296b97e73fb2a314de49648a`,
  }));

  let { messages, result: updates } = yield promiseConsoleOutput(() => {
    return checkUpdates({
      id: "updatecheck-hashes@tests.mozilla.org",
      version: "0.1",
      updates: updateItems
    });
  });

  equal(updates.length, hashFunctions.length);

  updates = updates.filter(update => update.updateHash || update.updateURL);
  equal(updates.length, 2, "expected number of update hashes were accepted");

  ok(updates[0].updateHash.startsWith("sha512:"), "sha512 hash is present");
  ok(updates[0].updateURL);

  ok(updates[1].updateHash.startsWith("sha256:"), "sha256 hash is present");
  ok(updates[1].updateURL);

  messages = messages.filter(msg => /Update link.*not secure.*strong enough hash \(needs to be sha256 or sha512\)/.test(msg.message));
  equal(messages.length, hashFunctions.length - 2, "insecure hashes generated the expected warning");
});


add_task(function* test_strict_compat() {
  // Checks that strict compatibility is enabled for strict max
  // versions other than "*", but not for advisory max versions.
  // Also, ensure that strict max versions take precedence over
  // advisory versions.

  let { messages, result: updates } = yield promiseConsoleOutput(() => {
    return checkUpdates({
      id: "updatecheck-strict@tests.mozilla.org",
      version: "0.1",
      updates: [
        { version: "0.2",
          applications: { gecko: { strict_max_version: "*" } } },
        { version: "0.3",
          applications: { gecko: { strict_max_version: "43" } } },
        { version: "0.4",
          applications: { gecko: { advisory_max_version: "43" } } },
        { version: "0.5",
          applications: { gecko: { advisory_max_version: "43",
                                   strict_max_version: "44" } } },
      ]
    });
  });

  equal(updates.length, 4, "all update items accepted");

  equal(updates[0].targetApplications[0].maxVersion, "*");
  equal(updates[0].strictCompatibility, false);

  equal(updates[1].targetApplications[0].maxVersion, "43");
  equal(updates[1].strictCompatibility, true);

  equal(updates[2].targetApplications[0].maxVersion, "43");
  equal(updates[2].strictCompatibility, false);

  equal(updates[3].targetApplications[0].maxVersion, "44");
  equal(updates[3].strictCompatibility, true);

  messages = messages.filter(msg => /Ignoring 'advisory_max_version'.*'strict_max_version' also present/.test(msg.message));
  equal(messages.length, 1, "mix of advisory_max_version and strict_max_version generated the expected warning");
});


add_task(function* test_update_url_security() {
  // Checks that update links to privileged URLs are not accepted.

  let { messages, result: updates } = yield promiseConsoleOutput(() => {
    return checkUpdates({
      id: "updatecheck-security@tests.mozilla.org",
      version: "0.1",
      updates: [
        { version: "0.2",
          update_link: "chrome://browser/content/browser.xul",
          update_hash: "sha256:08ac852190ecd81f40a514ea9299fe9143d9ab5e296b97e73fb2a314de49648a" },
        { version: "0.3",
          update_link: "http://example.com/update.xpi",
          update_hash: "sha256:18ac852190ecd81f40a514ea9299fe9143d9ab5e296b97e73fb2a314de49648a" },
      ]
    });
  });

  equal(updates.length, 2, "both updates were processed");
  equal(updates[0].updateURL, null, "privileged update URL was removed");
  equal(updates[1].updateURL, "http://example.com/update.xpi", "safe update URL was accepted");

  messages = messages.filter(msg => /http:\/\/localhost.*\/updates\/.*may not load or link to chrome:/.test(msg.message));
  equal(messages.length, 1, "privileged upate URL generated the expected console message");
});


add_task(function* test_no_update_key() {
  // Checks that updates fail when an update key has been specified.

  let { messages } = yield promiseConsoleOutput(function* () {
    yield Assert.rejects(
      checkUpdates({
        id: "updatecheck-updatekey@tests.mozilla.org",
        version: "0.1",
        updateKey: "ayzzx=",
        updates: [
          { version: "0.2" },
          { version: "0.3" },
        ]
      }),
      null, "updated expected to fail");
  });

  messages = messages.filter(msg => /Update keys are not supported for JSON update manifests/.test(msg.message));
  equal(messages.length, 1, "got expected update-key-unsupported error");
});


add_task(function* test_type_detection() {
  // Checks that JSON update manifests are detected correctly
  // regardless of extension or MIME type.

  let tests = [
    { contentType: "application/json",
      extension: "json",
      valid: true },
    { contentType: "application/json",
      extension: "php",
      valid: true },
    { contentType: "text/plain",
      extension: "json",
      valid: true },
    { contentType: "application/octet-stream",
      extension: "json",
      valid: true },
    { contentType: "text/plain",
      extension: "json?foo=bar",
      valid: true },
    { contentType: "text/plain",
      extension: "php",
      valid: true },
    { contentType: "text/plain",
      extension: "rdf",
      valid: true },
    { contentType: "application/json",
      extension: "rdf",
      valid: true },
    { contentType: "text/xml",
      extension: "json",
      valid: true },
    { contentType: "application/rdf+xml",
      extension: "json",
      valid: true },
  ];

  for (let [i, test] of tests.entries()) {
    let { messages } = yield promiseConsoleOutput(function *() {
      let id = `updatecheck-typedetection-${i}@tests.mozilla.org`;
      let updates;
      try {
        updates = yield checkUpdates({
          id: id,
          version: "0.1",
          contentType: test.contentType,
          manifestExtension: test.extension,
          updates: [{ version: "0.2" }]
        });
      } catch (e) {
        ok(!test.valid, "update manifest correctly detected as RDF");
        return;
      }

      ok(test.valid, "update manifest correctly detected as JSON");
      equal(updates.length, 1, "correct number of updates");
      equal(updates[0].id, id, "update is for correct extension");
    });

    if (test.valid) {
      // Make sure we don't get any XML parsing errors from the
      // XMLHttpRequest machinery.
      ok(!messages.some(msg => /not well-formed/.test(msg.message)),
         "expect XMLHttpRequest not to attempt XML parsing");
    }

    messages = messages.filter(msg => /Update manifest was not valid XML/.test(msg.message));
    equal(messages.length, !test.valid, "expected number of XML parsing errors");
  }
});