<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test for XMLHttpRequest with system privileges</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body onload="runTests();">
<p id="display">
</p>
<div id="content" style="display: none">

</div>
<pre id="test">
<script class="testbody" type="application/javascript">

let tests = [];

const PROTECTED_URL = "file:///etc/passwd";
const REDIRECT_URL = window.location.protocol + "//" + window.location.host + "/tests/dom/xhr/tests/file_XHR_system_redirect.html";
const CROSSSITE_URL = "http://example.com/tests/dom/xhr/tests/test_XHR_system.html";

tests.push(function test_cross_origin() {
  // System XHR can load cross-origin resources.

  is(window.location.hostname, "mochi.test", "correct origin");

  let xhr = new XMLHttpRequest({mozSystem: true});
  is(xhr.mozSystem, true, ".mozSystem == true");
  xhr.open("GET", CROSSSITE_URL);
  xhr.onload = function onload() {
    is(xhr.status, 200, "correct HTTP status");
    ok(xhr.responseText != null, "HTTP response non-null");
    ok(xhr.responseText.length, "HTTP response not empty");
    runNextTest();
  };
  xhr.onerror = function onerror(event) {
    ok(false, "Got an error event: " + event);
    runNextTest();
  }
  xhr.send();
});

tests.push(function test_file_uri() {
  // System XHR is not permitted to access file:/// URIs.

  let xhr = new XMLHttpRequest({mozSystem: true});
  is(xhr.mozSystem, true, ".mozSystem == true");
  xhr.open("GET", PROTECTED_URL);
  xhr.onload = function() {
    ok(false, "Should not have loaded");
    runNextTest();
  }
  xhr.onerror = function(event) {
    ok(true, "Got an error event: " + event);
    is(xhr.status, 0, "HTTP status is 0");
    runNextTest();
  }
  xhr.send();
});

tests.push(function test_redirect_to_file_uri() {
  // System XHR won't load file:/// URIs even if an HTTP resource redirects there.

  let xhr = new XMLHttpRequest({mozSystem: true});
  is(xhr.mozSystem, true, ".mozSystem == true");
  xhr.open("GET", REDIRECT_URL);
  xhr.onload = function onload() {
    ok(false, "Should not have loaded");
    runNextTest();
  };
  xhr.onerror = function onerror(event) {
    ok(true, "Got an error event: " + event);
    is(xhr.status, 0, "HTTP status is 0");
    runNextTest();
  }
  xhr.send();
});


function runNextTest() {
  if (!tests.length) {
    SimpleTest.finish();
    return;
  }
  tests.shift()();
}

function runTests() {
  SimpleTest.waitForExplicitFinish();

  SpecialPowers.pushPermissions([{'type': 'systemXHR', 'allow': true, 'context': document}], runNextTest);
}

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