summaryrefslogtreecommitdiffstats
path: root/dom/security/test/referrer-policy/referrer_testserver.sjs
blob: 10350b5da5d81aa494c0a3eaa66184b33972f78c (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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/*
 * Test server for iframe, anchor, and area referrer attributes.
 * https://bugzilla.mozilla.org/show_bug.cgi?id=1175736
 * Also server for further referrer tests such as redirecting tests
 * bug 1174913, bug 1175736, bug 1184781
 */

Cu.importGlobalProperties(["URLSearchParams"]);
const SJS = "referrer_testserver.sjs?";
const SJS_PATH = "/tests/dom/security/test/referrer-policy/";
const BASE_ORIGIN = "example.com";
const BASE_URL = BASE_ORIGIN + SJS_PATH + SJS;
const SHARED_KEY = SJS;
const SAME_ORIGIN = "mochi.test:8888" + SJS_PATH + SJS;
const CROSS_ORIGIN_URL = "test1.example.com" + SJS_PATH + SJS;

const IMG_BYTES = atob(
  "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12" +
    "P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
);

function createTestUrl(
  aPolicy,
  aAction,
  aName,
  aType,
  aSchemeFrom,
  aSchemeTo,
  crossOrigin,
  referrerPolicyHeader
) {
  var schemeTo = aSchemeTo || "http";
  var schemeFrom = aSchemeFrom || "http";
  var rpHeader = referrerPolicyHeader || "";
  var url = schemeTo + "://";
  url += crossOrigin ? CROSS_ORIGIN_URL : BASE_URL;
  url +=
    "ACTION=" +
    aAction +
    "&" +
    "policy=" +
    aPolicy +
    "&" +
    "NAME=" +
    aName +
    "&" +
    "type=" +
    aType +
    "&" +
    "RP_HEADER=" +
    rpHeader +
    "&" +
    "SCHEME_FROM=" +
    schemeFrom;
  return url;
}

// test page using iframe referrer attribute
// if aParams are set this creates a test where the iframe url is a redirect
function createIframeTestPageUsingRefferer(
  aMetaPolicy,
  aAttributePolicy,
  aNewAttributePolicy,
  aName,
  aParams,
  aSchemeFrom,
  aSchemeTo,
  aChangingMethod
) {
  var metaString = "";
  if (aMetaPolicy) {
    metaString = `<meta name="referrer" content="${aMetaPolicy}">`;
  }
  var changeString = "";
  if (aChangingMethod === "setAttribute") {
    changeString = `document.getElementById("myframe").setAttribute("referrerpolicy", "${aNewAttributePolicy}")`;
  } else if (aChangingMethod === "property") {
    changeString = `document.getElementById("myframe").referrerPolicy = "${aNewAttributePolicy}"`;
  }
  var iFrameString = `<iframe src="" id="myframe" ${
    aAttributePolicy ? ` referrerpolicy="${aAttributePolicy}"` : ""
  }>iframe</iframe>`;
  var iframeUrl = "";
  if (aParams) {
    aParams.delete("ACTION");
    aParams.append("ACTION", "redirectIframe");
    iframeUrl = "http://" + CROSS_ORIGIN_URL + aParams.toString();
  } else {
    iframeUrl = createTestUrl(
      aAttributePolicy,
      "test",
      aName,
      "iframe",
      aSchemeFrom,
      aSchemeTo
    );
  }

  return `<!DOCTYPE HTML>
           <html>
             <head>
             ${metaString}
             </head>
             <body>
               ${iFrameString}
               <script>
                 window.addEventListener("load", function() {
                   ${changeString}
                   document.getElementById("myframe").onload = function(){
                    parent.postMessage("childLoadComplete", "http://mochi.test:8888");
                   };
                   document.getElementById("myframe").src = "${iframeUrl}";
                 }.bind(window), false);
               </script>
             </body>
           </html>`;
}

function buildAnchorString(
  aMetaPolicy,
  aReferrerPolicy,
  aName,
  aRelString,
  aSchemeFrom,
  aSchemeTo
) {
  if (aReferrerPolicy) {
    return `<a href="${createTestUrl(
      aReferrerPolicy,
      "test",
      aName,
      "link",
      aSchemeFrom,
      aSchemeTo
    )}" referrerpolicy="${aReferrerPolicy}" id="link" ${aRelString}>${aReferrerPolicy}</a>`;
  }
  return `<a href="${createTestUrl(
    aMetaPolicy,
    "test",
    aName,
    "link",
    aSchemeFrom,
    aSchemeTo
  )}" id="link" ${aRelString}>link</a>`;
}

function buildAreaString(
  aMetaPolicy,
  aReferrerPolicy,
  aName,
  aRelString,
  aSchemeFrom,
  aSchemeTo
) {
  var result = `<img src="file_mozfiledataurl_img.jpg" alt="image" usemap="#imageMap">`;
  result += `<map name="imageMap">`;
  if (aReferrerPolicy) {
    result += `<area shape="circle" coords="1,1,1" href="${createTestUrl(
      aReferrerPolicy,
      "test",
      aName,
      "link",
      aSchemeFrom,
      aSchemeTo
    )}" alt="theArea" referrerpolicy="${aReferrerPolicy}" id="link" ${aRelString}>`;
  } else {
    result += `<area shape="circle" coords="1,1,1" href="${createTestUrl(
      aMetaPolicy,
      "test",
      aName,
      "link",
      aSchemeFrom,
      aSchemeTo
    )}" alt="theArea" id="link" ${aRelString}>`;
  }
  result += `</map>`;

  return result;
}

// test page using anchor or area referrer attribute
function createAETestPageUsingRefferer(
  aMetaPolicy,
  aAttributePolicy,
  aNewAttributePolicy,
  aName,
  aRel,
  aStringBuilder,
  aSchemeFrom,
  aSchemeTo,
  aChangingMethod
) {
  var metaString = "";
  if (aMetaPolicy) {
    metaString = `<head><meta name="referrer" content="${aMetaPolicy}"></head>`;
  }
  var changeString = "";
  if (aChangingMethod === "setAttribute") {
    changeString = `document.getElementById("link").setAttribute("referrerpolicy", "${aNewAttributePolicy}")`;
  } else if (aChangingMethod === "property") {
    changeString = `document.getElementById("link").referrerPolicy = "${aNewAttributePolicy}"`;
  }
  var relString = "";
  if (aRel) {
    relString = `rel="noreferrer"`;
  }
  var elementString = aStringBuilder(
    aMetaPolicy,
    aAttributePolicy,
    aName,
    relString,
    aSchemeFrom,
    aSchemeTo
  );

  return `<!DOCTYPE HTML>
           <html>
             ${metaString}
             <body>
               ${elementString}
               <script>
                 window.addEventListener("load", function() {
                   ${changeString}
                   document.getElementById("link").click();
                 }.bind(window), false);
               </script>
             </body>
           </html>`;
}

// test page using anchor target=_blank rel=noopener
function createTargetBlankRefferer(
  aMetaPolicy,
  aName,
  aSchemeFrom,
  aSchemeTo,
  aRpHeader
) {
  var metaString = "";
  if (aMetaPolicy) {
    metaString = `<head><meta name="referrer" content="${aMetaPolicy}"></head>`;
  }
  var elementString = `<a href="${createTestUrl(
    aMetaPolicy,
    "test",
    aName,
    "link",
    aSchemeFrom,
    aSchemeTo,
    aRpHeader
  )}" target=_blank rel="noopener" id="link">link</a>`;

  return `<!DOCTYPE HTML>
           <html>
             ${metaString}
             <body>
               ${elementString}
               <script>
                 window.addEventListener("load", function() {
                   let link = document.getElementById("link");
                   SpecialPowers.wrap(window).parent.postMessage("childLoadReady", "*");
                   link.click();
                 }.bind(window), false);
               </script>
             </body>
           </html>`;
}

// creates test page with img that is a redirect
function createRedirectImgTestCase(aParams, aAttributePolicy) {
  var metaString = "";
  if (aParams.has("META_POLICY")) {
    metaString = `<meta name="referrer" content="${aParams.get(
      "META_POLICY"
    )}">`;
  }
  aParams.delete("ACTION");
  aParams.append("ACTION", "redirectImg");
  var imgUrl = "http://" + CROSS_ORIGIN_URL + aParams.toString();

  return `<!DOCTYPE HTML>
          <html>
          <head>
          <meta charset="utf-8">
          ${metaString}
          <title>Test referrer policies on redirect (img)</title>
          </head>
          <body>
          <img id="testImg" src="${imgUrl}" ${
    aAttributePolicy ? ` referrerpolicy="${aAttributePolicy}"` : ""
  }>
          <script>
            window.addEventListener("load", function() {
              parent.postMessage("childLoadComplete", "http://mochi.test:8888");
            }.bind(window), false);
          </script>
          </body>
          </html>`;
}

// test page using link referrer attribute
function createLinkPageUsingRefferer(
  aMetaPolicy,
  aAttributePolicy,
  aNewAttributePolicy,
  aName,
  aRel,
  aStringBuilder,
  aSchemeFrom,
  aSchemeTo,
  aTestType
) {
  var metaString = "";
  if (aMetaPolicy) {
    metaString = `<meta name="referrer" content="${aMetaPolicy}">`;
  }

  var changeString = "";
  var policy = aAttributePolicy ? aAttributePolicy : aMetaPolicy;
  var elementString = aStringBuilder(
    policy,
    aName,
    aRel,
    aSchemeFrom,
    aSchemeTo,
    aTestType
  );

  if (aTestType === "setAttribute") {
    changeString = `var link = document.getElementById("test_link");
                    link.setAttribute("referrerpolicy", "${aNewAttributePolicy}");
                    link.href = "${createTestUrl(
                      policy,
                      "test",
                      aName,
                      "link_element_" + aRel,
                      aSchemeFrom,
                      aSchemeTo
                    )}";`;
  } else if (aTestType === "property") {
    changeString = `var link = document.getElementById("test_link");
                    link.referrerPolicy = "${aNewAttributePolicy}";
                    link.href = "${createTestUrl(
                      policy,
                      "test",
                      aName,
                      "link_element_" + aRel,
                      aSchemeFrom,
                      aSchemeTo
                    )}";`;
  }

  return `<!DOCTYPE HTML>
           <html>
             <head>
               ${metaString}
             </head>
             <body>
                ${elementString}
                <script>
                  ${changeString}
                </script>
             </body>
           </html>`;
}

function createFetchUserControlRPTestCase(
  aName,
  aSchemeFrom,
  aSchemeTo,
  crossOrigin
) {
  var srcUrl = createTestUrl(
    "",
    "test",
    aName,
    "fetch",
    aSchemeFrom,
    aSchemeTo,
    crossOrigin
  );

  return `<!DOCTYPE HTML>
          <html>
          <head>
          <meta charset="utf-8">
          <title>Test user control referrer policies</title>
          </head>
          <body>
          <script>
            fetch("${srcUrl}", {referrerPolicy: ""}).then(function (response) {
              window.parent.postMessage("childLoadComplete", "http://mochi.test:8888");
            });
          </script>
          </body>
          </html>`;
}

function buildLinkString(
  aPolicy,
  aName,
  aRel,
  aSchemeFrom,
  aSchemeTo,
  aTestType
) {
  var href = "";
  var onChildComplete = `window.parent.postMessage("childLoadComplete", "http://mochi.test:8888");`;
  var policy = "";
  var asString = "";
  var relString = "";

  if (aRel) {
    relString = `rel="${aRel}"`;
  }

  if (aPolicy) {
    policy = `referrerpolicy=${aPolicy}`;
  }

  if (aRel == "preload") {
    asString = 'as="image"';
  }

  if (!aTestType) {
    href = `href=${createTestUrl(
      aPolicy,
      "test",
      aName,
      "link_element_" + aRel,
      aSchemeFrom,
      aSchemeTo
    )}`;
  }

  return `<link ${relString} ${href} ${policy} ${asString} id="test_link" onload='${onChildComplete}' onerror='${onChildComplete}'>`;
}
// eslint-disable-next-line complexity
function handleRequest(request, response) {
  var params = new URLSearchParams(request.queryString);
  var action = params.get("ACTION");
  var schemeFrom = params.get("SCHEME_FROM") || "http";
  var schemeTo = params.get("SCHEME_TO") || "http";
  var crossOrigin = params.get("CROSS_ORIGIN") || false;
  var referrerPolicyHeader = params.get("RP_HEADER") || "";

  response.setHeader("Access-Control-Allow-Origin", "*", false);
  if (referrerPolicyHeader) {
    response.setHeader("Referrer-Policy", referrerPolicyHeader, false);
  }

  if (action === "resetState") {
    setSharedState(SHARED_KEY, "{}");
    response.write("");
    return;
  }
  if (action === "get-test-results") {
    // ?action=get-result
    response.setHeader("Cache-Control", "no-cache", false);
    response.setHeader("Content-Type", "text/plain", false);
    response.write(getSharedState(SHARED_KEY));
    return;
  }
  if (action === "redirect") {
    response.write(
      '<script>parent.postMessage("childLoadComplete", "http://mochi.test:8888");</script>'
    );
    return;
  }
  if (action === "redirectImg") {
    params.delete("ACTION");
    params.append("ACTION", "test");
    params.append("type", "img");
    // 302 found, 301 Moved Permanently, 303 See Other, 307 Temporary Redirect
    response.setStatusLine("1.1", 302, "found");
    response.setHeader(
      "Location",
      "http://" + CROSS_ORIGIN_URL + params.toString(),
      false
    );
    return;
  }
  if (action === "redirectIframe") {
    params.delete("ACTION");
    params.append("ACTION", "test");
    params.append("type", "iframe");
    // 302 found, 301 Moved Permanently, 303 See Other, 307 Temporary Redirect
    response.setStatusLine("1.1", 302, "found");
    response.setHeader(
      "Location",
      "http://" + CROSS_ORIGIN_URL + params.toString(),
      false
    );
    return;
  }
  if (action === "test") {
    // ?action=test&policy=origin&name=name
    let policy = params.get("policy");
    let name = params.get("NAME");
    let type = params.get("type");
    let result = getSharedState(SHARED_KEY);

    result = result ? JSON.parse(result) : {};

    var referrerLevel = "none";
    var test = {};
    if (request.hasHeader("Referer")) {
      var referrer = request.getHeader("Referer");
      if (referrer.indexOf("referrer_testserver") > 0) {
        referrerLevel = "full";
      } else if (referrer.indexOf(schemeFrom + "://example.com") == 0) {
        referrerLevel = "origin";
      } else {
        // this is never supposed to happen
        referrerLevel = "other-origin";
      }
      test.referrer = referrer;
    } else {
      test.referrer = "";
    }
    test.policy = referrerLevel;
    test.expected = policy;

    result[name] = test;

    setSharedState(SHARED_KEY, JSON.stringify(result));

    if (type === "img" || type == "link_element_preload") {
      // return image
      response.setHeader("Content-Type", "image/png");
      response.write(IMG_BYTES);
      return;
    }
    if (type === "iframe") {
      // return iframe page
      response.write("<html><body>I am the iframe</body></html>");
      return;
    }
    if (type === "link") {
      // forward link click to redirect URL to finish test
      var loc = "http://" + BASE_URL + "ACTION=redirect";
      response.setStatusLine("1.1", 302, "Found");
      response.setHeader("Location", loc, false);
    }
    return;
  }

  response.setHeader("Cache-Control", "no-cache", false);
  response.setHeader("Content-Type", "text/html; charset=utf-8", false);

  // parse test arguments and start test
  var attributePolicy = params.get("ATTRIBUTE_POLICY") || "";
  var newAttributePolicy = params.get("NEW_ATTRIBUTE_POLICY") || "";
  var metaPolicy = params.get("META_POLICY") || "";
  var rel = params.get("REL") || "";
  var name = params.get("NAME");

  // anchor & area
  var _getPage = createAETestPageUsingRefferer.bind(
    null,
    metaPolicy,
    attributePolicy,
    newAttributePolicy,
    name,
    rel
  );
  var _getAnchorPage = _getPage.bind(
    null,
    buildAnchorString,
    schemeFrom,
    schemeTo
  );
  var _getAreaPage = _getPage.bind(null, buildAreaString, schemeFrom, schemeTo);

  // aMetaPolicy, aAttributePolicy, aNewAttributePolicy, aName, aChangingMethod, aStringBuilder
  if (action === "generate-anchor-policy-test") {
    response.write(_getAnchorPage());
    return;
  }
  if (action === "generate-anchor-changing-policy-test-set-attribute") {
    response.write(_getAnchorPage("setAttribute"));
    return;
  }
  if (action === "generate-anchor-changing-policy-test-property") {
    response.write(_getAnchorPage("property"));
    return;
  }
  if (action === "generate-area-policy-test") {
    response.write(_getAreaPage());
    return;
  }
  if (action === "generate-area-changing-policy-test-set-attribute") {
    response.write(_getAreaPage("setAttribute"));
    return;
  }
  if (action === "generate-area-changing-policy-test-property") {
    response.write(_getAreaPage("property"));
    return;
  }
  if (action === "generate-anchor-target-blank-policy-test") {
    response.write(
      createTargetBlankRefferer(
        metaPolicy,
        name,
        schemeFrom,
        schemeTo,
        referrerPolicyHeader
      )
    );
    return;
  }

  // iframe
  _getPage = createIframeTestPageUsingRefferer.bind(
    null,
    metaPolicy,
    attributePolicy,
    newAttributePolicy,
    name,
    "",
    schemeFrom,
    schemeTo
  );

  // aMetaPolicy, aAttributePolicy, aNewAttributePolicy, aName, aChangingMethod
  if (action === "generate-iframe-policy-test") {
    response.write(_getPage());
    return;
  }
  if (action === "generate-iframe-changing-policy-test-set-attribute") {
    response.write(_getPage("setAttribute"));
    return;
  }
  if (action === "generate-iframe-changing-policy-test-property") {
    response.write(_getPage("property"));
    return;
  }

  // redirect tests with img and iframe
  if (action === "generate-img-redirect-policy-test") {
    response.write(createRedirectImgTestCase(params, attributePolicy));
    return;
  }
  if (action === "generate-iframe-redirect-policy-test") {
    response.write(
      createIframeTestPageUsingRefferer(
        metaPolicy,
        attributePolicy,
        newAttributePolicy,
        name,
        params,
        schemeFrom,
        schemeTo
      )
    );
    return;
  }

  _getPage = createLinkPageUsingRefferer.bind(
    null,
    metaPolicy,
    attributePolicy,
    newAttributePolicy,
    name,
    rel
  );
  var _getLinkPage = _getPage.bind(null, buildLinkString, schemeFrom, schemeTo);

  // link
  if (action === "generate-link-policy-test") {
    response.write(_getLinkPage());
    return;
  }
  if (action === "generate-link-policy-test-set-attribute") {
    response.write(_getLinkPage("setAttribute"));
    return;
  }
  if (action === "generate-link-policy-test-property") {
    response.write(_getLinkPage("property"));
    return;
  }

  if (action === "generate-fetch-user-control-policy-test") {
    response.write(
      createFetchUserControlRPTestCase(name, schemeFrom, schemeTo, crossOrigin)
    );
    return;
  }

  response.write("I don't know action " + action);
}