summaryrefslogtreecommitdiffstats
path: root/toolkit/components/downloads/test/unit/test_DownloadStore.js
blob: 9353b630607794a586fd0255fbe52ace78d6bdc0 (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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

/**
 * Tests the DownloadStore object.
 */

"use strict";

// Globals

ChromeUtils.defineESModuleGetters(this, {
  DownloadError: "resource://gre/modules/DownloadCore.sys.mjs",
  DownloadStore: "resource://gre/modules/DownloadStore.sys.mjs",
});

/**
 * Returns a new DownloadList object with an associated DownloadStore.
 *
 * @param aStorePath
 *        String pointing to the file to be associated with the DownloadStore,
 *        or undefined to use a non-existing temporary file.  In this case, the
 *        temporary file is deleted when the test file execution finishes.
 *
 * @return {Promise}
 * @resolves Array [ Newly created DownloadList , associated DownloadStore ].
 * @rejects JavaScript exception.
 */
function promiseNewListAndStore(aStorePath) {
  return promiseNewList().then(function (aList) {
    let path = aStorePath || getTempFile(TEST_STORE_FILE_NAME).path;
    let store = new DownloadStore(aList, path);
    return [aList, store];
  });
}

// Tests

/**
 * Saves downloads to a file, then reloads them.
 */
add_task(async function test_save_reload() {
  let [listForSave, storeForSave] = await promiseNewListAndStore();
  let [listForLoad, storeForLoad] = await promiseNewListAndStore(
    storeForSave.path
  );
  let referrerInfo = new ReferrerInfo(
    Ci.nsIReferrerInfo.EMPTY,
    true,
    NetUtil.newURI(TEST_REFERRER_URL)
  );

  listForSave.add(await promiseNewDownload(httpUrl("source.txt")));
  listForSave.add(
    await Downloads.createDownload({
      source: { url: httpUrl("empty.txt"), referrerInfo },
      target: getTempFile(TEST_TARGET_FILE_NAME),
    })
  );

  // If we used a callback to adjust the channel, the download should
  // not be serialized because we can't recreate it across sessions.
  let adjustedDownload = await Downloads.createDownload({
    source: {
      url: httpUrl("empty.txt"),
      adjustChannel: () => Promise.resolve(),
    },
    target: getTempFile(TEST_TARGET_FILE_NAME),
  });
  listForSave.add(adjustedDownload);

  let legacyDownload = await promiseStartLegacyDownload();
  await legacyDownload.cancel();
  listForSave.add(legacyDownload);

  await storeForSave.save();
  await storeForLoad.load();

  // Remove the adjusted download because it should not appear here.
  listForSave.remove(adjustedDownload);

  let itemsForSave = await listForSave.getAll();
  let itemsForLoad = await listForLoad.getAll();

  Assert.equal(itemsForSave.length, itemsForLoad.length);

  // Downloads should be reloaded in the same order.
  for (let i = 0; i < itemsForSave.length; i++) {
    // The reloaded downloads are different objects.
    Assert.notEqual(itemsForSave[i], itemsForLoad[i]);

    // The reloaded downloads have the same properties.
    Assert.equal(itemsForSave[i].source.url, itemsForLoad[i].source.url);
    Assert.equal(
      !!itemsForSave[i].source.referrerInfo,
      !!itemsForLoad[i].source.referrerInfo
    );
    if (
      itemsForSave[i].source.referrerInfo &&
      itemsForLoad[i].source.referrerInfo
    ) {
      Assert.ok(
        itemsForSave[i].source.referrerInfo.equals(
          itemsForLoad[i].source.referrerInfo
        )
      );
    }
    Assert.equal(itemsForSave[i].target.path, itemsForLoad[i].target.path);
    Assert.equal(
      itemsForSave[i].saver.toSerializable(),
      itemsForLoad[i].saver.toSerializable()
    );
  }
});

/**
 * Checks that saving an empty list deletes any existing file.
 */
add_task(async function test_save_empty() {
  let [, store] = await promiseNewListAndStore();

  await IOUtils.write(store.path, new Uint8Array());

  await store.save();

  let successful;
  try {
    await IOUtils.read(store.path);
    successful = true;
  } catch (ex) {
    successful = ex.name != "NotFoundError";
  }

  ok(!successful, "File should not exist");

  // If the file does not exist, saving should not generate exceptions.
  await store.save();
});

/**
 * Checks that loading from a missing file results in an empty list.
 */
add_task(async function test_load_empty() {
  let [list, store] = await promiseNewListAndStore();

  let succeesful;
  try {
    await IOUtils.read(store.path);
    succeesful = true;
  } catch (ex) {
    succeesful = ex.name != "NotFoundError";
  }

  ok(!succeesful, "File should not exist");

  let items = await list.getAll();
  Assert.equal(items.length, 0);
});

/**
 * Loads downloads from a string in a predefined format.  The purpose of this
 * test is to verify that the JSON format used in previous versions can be
 * loaded, assuming the file is reloaded on the same platform.
 */
add_task(async function test_load_string_predefined() {
  let [list, store] = await promiseNewListAndStore();

  // The platform-dependent file name should be generated dynamically.
  let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
  let filePathLiteral = JSON.stringify(targetPath);
  let sourceUriLiteral = JSON.stringify(httpUrl("source.txt"));
  let emptyUriLiteral = JSON.stringify(httpUrl("empty.txt"));
  let referrerInfo = new ReferrerInfo(
    Ci.nsIReferrerInfo.EMPTY,
    true,
    NetUtil.newURI(TEST_REFERRER_URL)
  );
  let referrerInfoLiteral = JSON.stringify(
    E10SUtils.serializeReferrerInfo(referrerInfo)
  );

  let string =
    '{"list":[{"source":' +
    sourceUriLiteral +
    "," +
    '"target":' +
    filePathLiteral +
    "}," +
    '{"source":{"url":' +
    emptyUriLiteral +
    "," +
    '"referrerInfo":' +
    referrerInfoLiteral +
    "}," +
    '"target":' +
    filePathLiteral +
    "}]}";

  await IOUtils.write(store.path, new TextEncoder().encode(string), {
    tmpPath: store.path + ".tmp",
  });

  await store.load();

  let items = await list.getAll();

  Assert.equal(items.length, 2);

  Assert.equal(items[0].source.url, httpUrl("source.txt"));
  Assert.equal(items[0].target.path, targetPath);

  Assert.equal(items[1].source.url, httpUrl("empty.txt"));

  checkEqualReferrerInfos(items[1].source.referrerInfo, referrerInfo);
  Assert.equal(items[1].target.path, targetPath);
});

/**
 * Loads downloads from a well-formed JSON string containing unrecognized data.
 */
add_task(async function test_load_string_unrecognized() {
  let [list, store] = await promiseNewListAndStore();

  // The platform-dependent file name should be generated dynamically.
  let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
  let filePathLiteral = JSON.stringify(targetPath);
  let sourceUriLiteral = JSON.stringify(httpUrl("source.txt"));

  let string =
    '{"list":[{"source":null,' +
    '"target":null},' +
    '{"source":{"url":' +
    sourceUriLiteral +
    "}," +
    '"target":{"path":' +
    filePathLiteral +
    "}," +
    '"saver":{"type":"copy"}}]}';

  await IOUtils.write(store.path, new TextEncoder().encode(string), {
    tmpPath: store.path + ".tmp",
  });

  await store.load();

  let items = await list.getAll();

  Assert.equal(items.length, 1);

  Assert.equal(items[0].source.url, httpUrl("source.txt"));
  Assert.equal(items[0].target.path, targetPath);
});

/**
 * Loads downloads from a malformed JSON string.
 */
add_task(async function test_load_string_malformed() {
  let [list, store] = await promiseNewListAndStore();

  let string =
    '{"list":[{"source":null,"target":null},' +
    '{"source":{"url":"about:blank"}}}';

  await IOUtils.write(store.path, new TextEncoder().encode(string), {
    tmpPath: store.path + ".tmp",
  });

  try {
    await store.load();
    do_throw("Exception expected when JSON data is malformed.");
  } catch (ex) {
    if (ex.name != "SyntaxError") {
      throw ex;
    }
    info("The expected SyntaxError exception was thrown.");
  }

  let items = await list.getAll();

  Assert.equal(items.length, 0);
});

/**
 * Saves downloads with unknown properties to a file and then reloads
 * them to ensure that these properties are preserved.
 */
add_task(async function test_save_reload_unknownProperties() {
  let [listForSave, storeForSave] = await promiseNewListAndStore();
  let [listForLoad, storeForLoad] = await promiseNewListAndStore(
    storeForSave.path
  );

  let download1 = await promiseNewDownload(httpUrl("source.txt"));
  // startTime should be ignored as it is a known property, and error
  // is ignored by serialization
  download1._unknownProperties = {
    peanut: "butter",
    orange: "marmalade",
    startTime: 77,
    error: { message: "Passed" },
  };
  listForSave.add(download1);

  let download2 = await promiseStartLegacyDownload();
  await download2.cancel();
  download2._unknownProperties = { number: 5, object: { test: "string" } };
  listForSave.add(download2);

  let referrerInfo = new ReferrerInfo(
    Ci.nsIReferrerInfo.EMPTY,
    true,
    NetUtil.newURI(TEST_REFERRER_URL)
  );
  let download3 = await Downloads.createDownload({
    source: {
      url: httpUrl("empty.txt"),
      referrerInfo,
      source1: "download3source1",
      source2: "download3source2",
    },
    target: {
      path: getTempFile(TEST_TARGET_FILE_NAME).path,
      target1: "download3target1",
      target2: "download3target2",
    },
    saver: {
      type: "copy",
      saver1: "download3saver1",
      saver2: "download3saver2",
    },
  });
  listForSave.add(download3);

  await storeForSave.save();
  await storeForLoad.load();

  let itemsForSave = await listForSave.getAll();
  let itemsForLoad = await listForLoad.getAll();

  Assert.equal(itemsForSave.length, itemsForLoad.length);

  Assert.equal(Object.keys(itemsForLoad[0]._unknownProperties).length, 2);
  Assert.equal(itemsForLoad[0]._unknownProperties.peanut, "butter");
  Assert.equal(itemsForLoad[0]._unknownProperties.orange, "marmalade");
  Assert.equal(false, "startTime" in itemsForLoad[0]._unknownProperties);
  Assert.equal(false, "error" in itemsForLoad[0]._unknownProperties);

  Assert.equal(Object.keys(itemsForLoad[1]._unknownProperties).length, 2);
  Assert.equal(itemsForLoad[1]._unknownProperties.number, 5);
  Assert.equal(itemsForLoad[1]._unknownProperties.object.test, "string");

  Assert.equal(
    Object.keys(itemsForLoad[2].source._unknownProperties).length,
    2
  );
  Assert.equal(
    itemsForLoad[2].source._unknownProperties.source1,
    "download3source1"
  );
  Assert.equal(
    itemsForLoad[2].source._unknownProperties.source2,
    "download3source2"
  );

  Assert.equal(
    Object.keys(itemsForLoad[2].target._unknownProperties).length,
    2
  );
  Assert.equal(
    itemsForLoad[2].target._unknownProperties.target1,
    "download3target1"
  );
  Assert.equal(
    itemsForLoad[2].target._unknownProperties.target2,
    "download3target2"
  );

  Assert.equal(Object.keys(itemsForLoad[2].saver._unknownProperties).length, 2);
  Assert.equal(
    itemsForLoad[2].saver._unknownProperties.saver1,
    "download3saver1"
  );
  Assert.equal(
    itemsForLoad[2].saver._unknownProperties.saver2,
    "download3saver2"
  );
});

/**
 * Saves insecure downloads to a file, then reloads the file and checks if they
 * are still there.
 */
add_task(async function test_insecure_download_deletion() {
  let [listForSave, storeForSave] = await promiseNewListAndStore();
  let [listForLoad, storeForLoad] = await promiseNewListAndStore(
    storeForSave.path
  );
  let referrerInfo = new ReferrerInfo(
    Ci.nsIReferrerInfo.EMPTY,
    true,
    NetUtil.newURI(TEST_REFERRER_URL)
  );

  const createTestDownload = async startTime => {
    // Create a valid test download and start it so it creates a file
    let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
    let download = await Downloads.createDownload({
      source: { url: httpUrl("empty.txt"), referrerInfo },
      target: targetFile.path,
      startTime: new Date().toISOString(),
      contentType: "application/zip",
    });
    await download.start();

    // Add an "Insecure Download" error and overwrite the start time for
    // serialization
    download.hasBlockedData = true;
    download.error = DownloadError.fromSerializable({
      becauseBlockedByReputationCheck: true,
      reputationCheckVerdict: "Insecure",
    });
    download.startTime = startTime;

    let targetPath = download.target.path;

    // Add download to store, save, load and retrieve deserialized download list
    listForSave.add(download);
    await storeForSave.save();
    await storeForLoad.load();
    let loadedDownloadList = await listForLoad.getAll();

    return [loadedDownloadList, targetPath];
  };

  // Insecure downloads that are older than 5 minutes should get removed from
  // the download-store and the file should get deleted. (360000 = 6 minutes)
  let [loadedDownloadList1, targetPath1] = await createTestDownload(
    new Date(Date.now() - 360000)
  );

  Assert.equal(loadedDownloadList1.length, 0, "Download should be removed");
  Assert.ok(
    !(await IOUtils.exists(targetPath1)),
    "The file should have been deleted."
  );

  // Insecure downloads that are newer than 5 minutes should stay in the
  // download store and the file should remain.
  let [loadedDownloadList2, targetPath2] = await createTestDownload(new Date());

  Assert.equal(loadedDownloadList2.length, 1, "Download should be kept");
  Assert.ok(
    await IOUtils.exists(targetPath2),
    "The file should have not been deleted."
  );
});