<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=1719309
Test that bad cert sites won't get upgraded by https-first
-->

<head>
  <title>HTTPS-FirstMode - Bad Certificates</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>Test: Downgrade bad certificates without warning page </p>
  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1706351">Bug 1719309</a>

  <script class="testbody" type="text/javascript">
  "use strict";
  /*
   * We perform the following tests:
   * 1. Request nocert.example.com which is a site without a certificate
   * 2. Request a site with self-signed cert (self-signed.example.com)
   * 3. Request a site with an untrusted cert (untrusted.example.com)
   * 4. Request a site with an expired cert
   * 5. Request a site with an untrusted and expired cert
   * 6. Request a site with no subject alternative dns name matching
   *
   * Expected result: Https-first tries to upgrade each request. Receives for each one an SSL_ERROR_*
   * and downgrades back to http.
   */
  const badCertificates = ["nocert","self-signed", "untrusted","expired","untrusted-expired", "no-subject-alt-name"];
  let currentTest = 0;
  let testWin;
  window.addEventListener("message", receiveMessage);

  // Receive message and verify that it is from an http site.
  // Verify that we got the correct message and an http scheme
  async function receiveMessage(event) {
    let data = event.data;
    let currentBadCert = badCertificates[currentTest];
    ok(data.result === "downgraded", "Downgraded request " + currentBadCert);
    ok(data.scheme === "http:", "Received 'http' for " + currentBadCert);
    testWin.close();
    if (++currentTest < badCertificates.length) {
      startTest();
      return;
    }
    window.removeEventListener("message", receiveMessage);
    SimpleTest.finish();
  }

  async function startTest() {
    const currentCode = badCertificates[currentTest];
    // make a request to a subdomain of example.com with a bad certificate
    testWin = window.open(`http://${currentCode}.example.com/tests/dom/security/test/https-first/file_bad_cert.sjs`);
  }

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