test_connection_based_auth.js (2896B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 const { NodeHTTPSProxyServer } = ChromeUtils.importESModule( 8 "resource://testing-common/NodeServer.sys.mjs" 9 ); 10 11 /* import-globals-from head_cache.js */ 12 /* import-globals-from head_cookies.js */ 13 /* import-globals-from head_channels.js */ 14 15 function makeChan(uri) { 16 let chan = NetUtil.newChannel({ 17 uri, 18 loadUsingSystemPrincipal: true, 19 }).QueryInterface(Ci.nsIHttpChannel); 20 chan.loadFlags = Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI; 21 return chan; 22 } 23 24 function channelOpenPromise(chan, flags) { 25 return new Promise(resolve => { 26 function finish(req, buffer) { 27 resolve([req, buffer]); 28 } 29 chan.asyncOpen(new ChannelListener(finish, null, flags)); 30 }); 31 } 32 33 add_task(async function test_connection_based_auth() { 34 let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService( 35 Ci.nsIX509CertDB 36 ); 37 addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u"); 38 addCertFromFile(certdb, "proxy-ca.pem", "CTu,u,u"); 39 40 let proxy = new NodeHTTPSProxyServer(); 41 await proxy.start(); 42 43 await proxy.registerConnectHandler((req, clientSocket) => { 44 if (!req.headers["proxy-authorization"]) { 45 clientSocket.write( 46 "HTTP/1.1 407 Unauthorized\r\n" + 47 "Proxy-agent: Node.js-Proxy\r\n" + 48 "Connection: keep-alive\r\n" + 49 "Proxy-Authenticate: mock_auth\r\n" + 50 "Content-Length: 0\r\n" + 51 "\r\n" 52 ); 53 54 clientSocket.on("data", data => { 55 let array = data.toString().split("\r\n"); 56 let proxyAuthorization = ""; 57 for (let line of array) { 58 let pair = line.split(":").map(element => element.trim()); 59 if (pair[0] === "Proxy-Authorization") { 60 proxyAuthorization = pair[1]; 61 } 62 } 63 64 if (proxyAuthorization === "moz_test_credentials") { 65 // We don't return 200 OK here, because we don't have a server 66 // to connect to. 67 clientSocket.write( 68 "HTTP/1.1 404 Not Found\r\nProxy-agent: Node.js-Proxy\r\n\r\n" 69 ); 70 } else { 71 clientSocket.write( 72 "HTTP/1.1 502 Error\r\nProxy-agent: Node.js-Proxy\r\n\r\n" 73 ); 74 } 75 clientSocket.destroy(); 76 }); 77 return; 78 } 79 80 // We should not reach here. 81 clientSocket.write( 82 "HTTP/1.1 502 Error\r\nProxy-agent: Node.js-Proxy\r\n\r\n" 83 ); 84 clientSocket.destroy(); 85 }); 86 87 let chan = makeChan(`https://example.ntlm.com/test`); 88 let [req] = await channelOpenPromise(chan, CL_EXPECT_FAILURE); 89 Assert.equal(req.status, Cr.NS_ERROR_UNKNOWN_HOST); 90 req.QueryInterface(Ci.nsIProxiedChannel); 91 Assert.equal(req.httpProxyConnectResponseCode, 404); 92 93 await proxy.stop(); 94 });