summaryrefslogtreecommitdiffstats
path: root/toolkit/components/resistfingerprinting/tests/browser/browser_canvas_randomization.js
blob: 8b4be78d539f8e57e1cebde617bee821a5d21d1d (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
652
653
654
655
656
657
658
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Bug 1816189 - Testing canvas randomization on canvas data extraction.
 *
 * In the test, we create canvas elements and offscreen canvas and test if
 * the extracted canvas data is altered because of the canvas randomization.
 */

const emptyPage =
  getRootDirectory(gTestPath).replace(
    "chrome://mochitests/content",
    "https://example.com"
  ) + "empty.html";

var TEST_CASES = [
  {
    name: "CanvasRenderingContext2D.getImageData() but constant color",
    shouldBeRandomized: false,
    extractCanvasData() {
      const canvas = document.createElement("canvas");
      canvas.width = 100;
      canvas.height = 100;

      const context = canvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      const imageData = context.getImageData(0, 0, 100, 100);

      // Access the data again.
      const imageDataSecond = context.getImageData(0, 0, 100, 100);

      return [imageData.data, imageDataSecond.data];
    },
    isDataRandomized(name, data1, data2, isCompareOriginal) {
      let diffCnt = countDifferencesInUint8Arrays(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);

      // The Canvas randomization adds at most 512 bits noise to the image data.
      // We compare the image data arrays to see if they are different and the
      // difference is within the range.

      // If we are compare two randomized arrays, the difference can be doubled.
      let expected = isCompareOriginal
        ? NUM_RANDOMIZED_CANVAS_BITS
        : NUM_RANDOMIZED_CANVAS_BITS * 2;

      // The number of difference bits should never bigger than the expected
      // number. It could be zero if the randomization is disabled.
      Assert.lessOrEqual(
        diffCnt,
        expected,
        "The number of noise bits is expected."
      );

      return diffCnt <= expected && diffCnt > 0;
    },
  },
  {
    name: "CanvasRenderingContext2D.getImageData().",
    shouldBeRandomized: true,
    extractCanvasData() {
      const canvas = document.createElement("canvas");
      canvas.width = 100;
      canvas.height = 100;

      const context = canvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      const imageData = context.getImageData(0, 0, 100, 100);

      // Access the data again.
      const imageDataSecond = context.getImageData(0, 0, 100, 100);

      return [imageData.data, imageDataSecond.data];
    },
    isDataRandomized(name, data1, data2, isCompareOriginal) {
      let diffCnt = countDifferencesInUint8Arrays(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);

      // The Canvas randomization adds at most 512 bits noise to the image data.
      // We compare the image data arrays to see if they are different and the
      // difference is within the range.

      // If we are compare two randomized arrays, the difference can be doubled.
      let expected = isCompareOriginal
        ? NUM_RANDOMIZED_CANVAS_BITS
        : NUM_RANDOMIZED_CANVAS_BITS * 2;

      // The number of difference bits should never bigger than the expected
      // number. It could be zero if the randomization is disabled.
      Assert.lessOrEqual(
        diffCnt,
        expected,
        "The number of noise bits is expected."
      );

      return diffCnt <= expected && diffCnt > 0;
    },
  },
  {
    name: "HTMLCanvasElement.toDataURL() with a 2d context",
    shouldBeRandomized: true,
    extractCanvasData() {
      const canvas = document.createElement("canvas");
      canvas.width = 100;
      canvas.height = 100;

      const context = canvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      const dataURL = canvas.toDataURL();

      // Access the data again.
      const dataURLSecond = canvas.toDataURL();

      return [dataURL, dataURLSecond];
    },
    isDataRandomized(name, data1, data2) {
      return data1 !== data2;
    },
  },
  {
    name: "HTMLCanvasElement.toDataURL() with a webgl context",
    shouldBeRandomized: true,
    extractCanvasData() {
      const canvas = document.createElement("canvas");

      const context = canvas.getContext("webgl");

      context.enable(context.SCISSOR_TEST);
      context.scissor(0, 0, 100, 100);
      context.clearColor(1, 0.2, 0.2, 1);
      context.clear(context.COLOR_BUFFER_BIT);
      context.scissor(15, 15, 30, 15);
      context.clearColor(0.2, 1, 0.2, 1);
      context.clear(context.COLOR_BUFFER_BIT);
      context.scissor(50, 50, 15, 15);
      context.clearColor(0.2, 0.2, 1, 1);
      context.clear(context.COLOR_BUFFER_BIT);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      const dataURL = canvas.toDataURL();

      // Access the data again.
      const dataURLSecond = canvas.toDataURL();

      return [dataURL, dataURLSecond];
    },
    isDataRandomized(name, data1, data2) {
      return data1 !== data2;
    },
  },
  {
    name: "HTMLCanvasElement.toDataURL() with a bitmaprenderer context",
    shouldBeRandomized: true,
    async extractCanvasData() {
      const canvas = document.createElement("canvas");
      canvas.width = 100;
      canvas.height = 100;

      const context = canvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      const bitmapCanvas = document.createElement("canvas");
      bitmapCanvas.width = 100;
      bitmapCanvas.heigh = 100;
      document.body.appendChild(bitmapCanvas);

      let bitmap = await createImageBitmap(canvas);
      const bitmapContext = bitmapCanvas.getContext("bitmaprenderer");
      bitmapContext.transferFromImageBitmap(bitmap);

      const dataURL = bitmapCanvas.toDataURL();

      // Access the data again.
      const dataURLSecond = bitmapCanvas.toDataURL();

      return [dataURL, dataURLSecond];
    },
    isDataRandomized(name, data1, data2) {
      return data1 !== data2;
    },
  },
  {
    name: "HTMLCanvasElement.toBlob() with a 2d context",
    shouldBeRandomized: true,
    async extractCanvasData() {
      const canvas = document.createElement("canvas");
      canvas.width = 100;
      canvas.height = 100;

      const context = canvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      let data = await new Promise(resolve => {
        canvas.toBlob(blob => {
          let fileReader = new FileReader();
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.readAsArrayBuffer(blob);
        });
      });

      // Access the data again.
      let dataSecond = await new Promise(resolve => {
        canvas.toBlob(blob => {
          let fileReader = new FileReader();
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.readAsArrayBuffer(blob);
        });
      });

      return [data, dataSecond];
    },
    isDataRandomized(name, data1, data2) {
      let diffCnt = countDifferencesInArrayBuffers(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);
      return diffCnt > 0;
    },
  },
  {
    name: "HTMLCanvasElement.toBlob() with a webgl context",
    shouldBeRandomized: true,
    async extractCanvasData() {
      const canvas = document.createElement("canvas");

      const context = canvas.getContext("webgl");

      context.enable(context.SCISSOR_TEST);
      context.scissor(0, 0, 100, 100);
      context.clearColor(1, 0.2, 0.2, 1);
      context.clear(context.COLOR_BUFFER_BIT);
      context.scissor(15, 15, 30, 15);
      context.clearColor(0.2, 1, 0.2, 1);
      context.clear(context.COLOR_BUFFER_BIT);
      context.scissor(50, 50, 15, 15);
      context.clearColor(0.2, 0.2, 1, 1);
      context.clear(context.COLOR_BUFFER_BIT);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      let data = await new Promise(resolve => {
        canvas.toBlob(blob => {
          let fileReader = new FileReader();
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.readAsArrayBuffer(blob);
        });
      });

      // We don't get the consistent blob data on second access with webgl
      // context regardless of the canvas randomization. So, we report the
      // same data here to not fail the test. Ideally, we should look into
      // why this happens, but it's not caused by canvas randomization.

      return [data, data];
    },
    isDataRandomized(name, data1, data2) {
      let diffCnt = countDifferencesInArrayBuffers(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);
      return diffCnt > 0;
    },
  },
  {
    name: "HTMLCanvasElement.toBlob() with a bitmaprenderer context",
    shouldBeRandomized: true,
    async extractCanvasData() {
      const canvas = document.createElement("canvas");
      canvas.width = 100;
      canvas.height = 100;

      const context = canvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      // Add the canvas element to the document
      document.body.appendChild(canvas);

      const bitmapCanvas = document.createElement("canvas");
      bitmapCanvas.width = 100;
      bitmapCanvas.heigh = 100;
      document.body.appendChild(bitmapCanvas);

      let bitmap = await createImageBitmap(canvas);
      const bitmapContext = bitmapCanvas.getContext("bitmaprenderer");
      bitmapContext.transferFromImageBitmap(bitmap);

      let data = await new Promise(resolve => {
        bitmapCanvas.toBlob(blob => {
          let fileReader = new FileReader();
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.readAsArrayBuffer(blob);
        });
      });

      // Access the data again.
      let dataSecond = await new Promise(resolve => {
        bitmapCanvas.toBlob(blob => {
          let fileReader = new FileReader();
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.readAsArrayBuffer(blob);
        });
      });

      return [data, dataSecond];
    },
    isDataRandomized(name, data1, data2) {
      let diffCnt = countDifferencesInArrayBuffers(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);
      return diffCnt > 0;
    },
  },
  {
    name: "OffscreenCanvas.convertToBlob() with a 2d context",
    shouldBeRandomized: true,
    async extractCanvasData() {
      let offscreenCanvas = new OffscreenCanvas(100, 100);

      const context = offscreenCanvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      let blob = await offscreenCanvas.convertToBlob();
      let data = await blob.arrayBuffer();

      // Access the data again.
      let blobSecond = await offscreenCanvas.convertToBlob();
      let dataSecond = await blobSecond.arrayBuffer();

      return [data, dataSecond];
    },
    isDataRandomized(name, data1, data2) {
      let diffCnt = countDifferencesInArrayBuffers(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);
      return diffCnt > 0;
    },
  },
  {
    name: "OffscreenCanvas.convertToBlob() with a webgl context",
    shouldBeRandomized: true,
    async extractCanvasData() {
      let offscreenCanvas = new OffscreenCanvas(100, 100);

      const context = offscreenCanvas.getContext("webgl");

      context.enable(context.SCISSOR_TEST);
      context.scissor(0, 0, 100, 100);
      context.clearColor(1, 0.2, 0.2, 1);
      context.clear(context.COLOR_BUFFER_BIT);
      context.scissor(15, 15, 30, 15);
      context.clearColor(0.2, 1, 0.2, 1);
      context.clear(context.COLOR_BUFFER_BIT);
      context.scissor(50, 50, 15, 15);
      context.clearColor(0.2, 0.2, 1, 1);
      context.clear(context.COLOR_BUFFER_BIT);

      let blob = await offscreenCanvas.convertToBlob();
      let data = await blob.arrayBuffer();

      // Access the data again.
      let blobSecond = await offscreenCanvas.convertToBlob();
      let dataSecond = await blobSecond.arrayBuffer();

      return [data, dataSecond];
    },
    isDataRandomized(name, data1, data2) {
      let diffCnt = countDifferencesInArrayBuffers(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);
      return diffCnt > 0;
    },
  },
  {
    name: "OffscreenCanvas.convertToBlob() with a bitmaprenderer context",
    shouldBeRandomized: true,
    async extractCanvasData() {
      let offscreenCanvas = new OffscreenCanvas(100, 100);

      const context = offscreenCanvas.getContext("2d");

      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      const bitmapCanvas = new OffscreenCanvas(100, 100);

      let bitmap = await createImageBitmap(offscreenCanvas);
      const bitmapContext = bitmapCanvas.getContext("bitmaprenderer");
      bitmapContext.transferFromImageBitmap(bitmap);

      let blob = await bitmapCanvas.convertToBlob();
      let data = await blob.arrayBuffer();

      // Access the data again.
      let blobSecond = await bitmapCanvas.convertToBlob();
      let dataSecond = await blobSecond.arrayBuffer();

      return [data, dataSecond];
    },
    isDataRandomized(name, data1, data2) {
      let diffCnt = countDifferencesInArrayBuffers(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);
      return diffCnt > 0;
    },
  },
  {
    name: "CanvasRenderingContext2D.getImageData() with a offscreen canvas",
    shouldBeRandomized: true,
    extractCanvasData() {
      let offscreenCanvas = new OffscreenCanvas(100, 100);

      const context = offscreenCanvas.getContext("2d");

      // Draw a red rectangle
      context.fillStyle = "#EE2222";
      context.fillRect(0, 0, 100, 100);
      context.fillStyle = "#2222EE";
      context.fillRect(20, 20, 100, 100);

      const imageData = context.getImageData(0, 0, 100, 100);

      // Access the data again.
      const imageDataSecond = context.getImageData(0, 0, 100, 100);

      return [imageData.data, imageDataSecond.data];
    },
    isDataRandomized(name, data1, data2, isCompareOriginal) {
      let diffCnt = countDifferencesInUint8Arrays(data1, data2);
      info(`For ${name} there are ${diffCnt} bits are different.`);

      // The Canvas randomization adds at most 512 bits noise to the image data.
      // We compare the image data arrays to see if they are different and the
      // difference is within the range.

      // If we are compare two randomized arrays, the difference can be doubled.
      let expected = isCompareOriginal
        ? NUM_RANDOMIZED_CANVAS_BITS
        : NUM_RANDOMIZED_CANVAS_BITS * 2;

      // The number of difference bits should never bigger than the expected
      // number. It could be zero if the randomization is disabled.
      Assert.lessOrEqual(
        diffCnt,
        expected,
        "The number of noise bits is expected."
      );

      return diffCnt <= expected && diffCnt > 0;
    },
  },
];

function runExtractCanvasData(test, tab) {
  let code = test.extractCanvasData.toString();
  return SpecialPowers.spawn(tab.linkedBrowser, [code], async code => {
    let result = await content.eval(`({${code}}).extractCanvasData()`);
    return result;
  });
}

async function runTest(enabled) {
  // Enable/Disable CanvasRandomization by the RFP target overrides.
  let RFPOverrides = enabled ? "+CanvasRandomization" : "-CanvasRandomization";
  await SpecialPowers.pushPrefEnv({
    set: [
      ["privacy.fingerprintingProtection", true],
      ["privacy.fingerprintingProtection.pbmode", true],
      ["privacy.fingerprintingProtection.overrides", RFPOverrides],
      ["privacy.resistFingerprinting", false],
    ],
  });

  // Open a private window.
  let privateWindow = await BrowserTestUtils.openNewBrowserWindow({
    private: true,
  });

  // Open tabs in the normal and private window.
  const tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, emptyPage);

  const privateTab = await BrowserTestUtils.openNewForegroundTab(
    privateWindow.gBrowser,
    emptyPage
  );

  for (let test of TEST_CASES) {
    info(`Testing ${test.name}`);

    // Clear telemetry before starting test.
    Services.fog.testResetFOG();

    let data = await runExtractCanvasData(test, tab);
    let result = test.isDataRandomized(test.name, data[0], test.originalData);

    if (test.shouldBeRandomized) {
      is(
        result,
        enabled,
        `The image data is ${enabled ? "randomized" : "the same"} for ${
          test.name
        }.`
      );
    } else {
      is(
        result,
        false,
        `The image data for ${test.name} should never be randomized.`
      );
    }

    ok(
      !test.isDataRandomized(test.name, data[0], data[1]),
      `The data of first and second access should be the same for ${test.name}.`
    );

    let privateData = await runExtractCanvasData(test, privateTab);

    // Check if we add noise to canvas data in private windows.
    result = test.isDataRandomized(
      test.name,
      privateData[0],
      test.originalData,
      true
    );
    if (test.shouldBeRandomized) {
      is(
        result,
        enabled,
        `The private image data is ${enabled ? "randomized" : "the same"} for ${
          test.name
        }.`
      );
    } else {
      is(
        result,
        false,
        `The image data for ${test.name} should never be randomized.`
      );
    }

    ok(
      !test.isDataRandomized(test.name, privateData[0], privateData[1]),
      "The data of first and second access should be the same for private windows."
    );

    if (test.shouldBeRandomized) {
      // Make sure the noises are different between normal window and private
      // windows.
      result = test.isDataRandomized(test.name, privateData[0], data[0]);
      is(
        result,
        enabled,
        `The image data between the normal window and the private window are ${
          enabled ? "different" : "the same"
        } for ${test.name}.`
      );

      // Verify the telemetry is recorded if canvas randomization is enabled.
      if (enabled) {
        await Services.fog.testFlushAllChildren();

        Assert.greater(
          Glean.fingerprintingProtection.canvasNoiseCalculateTime.testGetValue()
            .sum,
          0,
          "The telemetry of canvas randomization is recorded."
        );
      }
    }
  }

  BrowserTestUtils.removeTab(tab);
  BrowserTestUtils.removeTab(privateTab);
  await BrowserTestUtils.closeWindow(privateWindow);
}

add_setup(async function () {
  // Disable the fingerprinting randomization.
  await SpecialPowers.pushPrefEnv({
    set: [
      ["privacy.fingerprintingProtection", false],
      ["privacy.fingerprintingProtection.pbmode", false],
      ["privacy.resistFingerprinting", false],
    ],
  });

  // Open a tab for extracting the canvas data.
  const tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, emptyPage);

  // Extract the original canvas data without random noise.
  for (let test of TEST_CASES) {
    let data = await runExtractCanvasData(test, tab);
    test.originalData = data[0];
  }

  BrowserTestUtils.removeTab(tab);
});

add_task(async function run_tests_with_randomization_enabled() {
  await runTest(true);
});

add_task(async function run_tests_with_randomization_disabled() {
  await runTest(false);
});