summaryrefslogtreecommitdiffstats
path: root/toolkit/components/antitracking/bouncetrackingprotection/test/browser/head.js
blob: 71d9acedc629216cbec03fbf54b8dd6bbb152e02 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { SiteDataTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/SiteDataTestUtils.sys.mjs"
);

XPCOMUtils.defineLazyServiceGetter(
  this,
  "bounceTrackingProtection",
  "@mozilla.org/bounce-tracking-protection;1",
  "nsIBounceTrackingProtection"
);

const SITE_A = "example.com";
const ORIGIN_A = `https://${SITE_A}`;

const SITE_B = "example.org";
const ORIGIN_B = `https://${SITE_B}`;

const SITE_C = "example.net";
const ORIGIN_C = `https://${SITE_C}`;

const SITE_TRACKER = "itisatracker.org";
const ORIGIN_TRACKER = `https://${SITE_TRACKER}`;

const SITE_TRACKER_B = "trackertest.org";
// eslint-disable-next-line @microsoft/sdl/no-insecure-url
const ORIGIN_TRACKER_B = `http://${SITE_TRACKER_B}`;

// Test message used for observing when the record-bounces method in
// BounceTrackingProtection.cpp has finished.
const OBSERVER_MSG_RECORD_BOUNCES_FINISHED = "test-record-bounces-finished";

const ROOT_DIR = getRootDirectory(gTestPath);

/**
 * Get the base url for the current test directory using the given origin.
 * @param {string} origin - Origin to use in URL.
 * @returns {string} - Generated URL as a string.
 */
function getBaseUrl(origin) {
  return ROOT_DIR.replace("chrome://mochitests/content", origin);
}

/**
 * Constructs a url for an intermediate "bounce" hop which represents a tracker.
 * @param {*} options - URL generation options.
 * @param {('server'|'client')} options.bounceType - Redirect type to use for
 * the bounce.
 * @param {string} [options.bounceOrigin] - The origin of the bounce URL.
 * @param {string} [options.targetURL] - URL to redirect to after the bounce.
 * @param {('cookie-server'|'cookie-client'|'localStorage')} [options.setState]
 * Type of state to set during the redirect. Defaults to non stateful redirect.
 * @param {boolean} [options.setStateSameSiteFrame=false] - Whether to set the
 * state in a sub frame that is same site to the top window.
 * @param {boolean} [options.setStateInWebWorker=false] - Whether to set the
 * state in a web worker. This only supports setState == "indexedDB".
 * @param {boolean} [options.setStateInWebWorker=false] - Whether to set the
 * state in a nested web worker. Otherwise the same as setStateInWebWorker.
 * @param {number} [options.statusCode] - HTTP status code to use for server
 * side redirect. Only applies to bounceType == "server".
 * @param {number} [options.redirectDelayMS] - How long to wait before
 * redirecting. Only applies to bounceType == "client".
 * @returns {URL} Generated URL which points to an endpoint performing the
 * redirect.
 */
function getBounceURL({
  bounceType,
  bounceOrigin = ORIGIN_TRACKER,
  targetURL = new URL(getBaseUrl(ORIGIN_B) + "file_start.html"),
  setState = null,
  setStateSameSiteFrame = false,
  setStateInWebWorker = false,
  setStateInNestedWebWorker = false,
  statusCode = 302,
  redirectDelayMS = 50,
}) {
  if (!["server", "client"].includes(bounceType)) {
    throw new Error("Invalid bounceType");
  }

  let bounceFile =
    bounceType == "client" ? "file_bounce.html" : "file_bounce.sjs";

  let bounceUrl = new URL(getBaseUrl(bounceOrigin) + bounceFile);

  let { searchParams } = bounceUrl;
  searchParams.set("target", targetURL.href);
  if (setState) {
    searchParams.set("setState", setState);
  }
  if (setStateSameSiteFrame) {
    searchParams.set("setStateSameSiteFrame", setStateSameSiteFrame);
  }
  if (setStateInWebWorker) {
    if (setState != "indexedDB") {
      throw new Error(
        "setStateInWebWorker only supports setState == 'indexedDB'"
      );
    }
    searchParams.set("setStateInWebWorker", setStateInWebWorker);
  }
  if (setStateInNestedWebWorker) {
    if (setState != "indexedDB") {
      throw new Error(
        "setStateInNestedWebWorker only supports setState == 'indexedDB'"
      );
    }
    searchParams.set("setStateInNestedWebWorker", setStateInNestedWebWorker);
  }

  if (bounceType == "server") {
    searchParams.set("statusCode", statusCode);
  } else if (bounceType == "client") {
    searchParams.set("redirectDelay", redirectDelayMS);
  }

  return bounceUrl;
}

/**
 * Insert an <a href/> element with the given target and perform a synthesized
 * click on it.
 * @param {MozBrowser} browser - Browser to insert the link in.
 * @param {URL} targetURL - Destination for navigation.
 * @param {Object} options - Additional options.
 * @param {string} [options.spawnWindow] - If set to "newTab" or "popup" the
 * link will be opened in a new tab or popup window respectively. If unset the
 * link is opened in the given browser.
 * @returns {Promise} Resolves once the click is done. Does not wait for
 * navigation or load.
 */
async function navigateLinkClick(
  browser,
  targetURL,
  { spawnWindow = null } = {}
) {
  if (spawnWindow && !["newTab", "popup"].includes(spawnWindow)) {
    throw new Error(`Invalid option '${spawnWindow}' for spawnWindow`);
  }

  await SpecialPowers.spawn(
    browser,
    [targetURL.href, spawnWindow],
    async (targetURL, spawnWindow) => {
      let link = content.document.createElement("a");
      link.id = "link";
      link.textContent = "Click Me";
      link.style.display = "block";
      link.style.fontSize = "40px";

      // For opening a popup we attach an event listener to trigger via click.
      if (spawnWindow) {
        link.href = "#";
        link.addEventListener("click", event => {
          event.preventDefault();
          if (spawnWindow == "newTab") {
            // Open a new tab.
            content.window.open(targetURL, "bounce");
          } else {
            // Open a popup window.
            content.window.open(targetURL, "bounce", "height=200,width=200");
          }
        });
      } else {
        // For regular navigation add href and click.
        link.href = targetURL;
      }

      content.document.body.appendChild(link);

      // TODO: Bug 1892091: Use EventUtils.synthesizeMouse instead for a real click.
      SpecialPowers.wrap(content.document).notifyUserGestureActivation();
      content.document.userInteractionForTesting();
      link.click();
    }
  );
}

/**
 * Wait for the record-bounces method to run for the given tab / browser.
 * @param {browser} browser - Browser element which represents the tab we want
 * to observe.
 * @returns {Promise} Promise which resolves once the record-bounces method has
 * run for the given browser.
 */
async function waitForRecordBounces(browser) {
  return TestUtils.topicObserved(
    OBSERVER_MSG_RECORD_BOUNCES_FINISHED,
    subject => {
      // Ensure the message was dispatched for the browser we're interested in.
      let propBag = subject.QueryInterface(Ci.nsIPropertyBag2);
      let browserId = propBag.getProperty("browserId");
      return browser.browsingContext.browserId == browserId;
    }
  );
}

/**
 * Test helper which loads an initial blank page, then navigates to a url which
 * performs a bounce. Checks that the bounce hosts are properly identified as
 * trackers.
 * @param {object} options - Test Options.
 * @param {('server'|'client')} options.bounceType - Whether to perform a client
 * or server side redirect.
 * @param {('cookie-server'|'cookie-client'|'localStorage')} [options.setState]
 * Type of state to set during the redirect. Defaults to non stateful redirect.
 * @param {boolean} [options.setStateSameSiteFrame=false] - Whether to set the
 * state in a sub frame that is same site to the top window.
 * @param {boolean} [options.setStateInWebWorker=false] - Whether to set the
 * state in a web worker. This only supports setState == "indexedDB".
 * @param {boolean} [options.setStateInWebWorker=false] - Whether to set the
 * state in a nested web worker. Otherwise the same as setStateInWebWorker.
 * @param {boolean} [options.expectCandidate=true] - Expect the redirecting site
 * to be identified as a bounce tracker (candidate).
 * @param {boolean} [options.expectPurge=true] - Expect the redirecting site to
 * have its storage purged.
 * @param {OriginAttributes} [options.originAttributes={}] - Origin attributes
 * to use for the test. This determines whether the test is run in normal
 * browsing, a private window or a container tab. By default the test is run in
 * normal browsing.
 * @param {function} [options.postBounceCallback] - Optional function to run
 * after the bounce has completed.
 * @param {boolean} [options.skipSiteDataCleanup=false] - Skip the cleanup of
 * site data after the test. When this is enabled the caller is responsible for
 * cleaning up site data.
 */
async function runTestBounce(options = {}) {
  let {
    bounceType,
    setState = null,
    setStateSameSiteFrame = false,
    setStateInWebWorker = false,
    setStateInNestedWebWorker = false,
    expectCandidate = true,
    expectPurge = true,
    originAttributes = {},
    postBounceCallback = () => {},
    skipSiteDataCleanup = false,
  } = options;
  info(`runTestBounce ${JSON.stringify(options)}`);

  Assert.equal(
    bounceTrackingProtection.testGetBounceTrackerCandidateHosts(
      originAttributes
    ).length,
    0,
    "No bounce tracker hosts initially."
  );
  Assert.equal(
    bounceTrackingProtection.testGetUserActivationHosts(originAttributes)
      .length,
    0,
    "No user activation hosts initially."
  );

  let win = window;
  let { privateBrowsingId, userContextId } = originAttributes;
  let usePrivateWindow =
    privateBrowsingId != null &&
    privateBrowsingId !=
      Services.scriptSecurityManager.DEFAULT_PRIVATE_BROWSING_ID;
  if (userContextId != null && userContextId > 0 && usePrivateWindow) {
    throw new Error("userContextId is not supported in private windows");
  }

  if (usePrivateWindow) {
    win = await BrowserTestUtils.openNewBrowserWindow({ private: true });
  }

  let initialURL = getBaseUrl(ORIGIN_A) + "file_start.html";
  let tab = win.gBrowser.addTab(initialURL, {
    triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
    userContextId,
  });
  win.gBrowser.selectedTab = tab;

  let browser = tab.linkedBrowser;
  await BrowserTestUtils.browserLoaded(browser, true, initialURL);

  let promiseRecordBounces = waitForRecordBounces(browser);

  // The final destination after the bounce.
  let targetURL = new URL(getBaseUrl(ORIGIN_B) + "file_start.html");

  // Wait for the final site to be loaded which complete the BounceTrackingRecord.
  let targetURLLoadedPromise = BrowserTestUtils.browserLoaded(
    browser,
    false,
    targetURL
  );

  // Navigate through the bounce chain.
  await navigateLinkClick(
    browser,
    getBounceURL({
      bounceType,
      targetURL,
      setState,
      setStateSameSiteFrame,
      setStateInWebWorker,
      setStateInNestedWebWorker,
    })
  );

  await targetURLLoadedPromise;

  // Navigate again with user gesture which triggers
  // BounceTrackingProtection::RecordStatefulBounces. We could rely on the
  // timeout (mClientBounceDetectionTimeout) here but that can cause races
  // in debug where the load is quite slow.
  await navigateLinkClick(
    browser,
    new URL(getBaseUrl(ORIGIN_C) + "file_start.html")
  );

  await promiseRecordBounces;

  Assert.deepEqual(
    bounceTrackingProtection
      .testGetBounceTrackerCandidateHosts(originAttributes)
      .map(entry => entry.siteHost),
    expectCandidate ? [SITE_TRACKER] : [],
    `Should ${
      expectCandidate ? "" : "not "
    }have identified ${SITE_TRACKER} as a bounce tracker.`
  );
  Assert.deepEqual(
    bounceTrackingProtection
      .testGetUserActivationHosts(originAttributes)
      .map(entry => entry.siteHost)
      .sort(),
    [SITE_A, SITE_B].sort(),
    "Should only have user activation for sites where we clicked links."
  );

  // If the caller specified a function to run after the bounce, run it now.
  await postBounceCallback();

  Assert.deepEqual(
    await bounceTrackingProtection.testRunPurgeBounceTrackers(),
    expectPurge ? [SITE_TRACKER] : [],
    `Should ${expectPurge ? "" : "not "}purge state for ${SITE_TRACKER}.`
  );

  // Clean up
  BrowserTestUtils.removeTab(tab);
  if (usePrivateWindow) {
    await BrowserTestUtils.closeWindow(win);

    info(
      "Closing the last PBM window should trigger a purge of all PBM state."
    );
    Assert.ok(
      !bounceTrackingProtection.testGetBounceTrackerCandidateHosts(
        originAttributes
      ).length,
      "No bounce tracker hosts after closing private window."
    );
    Assert.ok(
      !bounceTrackingProtection.testGetUserActivationHosts(originAttributes)
        .length,
      "No user activation hosts after closing private window."
    );
  }
  bounceTrackingProtection.clearAll();
  if (!skipSiteDataCleanup) {
    await SiteDataTestUtils.clear();
  }
}