<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>Bug 1419222 - iFrame CSP should not affect parent document CSP</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>
<p id="display"></p>
<iframe style="width:100%;" id="testframe" src="file_independent_iframe_csp.html"></iframe>

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

  /* Description of the test:
    This test makes sure adding a CSP directive to an iFrame does not propagate
    the new directive to the parent document.

    The test page records it's own CSP before and after adding an iFrame
    with an additional CSP directive.

    CSPs before and after adding the iFrame are compared to make sure they do
    not differ.
   */

  SimpleTest.waitForExplicitFinish();

  function finishTest() {
    window.removeEventListener("message", compareCSPs);
    SimpleTest.finish();
  }

  function compareCSPs(event) {
    try {
      var beginCspObj = event.data.result[0];
      var iFrameCspObj = event.data.result[1];
      var endCspObj = event.data.result[2];

      // make sure the parent document had one policy from the start.
      var beginPolicies = beginCspObj["csp-policies"];
      is(beginPolicies.length, 1, "The parent doc should start with one policy applied.");

      // make sure the parent document still has one policy after adding the iFrame.
      var endPolicies = endCspObj["csp-policies"];
      is(endPolicies.length, 1, "The parent doc should still have one policy applied after adding the iFrame.");

      // make sure the iFrame has an additional CSP policy.
      var iFramePolicies = iFrameCspObj["csp-policies"];
      is(iFramePolicies.length, 2, "The iFrame should have two policies applied");

      var beginDirs = [];
      var endDirs = [];
      for (var dir in beginPolicies[0]) {
        beginDirs.push(dir);
      }
      for (var dir in endPolicies[0]) {
        endDirs.push(dir);
      }
      // Check correct number of CSP diretives.
      is(beginDirs.length, 3, "The parent's CSP policy should contain 3 directives.");
      // Compare the parent'S CSP directives before and after adding the iFrame.
      ok((beginDirs.length == endDirs.length && beginDirs.every((value, index) => value == endDirs[index])),
       "Begin and end CSP directives of the parent should not differ");
    }
    catch (e) {
      ok(false, "uuh, something went wrong within independent iFrame csp test");
    }

    finishTest();
  }

  // a postMessage handler to initiate the checks after the iFrame was added to
  // the test page.
  window.addEventListener("message", compareCSPs);

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