summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_dnr_startup_cache.js
blob: bcb05eec23fe285e51fb468091872367eee3fc1b (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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { Schemas } = ChromeUtils.importESModule(
  "resource://gre/modules/Schemas.sys.mjs"
);

ChromeUtils.defineESModuleGetters(this, {
  ExtensionDNR: "resource://gre/modules/ExtensionDNR.sys.mjs",
  ExtensionDNRStore: "resource://gre/modules/ExtensionDNRStore.sys.mjs",
  sinon: "resource://testing-common/Sinon.sys.mjs",
});

XPCOMUtils.defineLazyServiceGetters(this, {
  aomStartup: [
    "@mozilla.org/addons/addon-manager-startup;1",
    "amIAddonManagerStartup",
  ],
});

AddonTestUtils.init(this);
AddonTestUtils.overrideCertDB();

Services.scriptloader.loadSubScript(
  Services.io.newFileURI(do_get_file("head_dnr.js")).spec,
  this
);

const EXT_ID = "test-dnr-store-startup-cache@test-extension";
const TEMP_EXT_ID = "test-dnr-store-temporarily-installed@test-extension";

// Test rulesets should include fields that are special cased during Rule object deserialization
// from the plain objects loaded from the StartupCache data objects.
// In particular regexFilter are included to make sure that RuleValidator.deserializeRule is
// internally compiling the regexFilter and storing it into the RuleCondition instance as expected
// (implicitly asserted internally by the test helper assertDNRStoreData in head_dnr.js).
const RULESET_1_DATA = [
  getDNRRule({
    id: 1,
    action: { type: "allow" },
    condition: { resourceTypes: ["main_frame"], regexFilter: "http://from/$" },
  }),
  getDNRRule({
    id: 2,
    action: { type: "allow" },
    condition: {
      resourceTypes: ["main_frame"],
      regexFilter: "http://from2/$",
      isUrlFilterCaseSensitive: true,
    },
  }),
];
const RULESET_2_DATA = [
  getDNRRule({
    action: { type: "block" },
    condition: { resourceTypes: ["main_frame", "script"] },
  }),
];

function getDNRExtension({
  id = EXT_ID,
  version = "1.0",
  useAddonManager = "permanent",
  background,
  rule_resources,
  declarative_net_request,
  files,
}) {
  // Omit declarative_net_request if rule_resources isn't defined
  // (because declarative_net_request fails the manifest validation
  // if rule_resources is missing).
  const dnr = rule_resources ? { rule_resources } : undefined;

  return {
    background,
    useAddonManager,
    manifest: {
      manifest_version: 3,
      version,
      permissions: ["declarativeNetRequest", "declarativeNetRequestFeedback"],
      // Needed to make sure the upgraded extension will have the same id and
      // same uuid (which is mapped based on the extension id).
      browser_specific_settings: {
        gecko: { id },
      },
      declarative_net_request: declarative_net_request
        ? { ...declarative_net_request, ...(dnr ?? {}) }
        : dnr,
    },
    files,
  };
}

add_setup(async () => {
  Services.prefs.setBoolPref("extensions.manifestV3.enabled", true);
  Services.prefs.setBoolPref("extensions.dnr.enabled", true);
  Services.prefs.setBoolPref("extensions.dnr.feedback", true);

  setupTelemetryForTests();

  await ExtensionTestUtils.startAddonManager();
});

add_task(async function test_dnr_startup_cache_save_and_load() {
  resetTelemetryData();

  const rule_resources = [
    {
      id: "ruleset_1",
      enabled: true,
      path: "ruleset_1.json",
    },
    {
      id: "ruleset_2",
      enabled: false,
      path: "ruleset_2.json",
    },
  ];
  const files = {
    "ruleset_1.json": JSON.stringify(RULESET_1_DATA),
    "ruleset_2.json": JSON.stringify(RULESET_2_DATA),
  };

  let dnrStore = ExtensionDNRStore._getStoreForTesting();
  let sandboxStoreSpies = sinon.createSandbox();
  const spyScheduleCacheDataSave = sandboxStoreSpies.spy(
    dnrStore,
    "scheduleCacheDataSave"
  );

  const extension = ExtensionTestUtils.loadExtension(
    getDNRExtension({ rule_resources, files })
  );

  const temporarilyInstalledExt = ExtensionTestUtils.loadExtension(
    getDNRExtension({
      id: TEMP_EXT_ID,
      useAddonManager: "temporary",
      rule_resources,
      files,
    })
  );

  assertDNRTelemetryMetricsNoSamples(
    [
      {
        metric: "validateRulesTime",
        mirroredName: "WEBEXT_DNR_VALIDATE_RULES_MS",
        mirroredType: "histogram",
      },
    ],
    "before any test extensions have been loaded"
  );

  await temporarilyInstalledExt.startup();
  await extension.startup();
  info(
    "Wait for DNR initialization completed for the temporarily installed extension"
  );
  await ExtensionDNR.ensureInitialized(temporarilyInstalledExt.extension);
  info(
    "Wait for DNR initialization completed for the permanently installed extension"
  );
  await ExtensionDNR.ensureInitialized(extension.extension);

  assertDNRTelemetryMetricsSamplesCount(
    [
      {
        metric: "validateRulesTime",
        mirroredName: "WEBEXT_DNR_VALIDATE_RULES_MS",
        mirroredType: "histogram",
        expectedSamplesCount: 2,
      },
    ],
    "after two test extensions have been loaded"
  );

  Assert.equal(
    spyScheduleCacheDataSave.callCount,
    1,
    "Expect ExtensionDNRStore scheduleCacheDataSave method to have been called once"
  );

  sandboxStoreSpies.restore();

  const extUUID = extension.uuid;
  const { cacheFile } = dnrStore.getFilePaths(extUUID);

  await assertDNRStoreData(dnrStore, extension, {
    ruleset_1: getSchemaNormalizedRules(extension, RULESET_1_DATA),
  });

  assertDNRTelemetryMetricsNoSamples(
    [
      {
        metric: "startupCacheWriteTime",
        mirroredName: "WEBEXT_DNR_STARTUPCACHE_WRITE_MS",
        mirroredType: "histogram",
      },
      {
        metric: "startupCacheWriteSize",
        mirroredName: "WEBEXT_DNR_STARTUPCACHE_WRITE_BYTES",
        mirroredType: "histogram",
      },
      // Expected no startup cache file to be loaded or used for a newly installed extension.
      {
        metric: "startupCacheReadSize",
        mirroredName: "WEBEXT_DNR_STARTUPCACHE_READ_BYTES",
        mirroredType: "histogram",
      },
      {
        metric: "startupCacheReadTime",
        mirroredName: "WEBEXT_DNR_STARTUPCACHE_READ_MS",
        mirroredType: "histogram",
      },
      {
        metric: "startupCacheEntries",
        label: "miss",
        mirroredName: "extensions.apis.dnr.startup_cache_entries",
        mirroredType: "keyedScalar",
      },
      {
        metric: "startupCacheEntries",
        label: "hit",
        mirroredName: "extensions.apis.dnr.startup_cache_entries",
        mirroredType: "keyedScalar",
      },
    ],
    "on loading dnr rules for newly installed extension"
  );
  await dnrStore.waitSaveCacheDataForTesting();
  assertDNRTelemetryMetricsSamplesCount(
    [
      {
        metric: "startupCacheWriteTime",
        mirroredName: "WEBEXT_DNR_STARTUPCACHE_WRITE_MS",
        mirroredType: "histogram",
        expectedSamplesCount: 1,
      },
      {
        metric: "startupCacheWriteSize",
        mirroredName: "WEBEXT_DNR_STARTUPCACHE_WRITE_BYTES",
        mirroredType: "histogram",
        expectedSamplesCount: 1,
      },
    ],
    "after writing DNR startup cache data to disk"
  );

  ok(
    await IOUtils.exists(cacheFile),
    "Expect the DNR store startupCache file exist"
  );

  const assertDNRStoreDataLoadOnStartup = async ({
    expectLoadedFromCache,
    expectClearLastUpdateTagPref,
  }) => {
    info(
      `Mock browser restart and assert DNR rules ${
        expectLoadedFromCache ? "NOT " : ""
      }going through Schemas.normalize`
    );
    await AddonTestUtils.promiseShutdownManager();
    // Recreate the DNR store to more easily mock its initial state after a browser restart.
    dnrStore = ExtensionDNRStore._recreateStoreForTesting();
    const StoreData = ExtensionDNRStore._getStoreDataClassForTesting();

    let sandbox = sinon.createSandbox();
    const schemasNormalizeSpy = sandbox.spy(Schemas, "normalize");
    const ruleValidatorAddRulesSpy = sandbox.spy(
      ExtensionDNR.RuleValidator.prototype,
      "addRules"
    );
    const deserializeRuleSpy = sandbox.spy(
      ExtensionDNR.RuleValidator,
      "deserializeRule"
    );
    const clearLastUpdateTagPrefSpy = sandbox.spy(
      StoreData,
      "clearLastUpdateTagPref"
    );
    const scheduleCacheDataSaveSpy = sandbox.spy(
      dnrStore,
      "scheduleCacheDataSave"
    );

    resetTelemetryData();
    await AddonTestUtils.promiseStartupManager();
    await extension.awaitStartup();
    await ExtensionDNR.ensureInitialized(extension.extension);

    if (expectLoadedFromCache) {
      assertDNRTelemetryMetricsSamplesCount(
        [
          {
            metric: "startupCacheReadSize",
            mirroredName: "WEBEXT_DNR_STARTUPCACHE_READ_BYTES",
            mirroredType: "histogram",
            expectedSamplesCount: 1,
          },
          {
            metric: "startupCacheReadTime",
            mirroredName: "WEBEXT_DNR_STARTUPCACHE_READ_MS",
            mirroredType: "histogram",
            expectedSamplesCount: 1,
          },
        ],
        "after app startup and expected startup cache hit"
      );
      assertDNRTelemetryMetricsGetValueEq(
        [
          {
            metric: "startupCacheEntries",
            label: "hit",
            expectedGetValue: 1,
            mirroredName: "extensions.apis.dnr.startup_cache_entries",
            mirroredType: "keyedScalar",
          },
        ],
        "after app startup and expected startup cache hit"
      );
      assertDNRTelemetryMetricsNoSamples(
        [
          {
            metric: "validateRulesTime",
            mirroredName: "WEBEXT_DNR_VALIDATE_RULES_MS",
            mirroredType: "histogram",
          },
          {
            metric: "startupCacheEntries",
            label: "miss",
            mirroredName: "extensions.apis.dnr.startup_cache_entries",
            mirroredType: "keyedScalar",
          },
        ],
        "after DNR store loaded startup cache data"
      );
    } else {
      assertDNRTelemetryMetricsSamplesCount(
        [
          {
            metric: "validateRulesTime",
            mirroredName: "WEBEXT_DNR_VALIDATE_RULES_MS",
            mirroredType: "histogram",
            expectedSamplesCount: 1,
          },
          {
            metric: "startupCacheReadSize",
            mirroredName: "WEBEXT_DNR_STARTUPCACHE_READ_BYTES",
            mirroredType: "histogram",
            expectedSamplesCount: 1,
          },
          {
            metric: "startupCacheReadTime",
            mirroredName: "WEBEXT_DNR_STARTUPCACHE_READ_MS",
            mirroredType: "histogram",
            expectedSamplesCount: 1,
          },
        ],
        "after app startup and expected startup cache miss"
      );
      assertDNRTelemetryMetricsGetValueEq(
        [
          {
            metric: "startupCacheEntries",
            label: "miss",
            expectedGetValue: 1,
            mirroredName: "extensions.apis.dnr.startup_cache_entries",
            mirroredType: "keyedScalar",
          },
        ],
        "after app startup and expected startup cache miss"
      );
      assertDNRTelemetryMetricsNoSamples(
        [
          {
            metric: "startupCacheEntries",
            label: "hit",
            mirroredName: "extensions.apis.dnr.startup_cache_entries",
            mirroredType: "keyedScalar",
          },
        ],
        "after DNR store loaded startup cache data"
      );
    }

    Assert.equal(
      scheduleCacheDataSaveSpy.called,
      !expectLoadedFromCache,
      "scheduleCacheDataSave to not be called when the extension DNR rules are initialized from startup cache data"
    );

    Assert.equal(
      clearLastUpdateTagPrefSpy.callCount,
      expectClearLastUpdateTagPref ? 1 : 0,
      "Expect clearLastUpdateTagPrefSpy to have been called the expected number of times"
    );
    if (expectClearLastUpdateTagPref === true) {
      Assert.ok(
        clearLastUpdateTagPrefSpy.calledWith(extension.uuid),
        "Expect clearLastUpdateTagPrefSpy to have been called with the test extension uuid"
      );
    }

    Assert.equal(
      schemasNormalizeSpy.calledWith(
        sinon.match.any,
        sinon.match("declarativeNetRequest.Rule"),
        sinon.match.any
      ),
      !expectLoadedFromCache,
      `Expect DNR rules to ${
        expectLoadedFromCache ? "NOT " : ""
      }be going through Schemas.normalize`
    );

    Assert.equal(
      ruleValidatorAddRulesSpy.called,
      !expectLoadedFromCache,
      `Expect DNR rules to ${
        expectLoadedFromCache ? "NOT " : ""
      }be going through RuleValidator addRules`
    );

    Assert.equal(
      deserializeRuleSpy.called,
      expectLoadedFromCache,
      `Expect RuleValidator.deserializeRule to ${
        expectLoadedFromCache ? "NOT " : ""
      }be called to convert StartupCache data back into Rule class instances`
    );

    await assertDNRStoreData(dnrStore, extension, {
      ruleset_1: getSchemaNormalizedRules(extension, RULESET_1_DATA),
    });

    sandbox.restore();
  };

  const expectedLastUpdateTag = ExtensionDNRStore._getLastUpdateTag(
    extension.uuid
  );

  Assert.ok(
    typeof expectedLastUpdateTag == "string" && !!expectedLastUpdateTag.length,
    `Expect lastUpdateTag for ${extension.id} to be set to a non empty string: ${expectedLastUpdateTag}`
  );

  Assert.equal(
    ExtensionDNRStore._getLastUpdateTag(temporarilyInstalledExt.uuid),
    null,
    `Expect no lastUpdateTag value set for temporarily installed extensions`
  );

  await assertDNRStoreDataLoadOnStartup({
    expectLoadedFromCache: true,
    expectClearLastUpdateTagPref: false,
  });

  {
    const { buffer } = await IOUtils.read(cacheFile);
    const decodedData = aomStartup.decodeBlob(buffer);
    Assert.equal(
      expectedLastUpdateTag,
      decodedData?.cacheData.get(extension.uuid).lastUpdateTag,
      "Expect cacheData entry's lastUpdateTag to match the value stored in the related pref"
    );
    Assert.equal(
      decodedData?.cacheData.has(temporarilyInstalledExt.uuid),
      false,
      "Expect no cache data entry for temporarily installed extensions"
    );

    info("Confirm startupCache data dropped if last tag pref value mismatches");
    ExtensionDNRStore._storeLastUpdateTag(
      extension.uuid,
      "mismatching-tag-value"
    );
    Assert.notEqual(
      ExtensionDNRStore._getLastUpdateTag(extension.uuid),
      decodedData?.cacheData.get(extension.uuid).lastUpdateTag,
      "Expect cacheData.lastDNRStoreUpdateTag to NOT match the tampered value stored in the related pref"
    );
  }

  await assertDNRStoreDataLoadOnStartup({
    expectLoadedFromCache: false,
    expectClearLastUpdateTagPref: true,
  });

  info(
    "Verify that startupCache data mismatching with the StoreData schema version is being dropped"
  );
  await dnrStore.waitSaveCacheDataForTesting();
  await assertDNRStoreDataLoadOnStartup({
    expectLoadedFromCache: true,
    expectClearLastUpdateTagPref: false,
  });

  {
    info("Tamper the StoreData version in the startupCache data");
    const { buffer } = await IOUtils.read(cacheFile);
    const decodedData = aomStartup.decodeBlob(buffer);
    decodedData.cacheData.get(extUUID).schemaVersion = -1;
    await IOUtils.write(
      cacheFile,
      new Uint8Array(aomStartup.encodeBlob(decodedData))
    );
  }

  await assertDNRStoreDataLoadOnStartup({
    expectLoadedFromCache: false,
    expectClearLastUpdateTagPref: true,
  });

  info(
    "Verify that startupCache data mismatching with the extension version is being dropped"
  );
  await dnrStore.waitSaveCacheDataForTesting();
  await assertDNRStoreDataLoadOnStartup({
    expectLoadedFromCache: true,
    expectClearLastUpdateTagPref: false,
  });

  {
    info("Tamper the extension version in the startupCache data");
    const { buffer } = await IOUtils.read(cacheFile);
    const decodedData = aomStartup.decodeBlob(buffer);
    decodedData.cacheData.get(extUUID).extVersion = "0.1";
    await IOUtils.write(
      cacheFile,
      new Uint8Array(aomStartup.encodeBlob(decodedData))
    );
  }
  await assertDNRStoreDataLoadOnStartup({
    expectLoadedFromCache: false,
    expectClearLastUpdateTagPref: true,
  });

  await extension.unload();

  Assert.equal(
    ExtensionDNRStore._getLastUpdateTag(extension.uuid),
    null,
    "LastUpdateTag pref should have been removed after addon uninstall"
  );
});

add_task(async function test_detect_and_reschedule_save_cache_on_new_changes() {
  const rule_resources = [
    {
      id: "ruleset_1",
      enabled: true,
      path: "ruleset_1.json",
    },
  ];
  const files = {
    "ruleset_1.json": JSON.stringify(RULESET_1_DATA),
  };

  let dnrStore = ExtensionDNRStore._getStoreForTesting();
  let sandboxStore = sinon.createSandbox();
  const spyScheduleCacheDataSave = sandboxStore.spy(
    dnrStore,
    "scheduleCacheDataSave"
  );

  let extension;
  const tamperedLastUpdateTag = Services.uuid.generateUUID().toString();
  let resolvePromiseSaveCacheRescheduled;
  let promiseSaveCacheRescheduled = new Promise(resolve => {
    resolvePromiseSaveCacheRescheduled = resolve;
  });
  const realDetectStartupCacheDataChanged =
    dnrStore.detectStartupCacheDataChanged.bind(dnrStore);
  const stubDetectCacheDataChanges = sandboxStore.stub(
    dnrStore,
    "detectStartupCacheDataChanged"
  );

  stubDetectCacheDataChanges.callsFake(seenLastUpdateTags => {
    const extData = dnrStore._data.get(extension.extension.uuid);
    Assert.ok(extData, "Got StoreData instance for the test extension");
    Assert.ok(
      typeof extData.lastUpdateTag === "string" &&
        !!extData.lastUpdateTag.length,
      "Expect a non empty lastUpdateTag assigned to the extension StoreData"
    );
    Assert.deepEqual(
      Array.from(seenLastUpdateTags),
      [extData.lastUpdateTag],
      "Expects the extension storeData lastUpdateTag to have been seen"
    );
    if (stubDetectCacheDataChanges.callCount == 1) {
      Assert.notEqual(
        extData.lastUpdateTag,
        tamperedLastUpdateTag,
        "New tampered lastUpdateTag should not be equal to the one already set"
      );
      extData.lastUpdateTag = tamperedLastUpdateTag;
      Assert.equal(
        realDetectStartupCacheDataChanged(seenLastUpdateTags),
        true,
        "Expect dnrStore.detectStartupCacheDataChanged to detect a change"
      );
      return true;
    }
    Assert.equal(
      realDetectStartupCacheDataChanged(seenLastUpdateTags),
      false,
      "Expect dnrStore.detectStartupCacheDataChanged to NOT have detected any change"
    );

    Promise.resolve().then(resolvePromiseSaveCacheRescheduled);
    return false;
  });

  extension = ExtensionTestUtils.loadExtension(
    getDNRExtension({
      id: "test-reschedule-save-on-detected-changes@test",
      rule_resources,
      files,
    })
  );

  await extension.startup();
  info(
    "Wait for DNR initialization completed for the permanently installed extension"
  );
  await ExtensionDNR.ensureInitialized(extension.extension);
  info("Wait for the saveCacheDataNow task to have been rescheduled");
  await promiseSaveCacheRescheduled;

  Assert.equal(
    spyScheduleCacheDataSave.callCount,
    2,
    "Expect ExtensionDNRStore scheduleCacheDataSave method to have been called twice"
  );
  Assert.equal(
    stubDetectCacheDataChanges.callCount,
    2,
    "Expect ExtensionDNRStore detectStartupCacheDataChanged method to have been called twice"
  );

  sandboxStore.restore();

  await extension.unload();
});