summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/attribution-reporting/resources/helpers.js
blob: e5c749931e03c2335d1a5f9f076fe3caaee70fa7 (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
/**
 * Helper functions for attribution reporting API tests.
 */

const blankURL = (base = location.origin) => new URL('/attribution-reporting/resources/reporting_origin.py', base);

const attribution_reporting_promise_test = (f, name) =>
    promise_test(async t => {
      await resetWptServer();
      return f(t);
    }, name);

const resetWptServer = () =>
    Promise
        .all([
          resetAttributionReports(eventLevelReportsUrl),
          resetAttributionReports(aggregatableReportsUrl),
          resetAttributionReports(eventLevelDebugReportsUrl),
          resetAttributionReports(aggregatableDebugReportsUrl),
          resetAttributionReports(verboseDebugReportsUrl),
          resetRegisteredSources(),
        ]);

const eventLevelReportsUrl =
    '/.well-known/attribution-reporting/report-event-attribution';
const eventLevelDebugReportsUrl =
    '/.well-known/attribution-reporting/debug/report-event-attribution';
const aggregatableReportsUrl =
    '/.well-known/attribution-reporting/report-aggregate-attribution';
const aggregatableDebugReportsUrl =
    '/.well-known/attribution-reporting/debug/report-aggregate-attribution';
const verboseDebugReportsUrl =
    '/.well-known/attribution-reporting/debug/verbose';

const attributionDebugCookie = 'ar_debug=1;Secure;HttpOnly;SameSite=None;Path=/';

const pipeHeaderPattern = /[,)]/g;

// , and ) in pipe values must be escaped with \
const encodeForPipe = urlString => urlString.replace(pipeHeaderPattern, '\\$&');

const blankURLWithHeaders = (headers, origin, status) => {
  const url = blankURL(origin);

  const parts = headers.map(h => `header(${h.name},${encodeForPipe(h.value)})`);

  if (status !== undefined) {
    parts.push(`status(${encodeForPipe(status)})`);
  }

  if (parts.length > 0) {
    url.searchParams.set('pipe', parts.join('|'));
  }

  return url;
};

/**
 * Clears the source registration stash.
 */
const resetRegisteredSources = () => {
  return fetch(`${blankURL()}?clear-stash=true`);
}

/**
 * Method to clear the stash. Takes the URL as parameter. This could be for
 * event-level or aggregatable reports.
 */
const resetAttributionReports = url => {
  // The view of the stash is path-specific (https://web-platform-tests.org/tools/wptserve/docs/stash.html),
  // therefore the origin doesn't need to be specified.
  url = `${url}?clear_stash=true`;
  const options = {
    method: 'POST',
  };
  return fetch(url, options);
};

const redirectReportsTo = origin => {
  return Promise.all([
      fetch(`${eventLevelReportsUrl}?redirect_to=${origin}`, {method: 'POST'}),
      fetch(`${aggregatableReportsUrl}?redirect_to=${origin}`, {method: 'POST'})
    ]);
};

const getFetchParams = (origin, cookie) => {
  let credentials;
  const headers = [];

  if (!origin || origin === location.origin) {
    return {credentials, headers};
  }

  // https://fetch.spec.whatwg.org/#http-cors-protocol

  const allowOriginHeader = 'Access-Control-Allow-Origin';

  if (cookie) {
    credentials = 'include';
    headers.push({
      name: 'Access-Control-Allow-Credentials',
      value: 'true',
    });
    headers.push({
      name: allowOriginHeader,
      value: `${location.origin}`,
    });
  } else {
    headers.push({
      name: allowOriginHeader,
      value: '*',
    });
  }
  return {credentials, headers};
};

const getDefaultReportingOrigin = () => {
  // cross-origin means that the reporting origin differs from the source/destination origin.
  const crossOrigin = new URLSearchParams(location.search).get('cross-origin');
  return crossOrigin === null ? location.origin : get_host_info().HTTPS_REMOTE_ORIGIN;
};

const createRedirectChain = (redirects) => {
  let redirectTo;

  for (let i = redirects.length - 1; i >= 0; i--) {
    const {source, trigger, cookie, reportingOrigin} = redirects[i];
    const headers = [];

    if (source) {
      headers.push({
        name: 'Attribution-Reporting-Register-Source',
        value: JSON.stringify(source),
      });
    }

    if (trigger) {
      headers.push({
        name: 'Attribution-Reporting-Register-Trigger',
        value: JSON.stringify(trigger),
      });
    }

    if (cookie) {
      headers.push({name: 'Set-Cookie', value: cookie});
    }

    let status;
    if (redirectTo) {
      headers.push({name: 'Location', value: redirectTo.toString()});
      status = '302';
    }

    redirectTo = blankURLWithHeaders(
        headers, reportingOrigin || getDefaultReportingOrigin(), status);
  }

  return redirectTo;
};

const registerAttributionSrcByImg = (attributionSrc) => {
  const element = document.createElement('img');
  element.attributionSrc = attributionSrc;
};

const registerAttributionSrc = async ({
  source,
  trigger,
  cookie,
  method = 'img',
  extraQueryParams = {},
  reportingOrigin,
  extraHeaders = [],
}) => {
  const searchParams = new URLSearchParams(location.search);

  if (method === 'variant') {
    method = searchParams.get('method');
  }

  const eligible = searchParams.get('eligible');

  let headers = [];

  if (source) {
    headers.push({
      name: 'Attribution-Reporting-Register-Source',
      value: JSON.stringify(source),
    });
  }

  if (trigger) {
    headers.push({
      name: 'Attribution-Reporting-Register-Trigger',
      value: JSON.stringify(trigger),
    });
  }

  if (cookie) {
    const name = 'Set-Cookie';
    headers.push({name, value: cookie});
  }


  let credentials;
  if (method === 'fetch') {
    const params = getFetchParams(reportingOrigin, cookie);
    credentials = params.credentials;
    headers = headers.concat(params.headers);
  }

  headers = headers.concat(extraHeaders);

  const url = blankURLWithHeaders(headers, reportingOrigin);

  Object.entries(extraQueryParams)
      .forEach(([key, value]) => url.searchParams.set(key, value));

  switch (method) {
    case 'img':
      const img = document.createElement('img');
      if (eligible === null) {
        img.attributionSrc = url;
      } else {
        await new Promise(resolve => {
          img.onload = resolve;
          // Since the resource being fetched isn't a valid image, onerror will
          // be fired, but the browser will still process the
          // attribution-related headers, so resolve the promise instead of
          // rejecting.
          img.onerror = resolve;
          img.attributionSrc = '';
          img.src = url;
        });
      }
      return 'event';
    case 'script':
      const script = document.createElement('script');
      if (eligible === null) {
        script.attributionSrc = url;
      } else {
        await new Promise(resolve => {
          script.onload = resolve;
          script.attributionSrc = '';
          script.src = url;
          document.body.appendChild(script);
        });
      }
      return 'event';
    case 'a':
      const a = document.createElement('a');
      a.target = '_blank';
      a.textContent = 'link';
      if (eligible === null) {
        a.attributionSrc = url;
        a.href = blankURL();
      } else {
        a.attributionSrc = '';
        a.href = url;
      }
      document.body.appendChild(a);
      await test_driver.click(a);
      return 'navigation';
    case 'open':
      await test_driver.bless('open window', () => {
        if (eligible === null) {
          open(
              blankURL(), '_blank',
              `attributionsrc=${encodeURIComponent(url)}`);
        } else {
          open(url, '_blank', 'attributionsrc');
        }
      });
      return 'navigation';
    case 'fetch': {
      let attributionReporting;
      if (eligible !== null) {
        attributionReporting = JSON.parse(eligible);
      }
      await fetch(url, {credentials, attributionReporting});
      return 'event';
    }
    case 'xhr':
      await new Promise((resolve, reject) => {
        const req = new XMLHttpRequest();
        req.open('GET', url);
        if (eligible !== null) {
          req.setAttributionReporting(JSON.parse(eligible));
        }
        req.onload = resolve;
        req.onerror = () => reject(req.statusText);
        req.send();
      });
      return 'event';
    default:
      throw `unknown method "${method}"`;
  }
};


/**
 * Generates a random pseudo-unique source event id.
 */
const generateSourceEventId = () => {
  return `${Math.round(Math.random() * 10000000000000)}`;
}

/**
 * Delay method that waits for prescribed number of milliseconds.
 */
const delay = ms => new Promise(resolve => step_timeout(resolve, ms));

/**
 * Method that polls a particular URL for reports. Once reports
 * are received, returns the payload as promise. Returns null if the
 * timeout is reached before a report is available.
 */
const pollAttributionReports = async (url, origin = location.origin, timeout = 60 * 1000 /*ms*/) => {
  let startTime = performance.now();
  while (performance.now() - startTime < timeout) {
    const resp = await fetch(new URL(url, origin));
    const payload = await resp.json();
    if (payload.reports.length > 0) {
      return payload;
    }
    await delay(/*ms=*/ 100);
  }
  return null;
};

// Verbose debug reporting must have been enabled on the source registration for this to work.
const waitForSourceToBeRegistered = async (sourceId, reportingOrigin) => {
  const debugReportPayload = await pollVerboseDebugReports(reportingOrigin);
  assert_equals(debugReportPayload.reports.length, 1);
  const debugReport = JSON.parse(debugReportPayload.reports[0].body);
  assert_equals(debugReport.length, 1);
  assert_equals(debugReport[0].type, 'source-success');
  assert_equals(debugReport[0].body.source_event_id, sourceId);
};

const pollEventLevelReports = (origin) =>
    pollAttributionReports(eventLevelReportsUrl, origin);
const pollEventLevelDebugReports = (origin) =>
    pollAttributionReports(eventLevelDebugReportsUrl, origin);
const pollAggregatableReports = (origin) =>
    pollAttributionReports(aggregatableReportsUrl, origin);
const pollAggregatableDebugReports = (origin) =>
    pollAttributionReports(aggregatableDebugReportsUrl, origin);
const pollVerboseDebugReports = (origin) =>
    pollAttributionReports(verboseDebugReportsUrl, origin);

const validateReportHeaders = headers => {
  assert_array_equals(headers['content-type'], ['application/json']);
  assert_array_equals(headers['cache-control'], ['no-cache']);
  assert_own_property(headers, 'user-agent');
  assert_not_own_property(headers, 'cookie');
  assert_not_own_property(headers, 'referer');
};