summaryrefslogtreecommitdiffstats
path: root/netwerk/test/unit/test_client_auth_with_proxy.js
blob: 11f0ebdafec185de6b7dce72075d759ef47f58ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

/* import-globals-from head_cache.js */
/* import-globals-from head_cookies.js */
/* import-globals-from head_channels.js */
/* import-globals-from head_servers.js */

const { MockRegistrar } = ChromeUtils.importESModule(
  "resource://testing-common/MockRegistrar.sys.mjs"
);

const certOverrideService = Cc[
  "@mozilla.org/security/certoverride;1"
].getService(Ci.nsICertOverrideService);

function makeChan(uri) {
  let chan = NetUtil.newChannel({
    uri,
    loadUsingSystemPrincipal: true,
  }).QueryInterface(Ci.nsIHttpChannel);
  chan.loadFlags = Ci.nsIChannel.LOAD_INITIAL_DOCUMENT_URI;
  return chan;
}

function channelOpenPromise(chan, flags) {
  return new Promise(resolve => {
    function finish(req, buffer) {
      resolve([req, buffer]);
    }
    chan.asyncOpen(new ChannelListener(finish, null, flags));
  });
}

class SecurityObserver {
  constructor(input, output) {
    this.input = input;
    this.output = output;
  }

  onHandshakeDone() {
    info("TLS handshake done");

    let output = this.output;
    this.input.asyncWait(
      {
        onInputStreamReady(readyInput) {
          let request = NetUtil.readInputStreamToString(
            readyInput,
            readyInput.available()
          );
          ok(
            request.startsWith("GET /") && request.includes("HTTP/1.1"),
            "expecting an HTTP/1.1 GET request"
          );
          let response =
            "HTTP/1.1 200 OK\r\nContent-Type:text/plain\r\n" +
            "Connection:Close\r\nContent-Length:2\r\n\r\nOK";
          output.write(response, response.length);
        },
      },
      0,
      0,
      Services.tm.currentThread
    );
  }
}

function startServer(cert) {
  let tlsServer = Cc["@mozilla.org/network/tls-server-socket;1"].createInstance(
    Ci.nsITLSServerSocket
  );
  tlsServer.init(-1, true, -1);
  tlsServer.serverCert = cert;

  let securityObservers = [];

  let listener = {
    onSocketAccepted(socket, transport) {
      info("Accepted TLS client connection");
      let connectionInfo = transport.securityCallbacks.getInterface(
        Ci.nsITLSServerConnectionInfo
      );
      let input = transport.openInputStream(0, 0, 0);
      let output = transport.openOutputStream(0, 0, 0);
      connectionInfo.setSecurityObserver(new SecurityObserver(input, output));
    },

    onStopListening() {
      info("onStopListening");
      for (let securityObserver of securityObservers) {
        securityObserver.input.close();
        securityObserver.output.close();
      }
    },
  };

  tlsServer.setSessionTickets(false);
  tlsServer.setRequestClientCertificate(Ci.nsITLSServerSocket.REQUEST_ALWAYS);

  tlsServer.asyncListen(listener);

  return tlsServer;
}

// Replace the UI dialog that prompts the user to pick a client certificate.
const clientAuthDialogService = {
  chooseCertificate(hostname, certArray, loadContext, callback) {
    callback.certificateChosen(certArray[0], false);
  },
  QueryInterface: ChromeUtils.generateQI(["nsIClientAuthDialogService"]),
};

let server;
add_setup(async function setup() {
  do_get_profile();

  let clientAuthDialogServiceCID = MockRegistrar.register(
    "@mozilla.org/security/ClientAuthDialogService;1",
    clientAuthDialogService
  );

  let cert = getTestServerCertificate();
  ok(!!cert, "Got self-signed cert");
  server = startServer(cert);

  certOverrideService.rememberValidityOverride(
    "localhost",
    server.port,
    {},
    cert,
    true
  );

  registerCleanupFunction(async function () {
    MockRegistrar.unregister(clientAuthDialogServiceCID);
    certOverrideService.clearValidityOverride("localhost", server.port, {});
    server.close();
  });
});

add_task(async function test_client_auth_with_proxy() {
  let certdb = Cc["@mozilla.org/security/x509certdb;1"].getService(
    Ci.nsIX509CertDB
  );
  addCertFromFile(certdb, "http2-ca.pem", "CTu,u,u");
  addCertFromFile(certdb, "proxy-ca.pem", "CTu,u,u");

  let proxies = [
    NodeHTTPProxyServer,
    NodeHTTPSProxyServer,
    NodeHTTP2ProxyServer,
  ];

  for (let p of proxies) {
    info(`Test with proxy:${p.name}`);
    let proxy = new p();
    await proxy.start();
    registerCleanupFunction(async () => {
      await proxy.stop();
    });

    let chan = makeChan(`https://localhost:${server.port}`);
    let [req, buff] = await channelOpenPromise(chan, CL_ALLOW_UNKNOWN_CL);
    equal(req.status, Cr.NS_OK);
    equal(req.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200);
    equal(buff, "OK");
    req.QueryInterface(Ci.nsIProxiedChannel);
    ok(!!req.proxyInfo);
    notEqual(req.proxyInfo.type, "direct");
    await proxy.stop();
  }
});