test_csp_upgrade_insecure_request_header.js (2721B)
1 const { HttpServer } = ChromeUtils.importESModule( 2 "resource://testing-common/httpd.sys.mjs" 3 ); 4 const { NetUtil } = ChromeUtils.importESModule( 5 "resource://gre/modules/NetUtil.sys.mjs" 6 ); 7 8 // Since this test creates a TYPE_DOCUMENT channel via javascript, it will 9 // end up using the wrong LoadInfo constructor. Setting this pref will disable 10 // the ContentPolicyType assertion in the constructor. 11 Services.prefs.setBoolPref("network.loadinfo.skip_type_assertion", true); 12 13 ChromeUtils.defineLazyGetter(this, "URL", function () { 14 return "http://localhost:" + httpserver.identity.primaryPort; 15 }); 16 17 var httpserver = null; 18 var channel = null; 19 var curTest = null; 20 var testpath = "/footpath"; 21 22 var tests = [ 23 { 24 description: "should not set request header for TYPE_OTHER", 25 expectingHeader: false, 26 contentType: Ci.nsIContentPolicy.TYPE_OTHER, 27 }, 28 { 29 description: "should set request header for TYPE_DOCUMENT", 30 expectingHeader: true, 31 contentType: Ci.nsIContentPolicy.TYPE_DOCUMENT, 32 }, 33 { 34 description: "should set request header for TYPE_SUBDOCUMENT", 35 expectingHeader: true, 36 contentType: Ci.nsIContentPolicy.TYPE_SUBDOCUMENT, 37 }, 38 { 39 description: "should not set request header for TYPE_IMAGE", 40 expectingHeader: false, 41 contentType: Ci.nsIContentPolicy.TYPE_IMAGE, 42 }, 43 ]; 44 45 function ChannelListener() {} 46 47 ChannelListener.prototype = { 48 onStartRequest() {}, 49 onDataAvailable() { 50 do_throw("Should not get any data!"); 51 }, 52 onStopRequest(request) { 53 var upgrade_insecure_header = false; 54 try { 55 if (request.getRequestHeader("Upgrade-Insecure-Requests")) { 56 upgrade_insecure_header = true; 57 } 58 } catch (e) { 59 // exception is thrown if header is not available on the request 60 } 61 // debug 62 // dump("executing test: " + curTest.description); 63 Assert.equal(upgrade_insecure_header, curTest.expectingHeader); 64 run_next_test(); 65 }, 66 }; 67 68 function setupChannel(aContentType) { 69 var chan = NetUtil.newChannel({ 70 uri: URL + testpath, 71 loadUsingSystemPrincipal: true, 72 contentPolicyType: aContentType, 73 }); 74 chan.QueryInterface(Ci.nsIHttpChannel); 75 chan.requestMethod = "GET"; 76 return chan; 77 } 78 79 function serverHandler() { 80 // no need to perform anything here 81 } 82 83 function run_next_test() { 84 curTest = tests.shift(); 85 if (!curTest) { 86 httpserver.stop(do_test_finished); 87 return; 88 } 89 channel = setupChannel(curTest.contentType); 90 channel.asyncOpen(new ChannelListener()); 91 } 92 93 function run_test() { 94 do_get_profile(); 95 96 // set up the test environment 97 httpserver = new HttpServer(); 98 httpserver.registerPathHandler(testpath, serverHandler); 99 httpserver.start(-1); 100 101 run_next_test(); 102 do_test_pending(); 103 }