<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=1715253
Test that same origin redirect does not cause endless loop with https-first enabled
-->

<head>
  <title>HTTPS-First-Mode - Break endless upgrade downgrade redirect loop</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>

<body>
  <h1>HTTPS-First Mode</h1>
  <p>Upgrade Test for insecure redirects.</p>

  <script class="testbody" type="text/javascript">
  "use strict";

  SimpleTest.waitForExplicitFinish();

  const redirectCodes = ["301", "302","303","307"];
  let currentTest = 0;
  let testWin;
  window.addEventListener("message", receiveMessage);

  // receive message from loaded site verifying the scheme of
  // the loaded document.
  async function receiveMessage(event) {
    let currentRedirectCode = redirectCodes[currentTest];
    is(event.data.result,
       "scheme-http",
       "same-origin redirect results in 'http' for " + currentRedirectCode
    );
    testWin.close();
    if (++currentTest < redirectCodes.length) {
      startTest();
      return;
    }
    window.removeEventListener("message", receiveMessage);
    window.addEventListener("message", receiveMessageForDifferentPathTest);
    testDifferentPath();
  }

  async function receiveMessageForDifferentPathTest(event) {
    is(event.data.result,
       "scheme-https",
       "scheme should be https when the path is different"
    );
    testWin.close();
    window.removeEventListener("message", receiveMessageForDifferentPathTest);
    SimpleTest.finish();
  }

  async function startTest() {
    const currentCode = redirectCodes[currentTest];
    // Load an http:// window which gets upgraded to https://
    let uri =
      `http://example.com/tests/dom/security/test/https-first/file_break_endless_upgrade_downgrade_loop.sjs?${currentCode}`;
    testWin = window.open(uri);
  }

  async function testDifferentPath() {
    // Load an https:// window which gets downgraded to http://
    let uri =
      `https://example.com/tests/dom/security/test/https-first/file_break_endless_upgrade_downgrade_loop.sjs?downgrade`;
    testWin = window.open(uri);
  }

  // Set preference and start test
  SpecialPowers.pushPrefEnv({ set: [
    ["dom.security.https_first", true],
    ["security.mixed_content.block_active_content", false],
    ["security.mixed_content.block_display_content", false],
    ["dom.security.https_only_check_path_upgrade_downgrade_endless_loop", true],
  ]}, startTest);
  </script>
</body>
</html>
