summaryrefslogtreecommitdiffstats
path: root/toolkit/components/antitracking/test/browser/browser_storageAccessPrivilegeAPI.js
blob: 9594fdf270b166dec21e92f72b32c8fde4f2d47c (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
//
// Bug 1724376 - Tests for the privilege requestStorageAccessForOrigin API.
//

/* import-globals-from storageAccessAPIHelpers.js */

"use strict";

const TEST_ANOTHER_TRACKER_DOMAIN = "https://itisatracker.org/";
const TEST_ANOTHER_TRACKER_PAGE =
  TEST_ANOTHER_TRACKER_DOMAIN + TEST_PATH + "3rdParty.html";
const TEST_ANOTHER_4TH_PARTY_DOMAIN = "https://test1.example.org/";
const TEST_ANOTHER_4TH_PARTY_PAGE =
  TEST_ANOTHER_4TH_PARTY_DOMAIN + TEST_PATH + "3rdParty.html";

// Insert an iframe with the given id into the content.
async function insertSubFrame(browser, url, id) {
  return SpecialPowers.spawn(browser, [url, id], async (url, id) => {
    let ifr = content.document.createElement("iframe");
    ifr.setAttribute("id", id);

    let loaded = ContentTaskUtils.waitForEvent(ifr, "load", false);
    content.document.body.appendChild(ifr);
    ifr.src = url;
    await loaded;
  });
}

// Run the given script in the iframe with the given id.
function runScriptInSubFrame(browser, id, script) {
  return SpecialPowers.spawn(
    browser,
    [{ callback: script.toString(), id }],
    async obj => {
      await new content.Promise(resolve => {
        let ifr = content.document.getElementById(obj.id);

        content.addEventListener("message", function msg(event) {
          if (event.data.type == "finish") {
            content.removeEventListener("message", msg);
            resolve();
            return;
          }

          if (event.data.type == "ok") {
            ok(event.data.what, event.data.msg);
            return;
          }

          if (event.data.type == "info") {
            info(event.data.msg);
            return;
          }

          ok(false, "Unknown message");
        });

        ifr.contentWindow.postMessage(obj.callback, "*");
      });
    }
  );
}

function waitStoragePermission(trackingOrigin) {
  return TestUtils.topicObserved("perm-changed", (aSubject, aData) => {
    let permission = aSubject.QueryInterface(Ci.nsIPermission);
    let uri = Services.io.newURI(TEST_DOMAIN);
    return (
      permission.type == `3rdPartyStorage^${trackingOrigin}` &&
      permission.principal.equalsURI(uri)
    );
  });
}

function clearStoragePermission(trackingOrigin) {
  return SpecialPowers.removePermission(
    `3rdPartyStorage^${trackingOrigin}`,
    TEST_TOP_PAGE
  );
}

function triggerCommand(button) {
  let notifications = PopupNotifications.panel.children;
  let notification = notifications[0];
  EventUtils.synthesizeMouseAtCenter(notification[button], {});
}

function triggerMainCommand() {
  triggerCommand("button");
}

function triggerSecondaryCommand() {
  triggerCommand("secondaryButton");
}

add_setup(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["dom.storage_access.auto_grants", true],
      ["dom.storage_access.auto_grants.delayed", false],
      ["dom.storage_access.enabled", true],
      ["dom.storage_access.prompt.testing", 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],
    ],
  });

  await UrlClassifierTestUtils.addTestTrackers();

  registerCleanupFunction(() => {
    SpecialPowers.clearUserPref("network.cookie.sameSite.laxByDefault");
    UrlClassifierTestUtils.cleanupTestTrackers();
  });
});

add_task(async function test_api_only_available_in_privilege_scope() {
  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    TEST_TOP_PAGE
  );
  let browser = tab.linkedBrowser;

  await SpecialPowers.spawn(browser, [], async _ => {
    ok(
      content.document.requestStorageAccessForOrigin,
      "The privilege API is available in system privilege code."
    );
  });

  // Open an iframe and check if the privilege is not available in content code.
  await insertSubFrame(browser, TEST_3RD_PARTY_PAGE, "test");
  await runScriptInSubFrame(browser, "test", async function check() {
    ok(
      !document.requestStorageAccessForOrigin,
      "The privilege API is not available in content code."
    );
  });

  BrowserTestUtils.removeTab(tab);
});

add_task(async function test_privilege_api_with_reject_tracker() {
  await SpecialPowers.pushPrefEnv({
    set: [
      [
        "network.cookie.cookieBehavior",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER,
      ],
      [
        "network.cookie.cookieBehavior.pbmode",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER,
      ],
    ],
  });

  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    TEST_TOP_PAGE
  );
  let browser = tab.linkedBrowser;

  await insertSubFrame(browser, TEST_3RD_PARTY_PAGE, "test");

  // Verify that the third party tracker doesn't have storage access at
  // beginning.
  await runScriptInSubFrame(browser, "test", async _ => {
    await noStorageAccessInitially();

    is(document.cookie, "", "No cookies for me");
    document.cookie = "name=value";
    is(document.cookie, "", "Setting cookie is blocked");
  });

  let storagePermissionPromise = waitStoragePermission(
    "https://tracking.example.org"
  );

  // Verify if the prompt has been shown.
  let shownPromise = BrowserTestUtils.waitForEvent(
    PopupNotifications.panel,
    "popupshown"
  );

  // Call the privilege API.
  let callAPIPromise = SpecialPowers.spawn(browser, [], async _ => {
    // The privilege API requires user activation. So, we set the user
    // activation flag before we call the API.
    content.document.notifyUserGestureActivation();

    try {
      await content.document.requestStorageAccessForOrigin(
        "https://tracking.example.org/"
      );
    } catch (e) {
      ok(false, "The API shouldn't throw.");
    }

    content.document.clearUserGestureActivation();
  });

  await shownPromise;

  // Accept the prompt
  triggerMainCommand();

  await callAPIPromise;

  // Verify if the storage access permission is set correctly.
  await storagePermissionPromise;

  // Verify if the existing third-party tracker iframe gains the storage
  // access.
  await runScriptInSubFrame(browser, "test", async _ => {
    await hasStorageAccessInitially();

    is(document.cookie, "", "Still no cookies for me");
    document.cookie = "name=value";
    is(document.cookie, "name=value", "Successfully set cookies.");
  });

  // Insert another third-party tracker iframe and check if it has storage access.
  await insertSubFrame(browser, TEST_3RD_PARTY_PAGE, "test2");
  await runScriptInSubFrame(browser, "test2", async _ => {
    await hasStorageAccessInitially();

    is(document.cookie, "name=value", "Some cookies for me");
  });

  // Insert another iframe with different third-party tracker and check it has
  // no storage access.
  await insertSubFrame(browser, TEST_ANOTHER_TRACKER_PAGE, "test3");
  await runScriptInSubFrame(browser, "test3", async _ => {
    await noStorageAccessInitially();

    is(document.cookie, "", "No cookies for me");
    document.cookie = "name=value";
    is(document.cookie, "", "Setting cookie is blocked for another tracker.");
  });

  await clearStoragePermission("https://tracking.example.org");
  Services.cookies.removeAll();
  BrowserTestUtils.removeTab(tab);
});

add_task(async function test_privilege_api_with_dFPI() {
  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,
      ],
    ],
  });

  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    TEST_TOP_PAGE
  );
  let browser = tab.linkedBrowser;

  await insertSubFrame(browser, TEST_4TH_PARTY_PAGE_HTTPS, "test");

  // Verify that the third-party context doesn't have storage access at
  // beginning.
  await runScriptInSubFrame(browser, "test", async _ => {
    await noStorageAccessInitially();

    is(document.cookie, "", "No cookies for me");
    document.cookie = "name=partitioned";
    is(
      document.cookie,
      "name=partitioned",
      "Setting cookie in partitioned context."
    );
  });

  let storagePermissionPromise = waitStoragePermission(
    "https://not-tracking.example.com"
  );

  // Verify if the prompt has been shown.
  let shownPromise = BrowserTestUtils.waitForEvent(
    PopupNotifications.panel,
    "popupshown"
  );

  // Call the privilege API.
  let callAPIPromise = SpecialPowers.spawn(browser, [], async _ => {
    // The privilege API requires a user gesture. So, we set the user handling
    // flag before we call the API.
    content.document.notifyUserGestureActivation();

    try {
      await content.document.requestStorageAccessForOrigin(
        "https://not-tracking.example.com/"
      );
    } catch (e) {
      ok(false, "The API shouldn't throw.");
    }

    content.document.clearUserGestureActivation();
  });

  await shownPromise;

  // Accept the prompt
  triggerMainCommand();

  await callAPIPromise;

  // Verify if the storage access permission is set correctly.
  await storagePermissionPromise;

  // Verify if the existing third-party iframe gains the storage access.
  await runScriptInSubFrame(browser, "test", async _ => {
    await hasStorageAccessInitially();

    is(document.cookie, "", "No unpartitioned cookies");
    document.cookie = "name=unpartitioned";
    is(document.cookie, "name=unpartitioned", "Successfully set cookies.");
  });

  // Insert another third-party content iframe and check if it has storage access.
  await insertSubFrame(browser, TEST_4TH_PARTY_PAGE_HTTPS, "test2");
  await runScriptInSubFrame(browser, "test2", async _ => {
    await hasStorageAccessInitially();

    is(
      document.cookie,
      "name=unpartitioned",
      "Some cookies for unpartitioned context"
    );
  });

  // Insert another iframe with different third-party content and check it has
  // no storage access.
  await insertSubFrame(browser, TEST_ANOTHER_4TH_PARTY_PAGE, "test3");
  await runScriptInSubFrame(browser, "test3", async _ => {
    await noStorageAccessInitially();

    is(document.cookie, "", "No cookies for me");
    document.cookie = "name=value";
    is(document.cookie, "name=value", "Setting cookie to partitioned context.");
  });

  await clearStoragePermission("https://not-tracking.example.com");
  Services.cookies.removeAll();
  BrowserTestUtils.removeTab(tab);
});

add_task(async function test_prompt() {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["dom.storage_access.auto_grants", false],
      [
        "network.cookie.cookieBehavior",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER,
      ],
      [
        "network.cookie.cookieBehavior.pbmode",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER,
      ],
    ],
  });

  for (const allow of [false, true]) {
    let tab = await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      TEST_TOP_PAGE
    );
    let browser = tab.linkedBrowser;

    // Verify if the prompt has been shown.
    let shownPromise = BrowserTestUtils.waitForEvent(
      PopupNotifications.panel,
      "popupshown"
    );

    let hiddenPromise = BrowserTestUtils.waitForEvent(
      PopupNotifications.panel,
      "popuphidden"
    );

    // Call the privilege API.
    let callAPIPromise = SpecialPowers.spawn(browser, [allow], async allow => {
      // The privilege API requires a user gesture. So, we set the user handling
      // flag before we call the API.
      content.document.notifyUserGestureActivation();
      let isThrown = false;

      try {
        await content.document.requestStorageAccessForOrigin(
          "https://tracking.example.org"
        );
      } catch (e) {
        isThrown = true;
      }

      is(isThrown, !allow, `The API ${allow ? "shouldn't" : "should"} throw.`);

      content.document.clearUserGestureActivation();
    });

    await shownPromise;

    let notification = await TestUtils.waitForCondition(_ =>
      PopupNotifications.getNotification("storage-access", browser)
    );
    ok(notification, "Should have gotten the notification");

    // Click the popup button.
    if (allow) {
      triggerMainCommand();
    } else {
      triggerSecondaryCommand();
    }

    // Wait until the popup disappears.
    await hiddenPromise;

    // Wait until the API finishes.
    await callAPIPromise;

    await insertSubFrame(browser, TEST_3RD_PARTY_PAGE, "test");

    if (allow) {
      await runScriptInSubFrame(browser, "test", async _ => {
        await hasStorageAccessInitially();

        is(document.cookie, "", "Still no cookies for me");
        document.cookie = "name=value";
        is(document.cookie, "name=value", "Successfully set cookies.");
      });
    } else {
      await runScriptInSubFrame(browser, "test", async _ => {
        await noStorageAccessInitially();

        is(document.cookie, "", "Still no cookies for me");
        document.cookie = "name=value";
        is(document.cookie, "", "No cookie after setting.");
      });
    }

    BrowserTestUtils.removeTab(tab);
  }

  await clearStoragePermission("https://tracking.example.org");
  Services.cookies.removeAll();
});

// Tests that the priviledged rSA method should show a prompt when auto grants
// are enabled, but we don't have user activation. When requiring user
// activation, rSA should still reject.
add_task(async function test_prompt_no_user_activation() {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["dom.storage_access.auto_grants", true],
      [
        "network.cookie.cookieBehavior",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER,
      ],
      [
        "network.cookie.cookieBehavior.pbmode",
        Ci.nsICookieService.BEHAVIOR_REJECT_TRACKER,
      ],
    ],
  });

  for (let requireUserActivation of [false, true]) {
    let tab = await BrowserTestUtils.openNewForegroundTab(
      gBrowser,
      TEST_TOP_PAGE
    );
    let browser = tab.linkedBrowser;

    let shownPromise, hiddenPromise;

    // Verify if the prompt has been shown.
    if (!requireUserActivation) {
      shownPromise = BrowserTestUtils.waitForEvent(
        PopupNotifications.panel,
        "popupshown"
      );

      hiddenPromise = BrowserTestUtils.waitForEvent(
        PopupNotifications.panel,
        "popuphidden"
      );
    }

    // Call the privilege API.
    let callAPIPromise = SpecialPowers.spawn(
      browser,
      [requireUserActivation],
      async requireUserActivation => {
        let isThrown = false;

        try {
          await content.document.requestStorageAccessForOrigin(
            "https://tracking.example.org",
            requireUserActivation
          );
        } catch (e) {
          isThrown = true;
        }

        is(
          isThrown,
          requireUserActivation,
          `The API ${requireUserActivation ? "shouldn't" : "should"} throw.`
        );
      }
    );

    if (!requireUserActivation) {
      await shownPromise;

      let notification = await TestUtils.waitForCondition(_ =>
        PopupNotifications.getNotification("storage-access", browser)
      );
      ok(notification, "Should have gotten the notification");

      // Click the popup button.
      triggerMainCommand();

      // Wait until the popup disappears.
      await hiddenPromise;
    }

    // Wait until the API finishes.
    await callAPIPromise;

    await insertSubFrame(browser, TEST_3RD_PARTY_PAGE, "test");

    if (!requireUserActivation) {
      await runScriptInSubFrame(browser, "test", async _ => {
        await hasStorageAccessInitially();

        is(document.cookie, "", "Still no cookies for me");
        document.cookie = "name=value";
        is(document.cookie, "name=value", "Successfully set cookies.");
      });
    } else {
      await runScriptInSubFrame(browser, "test", async _ => {
        await noStorageAccessInitially();

        is(document.cookie, "", "Still no cookies for me");
        document.cookie = "name=value";
        is(document.cookie, "", "No cookie after setting.");
      });
    }

    BrowserTestUtils.removeTab(tab);
    await clearStoragePermission("https://tracking.example.org");
    Services.cookies.removeAll();
  }
});

add_task(async function test_invalid_input() {
  let tab = await BrowserTestUtils.openNewForegroundTab(
    gBrowser,
    TEST_TOP_PAGE
  );
  let browser = tab.linkedBrowser;

  await SpecialPowers.spawn(browser, [], async _ => {
    let isThrown = false;
    try {
      await content.document.requestStorageAccessForOrigin(
        "https://tracking.example.org"
      );
    } catch (e) {
      isThrown = true;
    }
    ok(isThrown, "The API should throw without user gesture.");

    content.document.notifyUserGestureActivation();
    isThrown = false;
    try {
      await content.document.requestStorageAccessForOrigin();
    } catch (e) {
      isThrown = true;
    }
    ok(isThrown, "The API should throw with no input.");

    content.document.notifyUserGestureActivation();
    isThrown = false;
    try {
      await content.document.requestStorageAccessForOrigin("");
    } catch (e) {
      isThrown = true;
      is(e.name, "NS_ERROR_MALFORMED_URI", "The input is not a valid url");
    }
    ok(isThrown, "The API should throw with empty string.");

    content.document.notifyUserGestureActivation();
    isThrown = false;
    try {
      await content.document.requestStorageAccessForOrigin("invalid url");
    } catch (e) {
      isThrown = true;
      is(e.name, "NS_ERROR_MALFORMED_URI", "The input is not a valid url");
    }
    ok(isThrown, "The API should throw with invalid url.");

    content.document.clearUserGestureActivation();
  });

  BrowserTestUtils.removeTab(tab);
});