summaryrefslogtreecommitdiffstats
path: root/toolkit/components/antitracking/test/browser/browser_storageAccessWithDynamicFpi.js
blob: b5e950cc5f6020dc7b32b188a6fa8a4f537b70fc (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
/* vim: set ts=2 et sw=2 tw=80: */
/* 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/. */

"use strict";

const { RemoteSettings } = ChromeUtils.importESModule(
  "resource://services-settings/remote-settings.sys.mjs"
);

XPCOMUtils.defineLazyServiceGetter(
  this,
  "peuService",
  "@mozilla.org/partitioning/exception-list-service;1",
  "nsIPartitioningExceptionListService"
);

const TEST_REDIRECT_TOP_PAGE =
  TEST_3RD_PARTY_DOMAIN + TEST_PATH + "redirect.sjs?" + TEST_TOP_PAGE;
const TEST_REDIRECT_3RD_PARTY_PAGE =
  TEST_DOMAIN + TEST_PATH + "redirect.sjs?" + TEST_3RD_PARTY_PARTITIONED_PAGE;
const TEST_REDIRECT_ANOTHER_3RD_PARTY_PAGE =
  TEST_ANOTHER_3RD_PARTY_DOMAIN_HTTPS +
  TEST_PATH +
  "redirect.sjs?" +
  TEST_TOP_PAGE_HTTPS;

const COLLECTION_NAME = "partitioning-exempt-urls";
const EXCEPTION_LIST_PREF_NAME = "privacy.restrict3rdpartystorage.skip_list";

async function cleanup() {
  Services.prefs.clearUserPref(EXCEPTION_LIST_PREF_NAME);
  await new Promise(resolve => {
    Services.clearData.deleteData(Ci.nsIClearDataService.CLEAR_ALL, value =>
      resolve()
    );
  });
}

add_setup(async function () {
  await SpecialPowers.flushPrefEnv();
  await SpecialPowers.pushPrefEnv({
    set: [
      [
        "network.cookie.cookieBehavior",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN,
      ],
      [
        "network.cookie.cookieBehavior.pbmode",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN,
      ],
      ["privacy.restrict3rdpartystorage.heuristic.redirect", false],
      ["privacy.trackingprotection.enabled", false],
      ["privacy.trackingprotection.pbmode.enabled", false],
      ["privacy.trackingprotection.annotate_channels", true],
      // Bug 1617611: Fix all the tests broken by "cookies SameSite=lax by default"
      ["network.cookie.sameSite.laxByDefault", false],
    ],
  });
  registerCleanupFunction(cleanup);
});

function executeContentScript(browser, callback, options = {}) {
  return SpecialPowers.spawn(
    browser,
    [
      {
        callback: callback.toString(),
        ...options,
      },
    ],
    obj => {
      return new content.Promise(async resolve => {
        if (obj.page) {
          // third-party
          let ifr = content.document.createElement("iframe");
          ifr.onload = async () => {
            info("Sending code to the 3rd party content");
            ifr.contentWindow.postMessage(
              { cb: obj.callback, value: obj.value },
              "*"
            );
          };

          content.addEventListener("message", event => resolve(event.data), {
            once: true,
          });

          content.document.body.appendChild(ifr);
          ifr.src = obj.page;
        } else {
          // first-party
          let runnableStr = `(() => {return (${obj.callback});})();`;
          let runnable = eval(runnableStr); // eslint-disable-line no-eval
          resolve(await runnable.call(content, content, obj.value));
        }
      });
    }
  );
}

function readNetworkCookie(win) {
  return win
    .fetch("cookies.sjs")
    .then(r => r.text())
    .then(text => {
      return text.substring("cookie:foopy=".length);
    });
}

async function writeNetworkCookie(win, value) {
  await win.fetch("cookies.sjs?" + value).then(r => r.text());
  return true;
}

function createDataInFirstParty(browser, value) {
  return executeContentScript(browser, writeNetworkCookie, { value });
}
function getDataFromFirstParty(browser) {
  return executeContentScript(browser, readNetworkCookie, {});
}
function createDataInThirdParty(browser, value) {
  return executeContentScript(browser, writeNetworkCookie, {
    page: TEST_3RD_PARTY_PARTITIONED_PAGE,
    value,
  });
}
function getDataFromThirdParty(browser) {
  return executeContentScript(browser, readNetworkCookie, {
    page: TEST_3RD_PARTY_PARTITIONED_PAGE,
  });
}

async function redirectWithUserInteraction(browser, url, wait = null) {
  await executeContentScript(
    browser,
    (content, value) => {
      content.document.userInteractionForTesting();

      let link = content.document.createElement("a");
      link.appendChild(content.document.createTextNode("click me!"));
      link.href = value;
      content.document.body.appendChild(link);
      link.click();
    },
    {
      value: url,
    }
  );
  await BrowserTestUtils.browserLoaded(browser, false, wait || url);
}

async function checkData(browser, options) {
  if ("firstParty" in options) {
    is(
      await getDataFromFirstParty(browser),
      options.firstParty,
      "correct first-party data"
    );
  }
  if ("thirdParty" in options) {
    is(
      await getDataFromThirdParty(browser),
      options.thirdParty,
      "correct third-party data"
    );
  }
}

async function runTestRedirectHeuristic(disableHeuristics) {
  info("Starting Dynamic FPI Redirect Heuristic test...");

  await SpecialPowers.pushPrefEnv({
    set: [
      ["privacy.restrict3rdpartystorage.heuristic.recently_visited", true],
      ["privacy.antitracking.enableWebcompat", !disableHeuristics],
    ],
  });

  // mark third-party as tracker
  await UrlClassifierTestUtils.addTestTrackers();

  info("Creating a new tab");
  let tab = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE);
  gBrowser.selectedTab = tab;

  let browser = gBrowser.getBrowserForTab(tab);
  await BrowserTestUtils.browserLoaded(browser);

  info("initializing...");
  await checkData(browser, { firstParty: "", thirdParty: "" });

  await Promise.all([
    createDataInFirstParty(browser, "firstParty"),
    createDataInThirdParty(browser, "thirdParty"),
  ]);

  await checkData(browser, {
    firstParty: "firstParty",
    thirdParty: "",
  });

  info("load third-party content as first-party");
  await redirectWithUserInteraction(
    browser,
    TEST_REDIRECT_3RD_PARTY_PAGE,
    TEST_3RD_PARTY_PARTITIONED_PAGE
  );

  await checkData(browser, { firstParty: "" });
  await createDataInFirstParty(browser, "heuristicFirstParty");
  await checkData(browser, { firstParty: "heuristicFirstParty" });

  info("redirect back to first-party page");
  await redirectWithUserInteraction(
    browser,
    TEST_REDIRECT_TOP_PAGE,
    TEST_TOP_PAGE
  );

  info("third-party tracker should NOT able to access first-party data");
  await checkData(browser, {
    firstParty: "firstParty",
    thirdParty: "",
  });

  // remove third-party from tracker
  await UrlClassifierTestUtils.cleanupTestTrackers();

  info("load third-party content as first-party");
  await redirectWithUserInteraction(
    browser,
    TEST_REDIRECT_3RD_PARTY_PAGE,
    TEST_3RD_PARTY_PARTITIONED_PAGE
  );

  await checkData(browser, {
    firstParty: "heuristicFirstParty",
  });

  info("redirect back to first-party page");
  await redirectWithUserInteraction(
    browser,
    TEST_REDIRECT_TOP_PAGE,
    TEST_TOP_PAGE
  );

  info(
    `third-party page should ${
      disableHeuristics ? "not " : ""
    }be able to access first-party data`
  );
  await checkData(browser, {
    firstParty: "firstParty",
    thirdParty: disableHeuristics ? "" : "heuristicFirstParty",
  });

  info("Removing the tab");
  BrowserTestUtils.removeTab(tab);

  await SpecialPowers.popPrefEnv();

  await cleanup();
}

async function runTestRedirectHeuristicWithSameSite() {
  info("Starting Dynamic FPI Redirect Between Same Site Heuristic test...");

  info("Creating a new tab");
  let tab = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE_HTTPS);
  gBrowser.selectedTab = tab;

  let browser = gBrowser.getBrowserForTab(tab);
  await BrowserTestUtils.browserLoaded(browser);

  info(
    `Redirecting from ${TEST_DOMAIN_HTTPS} to ${TEST_ANOTHER_3RD_PARTY_DOMAIN_HTTPS}`
  );

  await redirectWithUserInteraction(
    browser,
    TEST_REDIRECT_ANOTHER_3RD_PARTY_PAGE,
    TEST_TOP_PAGE_HTTPS
  );

  info("Checking if a permission was set between the redirect");

  const principal = browser.contentPrincipal;

  is(
    Services.perms.testPermissionFromPrincipal(
      principal,
      `3rdPartyStorage^${TEST_ANOTHER_3RD_PARTY_DOMAIN_HTTPS.slice(0, -1)}`
    ),
    Services.perms.UNKNOWN_ACTION,
    "No permission was set for same-site redirect"
  );

  info("Removing the tab");
  BrowserTestUtils.removeTab(tab);

  await cleanup();
}
add_task(async function testRedirectHeuristic() {
  await runTestRedirectHeuristic(false);
});

add_task(runTestRedirectHeuristicWithSameSite);

add_task(async function testRedirectHeuristicDisabled() {
  await runTestRedirectHeuristic(true);
});

class UpdateEvent extends EventTarget {}
function waitForEvent(element, eventName) {
  return new Promise(function (resolve) {
    element.addEventListener(eventName, e => resolve(e.detail), { once: true });
  });
}

// The test URLs have a trailing / which means they're not valid origins.
const TEST_ORIGIN = TEST_DOMAIN.substring(0, TEST_DOMAIN.length - 1);
const TEST_3RD_PARTY_ORIGIN = TEST_3RD_PARTY_DOMAIN.substring(
  0,
  TEST_3RD_PARTY_DOMAIN.length - 1
);

async function runTestExceptionListPref(disableHeuristics) {
  info("Starting Dynamic FPI exception list test pref");

  await SpecialPowers.pushPrefEnv({
    set: [
      ["privacy.restrict3rdpartystorage.heuristic.recently_visited", false],
      ["privacy.antitracking.enableWebcompat", !disableHeuristics],
    ],
  });

  info("Creating new tabs");
  let tabThirdParty = BrowserTestUtils.addTab(
    gBrowser,
    TEST_3RD_PARTY_PARTITIONED_PAGE
  );
  gBrowser.selectedTab = tabThirdParty;

  let browserThirdParty = gBrowser.getBrowserForTab(tabThirdParty);
  await BrowserTestUtils.browserLoaded(browserThirdParty);

  let tabFirstParty = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE);
  gBrowser.selectedTab = tabFirstParty;

  let browserFirstParty = gBrowser.getBrowserForTab(tabFirstParty);
  await BrowserTestUtils.browserLoaded(browserFirstParty);

  info("initializing...");
  await Promise.all([
    checkData(browserFirstParty, { firstParty: "", thirdParty: "" }),
    checkData(browserThirdParty, { firstParty: "" }),
  ]);

  info("fill default data");
  await Promise.all([
    createDataInFirstParty(browserFirstParty, "firstParty"),
    createDataInThirdParty(browserFirstParty, "thirdParty"),
    createDataInFirstParty(browserThirdParty, "ExceptionListFirstParty"),
  ]);

  info("check data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "thirdParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set exception list pref");
  Services.prefs.setStringPref(
    EXCEPTION_LIST_PREF_NAME,
    `${TEST_ORIGIN},${TEST_3RD_PARTY_ORIGIN}`
  );

  info("check data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: disableHeuristics ? "thirdParty" : "ExceptionListFirstParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set incomplete exception list pref");
  Services.prefs.setStringPref(EXCEPTION_LIST_PREF_NAME, `${TEST_ORIGIN}`);

  info("check data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "thirdParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set exception list pref, with extra semicolons");
  Services.prefs.setStringPref(
    EXCEPTION_LIST_PREF_NAME,
    `;${TEST_ORIGIN},${TEST_3RD_PARTY_ORIGIN};;`
  );

  info("check data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: disableHeuristics ? "thirdParty" : "ExceptionListFirstParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set exception list pref, with subdomain wildcard");
  Services.prefs.setStringPref(
    EXCEPTION_LIST_PREF_NAME,
    `${TEST_ORIGIN},${TEST_3RD_PARTY_ORIGIN.replace("tracking", "*")}`
  );

  info("check data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: disableHeuristics ? "thirdParty" : "ExceptionListFirstParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("Removing the tab");
  BrowserTestUtils.removeTab(tabFirstParty);
  BrowserTestUtils.removeTab(tabThirdParty);

  await SpecialPowers.popPrefEnv();

  await cleanup();
}

add_task(async function testExceptionListPref() {
  await runTestExceptionListPref(false);
});

add_task(async function testExceptionListPrefDisabled() {
  await runTestExceptionListPref(true);
});

add_task(async function testExceptionListRemoteSettings() {
  info("Starting Dynamic FPI exception list test (remote settings)");

  await SpecialPowers.pushPrefEnv({
    set: [
      ["privacy.restrict3rdpartystorage.heuristic.recently_visited", false],
    ],
  });

  // Make sure we have a pref initially, since the exception list service
  // requires it.
  Services.prefs.setStringPref(EXCEPTION_LIST_PREF_NAME, "");

  // Add some initial data
  let db = RemoteSettings(COLLECTION_NAME).db;
  await db.importChanges({}, Date.now(), []);

  // make peuSerivce start working by calling
  // registerAndRunExceptionListObserver
  let updateEvent = new UpdateEvent();
  let obs = data => {
    let event = new CustomEvent("update", { detail: data });
    updateEvent.dispatchEvent(event);
  };
  let promise = waitForEvent(updateEvent, "update");
  peuService.registerAndRunExceptionListObserver(obs);
  await promise;

  info("Creating new tabs");
  let tabThirdParty = BrowserTestUtils.addTab(
    gBrowser,
    TEST_3RD_PARTY_PARTITIONED_PAGE
  );
  gBrowser.selectedTab = tabThirdParty;

  let browserThirdParty = gBrowser.getBrowserForTab(tabThirdParty);
  await BrowserTestUtils.browserLoaded(browserThirdParty);

  let tabFirstParty = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE);
  gBrowser.selectedTab = tabFirstParty;

  let browserFirstParty = gBrowser.getBrowserForTab(tabFirstParty);
  await BrowserTestUtils.browserLoaded(browserFirstParty);

  info("initializing...");
  await Promise.all([
    checkData(browserFirstParty, { firstParty: "", thirdParty: "" }),
    checkData(browserThirdParty, { firstParty: "" }),
  ]);

  info("fill default data");
  await Promise.all([
    createDataInFirstParty(browserFirstParty, "firstParty"),
    createDataInThirdParty(browserFirstParty, "thirdParty"),
    createDataInFirstParty(browserThirdParty, "ExceptionListFirstParty"),
  ]);

  info("check data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "thirdParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set exception list remote settings");

  // set records
  promise = waitForEvent(updateEvent, "update");
  await RemoteSettings(COLLECTION_NAME).emit("sync", {
    data: {
      current: [
        {
          id: "1",
          last_modified: 1000000000000001,
          firstPartyOrigin: TEST_ORIGIN,
          thirdPartyOrigin: TEST_3RD_PARTY_ORIGIN,
        },
      ],
    },
  });

  let list = await promise;
  is(
    list,
    `${TEST_ORIGIN},${TEST_3RD_PARTY_ORIGIN}`,
    "exception list is correctly set"
  );

  info("check data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "ExceptionListFirstParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("Removing the tab");
  BrowserTestUtils.removeTab(tabFirstParty);
  BrowserTestUtils.removeTab(tabThirdParty);

  promise = waitForEvent(updateEvent, "update");
  await RemoteSettings(COLLECTION_NAME).emit("sync", {
    data: {
      current: [],
    },
  });
  is(await promise, "", "Exception list is cleared");

  peuService.unregisterExceptionListObserver(obs);
  await cleanup();
});

add_task(async function testWildcardExceptionListPref() {
  info("Starting Dynamic FPI wirdcard exception list test pref");

  await SpecialPowers.pushPrefEnv({
    set: [
      ["privacy.restrict3rdpartystorage.heuristic.recently_visited", false],
    ],
  });

  info("Creating new tabs");
  let tabThirdParty = BrowserTestUtils.addTab(
    gBrowser,
    TEST_3RD_PARTY_PARTITIONED_PAGE
  );
  gBrowser.selectedTab = tabThirdParty;

  let browserThirdParty = gBrowser.getBrowserForTab(tabThirdParty);
  await BrowserTestUtils.browserLoaded(browserThirdParty);

  let tabFirstParty = BrowserTestUtils.addTab(gBrowser, TEST_TOP_PAGE);
  gBrowser.selectedTab = tabFirstParty;

  let browserFirstParty = gBrowser.getBrowserForTab(tabFirstParty);
  await BrowserTestUtils.browserLoaded(browserFirstParty);

  info("initializing...");
  await Promise.all([
    checkData(browserFirstParty, { firstParty: "", thirdParty: "" }),
    checkData(browserThirdParty, { firstParty: "" }),
  ]);

  info("fill default data");
  await Promise.all([
    createDataInFirstParty(browserFirstParty, "firstParty"),
    createDataInThirdParty(browserFirstParty, "thirdParty"),
    createDataInFirstParty(browserThirdParty, "ExceptionListFirstParty"),
  ]);

  info("check initial data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "thirdParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set wildcard (1st-party) pref");
  Services.prefs.setStringPref(
    EXCEPTION_LIST_PREF_NAME,
    `*,${TEST_3RD_PARTY_ORIGIN}`
  );

  info("check wildcard (1st-party) data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "ExceptionListFirstParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set invalid exception list pref");
  Services.prefs.setStringPref(EXCEPTION_LIST_PREF_NAME, "*,*");

  info("check initial data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "thirdParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("set wildcard (3rd-party) pref");
  Services.prefs.setStringPref(EXCEPTION_LIST_PREF_NAME, `${TEST_ORIGIN},*`);

  info("check wildcard (3rd-party) data");
  await Promise.all([
    checkData(browserFirstParty, {
      firstParty: "firstParty",
      thirdParty: "ExceptionListFirstParty",
    }),
    checkData(browserThirdParty, { firstParty: "ExceptionListFirstParty" }),
  ]);

  info("Removing the tab");
  BrowserTestUtils.removeTab(tabFirstParty);
  BrowserTestUtils.removeTab(tabThirdParty);

  await cleanup();
});