<!DOCTYPE HTML>
<html>
<head>
  <title>Bug 1648825 - Fetch Metadata Headers contain invalid value for Sec-Fetch-Site for history manipulation</title>
  <!-- Including SimpleTest.js so we can use waitForExplicitFinish !-->
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>

<body>

<script class="testbody" type="text/javascript">

const REQUEST_PATH = 'tests/dom/security/test/sec-fetch/file_no_cache.sjs'
let sendHome = true;
let testCounter = 0;
let testFrame;

var script = SpecialPowers.loadChromeScript(() => {
  /* eslint-env mozilla/chrome-script */
  Services.obs.addObserver(function onExamResp(subject, topic, data) {
    let channel = subject.QueryInterface(Ci.nsIHttpChannel);
    info("request observed: " + channel.URI.spec);
    if (!channel.URI.spec.startsWith("https://example.org")) {
      return;
    }
    let headerPresent = false;
    try {
      is(channel.getRequestHeader("Sec-Fetch-Site"), "cross-site", "testing sec-fetch-site is cross-site");

      // This should fail and cause the catch clause to be executed.
      channel.getRequestHeader("Sec-Fetch-User");
      headerPresent = true;
    } catch (e) {
      headerPresent = false;
    }

    ok(!headerPresent, "testing sec-fetch-user header is not set");

    sendAsyncMessage("test-pass");
  }, "http-on-stop-request");
});

script.addMessageListener("test-pass", () => {
  testCounter++;
  if(testCounter == 2) {
    SimpleTest.finish();
  }
}); 

window.addEventListener("message", function (event) {
  iframeAction(event.data.test);
});

function iframeAction(test) {
  info("received message " + test);

  switch (test) {
    case 'test':
      testFrame.contentWindow.location  = `https://example.org/${REQUEST_PATH}?test#bypass`;
      if(sendHome) {
        // We need to send the message manually here because there is no request send to the server.
        window.postMessage({test: "home"}, "*");
        sendHome = false;
      }

      break;
    case 'home':
      testFrame.contentWindow.location  = `/${REQUEST_PATH}?back`;
      break;
    case 'back':
      testFrame.contentWindow.history.back();
      break;
  }
}

SimpleTest.waitForExplicitFinish();

testFrame = document.createElement('iframe');
testFrame.src = `https://example.org/${REQUEST_PATH}?test`;
document.body.appendChild(testFrame);

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