file_testserver.sjs (1950B)
1 // SJS file for CSP mochitests 2 "use strict"; 3 const { NetUtil } = ChromeUtils.importESModule( 4 "resource://gre/modules/NetUtil.sys.mjs" 5 ); 6 7 function loadHTMLFromFile(path) { 8 // Load the HTML to return in the response from file. 9 // Since it's relative to the cwd of the test runner, we start there and 10 // append to get to the actual path of the file. 11 const testHTMLFile = Cc["@mozilla.org/file/directory_service;1"] 12 .getService(Ci.nsIProperties) 13 .get("CurWorkD", Ci.nsIFile); 14 15 const testHTMLFileStream = Cc[ 16 "@mozilla.org/network/file-input-stream;1" 17 ].createInstance(Ci.nsIFileInputStream); 18 19 path 20 .split("/") 21 .filter(path => path) 22 .reduce((file, path) => { 23 testHTMLFile.append(path); 24 return testHTMLFile; 25 }, testHTMLFile); 26 testHTMLFileStream.init(testHTMLFile, -1, 0, 0); 27 const isAvailable = testHTMLFileStream.available(); 28 return NetUtil.readInputStreamToString(testHTMLFileStream, isAvailable); 29 } 30 31 function handleRequest(request, response) { 32 const query = new URLSearchParams(request.queryString); 33 34 // avoid confusing cache behaviors 35 response.setHeader("Cache-Control", "no-cache", false); 36 37 // Deliver the CSP policy encoded in the URL 38 if (query.has("csp")) { 39 response.setHeader("Content-Security-Policy", query.get("csp"), false); 40 } 41 42 // Deliver the CSP report-only policy encoded in the URI 43 if (query.has("cspRO")) { 44 response.setHeader( 45 "Content-Security-Policy-Report-Only", 46 query.get("cspRO"), 47 false 48 ); 49 } 50 51 // Deliver the CORS header in the URL 52 if (query.has("cors")) { 53 response.setHeader("Access-Control-Allow-Origin", query.get("cors"), false); 54 } 55 56 // Send HTML to test allowed/blocked behaviors 57 let type = "text/html"; 58 if (query.has("type")) { 59 type = query.get("type"); 60 } 61 62 response.setHeader("Content-Type", type, false); 63 if (query.has("file")) { 64 response.write(loadHTMLFromFile(query.get("file"))); 65 } 66 }