<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=1613063
Test that 302 redirect requests get upgraded to https:// with HTTPS-Only Mode enabled
-->

<head>
  <title>HTTPS-Only Mode - XHR Redirect Upgrade</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>

<body>
  <h1>HTTPS-Only Mode</h1>
  <p>Upgrade Test for insecure XHR redirects.</p>
  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1613063">Bug 1613063</a>

  <script type="application/javascript">

    const redirectCodes = ["301", "302", "303", "307"]
    let currentTest = 0

    function startTest() {
      const currentCode = redirectCodes[currentTest];

      const myXHR = new XMLHttpRequest();
      // Make a request to a site (eg. https://file_redirect.sjs?301), which will redirect to http://file_redirect.sjs?check.
      // The response will either be secure-ok, if the request has been upgraded to https:// or secure-error if it didn't.
      myXHR.open("GET", `https://example.com/tests/dom/security/test/https-only/file_redirect.sjs?${currentCode}`);
      myXHR.onload = (e) => {
        is(myXHR.responseText, "secure-ok", `a ${currentCode} redirect when posting violation report should be blocked`)
        testDone();
      }
      // This should not happen
      myXHR.onerror = (e) => {
        ok(false, `Could not query results from server for ${currentCode}-redirect test (" + e.message + ")`);
        testDone();
      }
      myXHR.send();
    }

    function testDone() {
      // Check if there are remaining tests
      if (++currentTest < redirectCodes.length) {
        startTest()
      } else {
        SimpleTest.finish();
      }
    }

    SimpleTest.waitForExplicitFinish();
    // Set preference and start test
    SpecialPowers.pushPrefEnv({ set: [["dom.security.https_only_mode", true]] }, startTest);

  </script>
</body>
</html>
