summaryrefslogtreecommitdiffstats
path: root/netwerk/test/unit/test_httpssvc_https_upgrade.js
blob: 51b711d983ef1bdbc3d5e364bee051f97cb1e4e8 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/* 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";

const certOverrideService = Cc[
  "@mozilla.org/security/certoverride;1"
].getService(Ci.nsICertOverrideService);
const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js");
const { TestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/TestUtils.sys.mjs"
);

const ReferrerInfo = Components.Constructor(
  "@mozilla.org/referrer-info;1",
  "nsIReferrerInfo",
  "init"
);

add_setup(async function setup() {
  trr_test_setup();

  let h2Port = Services.env.get("MOZHTTP2_PORT");
  Assert.notEqual(h2Port, null);
  Assert.notEqual(h2Port, "");

  Services.prefs.setCharPref(
    "network.trr.uri",
    "https://foo.example.com:" + h2Port + "/httpssvc_as_altsvc"
  );

  Services.prefs.setBoolPref("network.dns.upgrade_with_https_rr", true);
  Services.prefs.setBoolPref("network.dns.use_https_rr_as_altsvc", true);

  Services.prefs.setBoolPref(
    "network.dns.use_https_rr_for_speculative_connection",
    true
  );

  registerCleanupFunction(async () => {
    trr_clear_prefs();
    Services.prefs.clearUserPref("network.dns.upgrade_with_https_rr");
    Services.prefs.clearUserPref("network.dns.use_https_rr_as_altsvc");
    Services.prefs.clearUserPref(
      "network.dns.use_https_rr_for_speculative_connection"
    );
    Services.prefs.clearUserPref("network.dns.notifyResolution");
    Services.prefs.clearUserPref("network.dns.disablePrefetch");
  });

  if (mozinfo.socketprocess_networking) {
    Services.dns; // Needed to trigger socket process.
    await TestUtils.waitForCondition(() => Services.io.socketProcessLaunched);
  }

  Services.prefs.setIntPref("network.trr.mode", Ci.nsIDNSService.MODE_TRRFIRST);
});

function makeChan(url) {
  let chan = NetUtil.newChannel({
    uri: url,
    loadUsingSystemPrincipal: true,
    contentPolicyType: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  }).QueryInterface(Ci.nsIHttpChannel);
  return chan;
}

// When observer is specified, the channel will be suspended when receiving
// "http-on-modify-request".
function channelOpenPromise(chan, flags, observer) {
  return new Promise(resolve => {
    function finish(req, buffer) {
      certOverrideService.setDisableAllSecurityChecksAndLetAttackersInterceptMyData(
        false
      );
      resolve([req, buffer]);
    }
    certOverrideService.setDisableAllSecurityChecksAndLetAttackersInterceptMyData(
      true
    );

    if (observer) {
      let topic = "http-on-modify-request";
      Services.obs.addObserver(observer, topic);
    }
    chan.asyncOpen(new ChannelListener(finish, null, flags));
  });
}

class EventSinkListener {
  getInterface(iid) {
    if (iid.equals(Ci.nsIChannelEventSink)) {
      return this;
    }
    throw Components.Exception("", Cr.NS_ERROR_NO_INTERFACE);
  }
  asyncOnChannelRedirect(oldChan, newChan, flags, callback) {
    Assert.equal(oldChan.URI.hostPort, newChan.URI.hostPort);
    Assert.equal(oldChan.URI.scheme, "http");
    Assert.equal(newChan.URI.scheme, "https");
    callback.onRedirectVerifyCallback(Cr.NS_OK);
  }
}

EventSinkListener.prototype.QueryInterface = ChromeUtils.generateQI([
  "nsIInterfaceRequestor",
  "nsIChannelEventSink",
]);

// Test if the request is upgraded to https with a HTTPSSVC record.
add_task(async function testUseHTTPSSVCAsHSTS() {
  Services.dns.clearCache(true);
  // Do DNS resolution before creating the channel, so the HTTPSSVC record will
  // be resolved from the cache.
  await new TRRDNSListener("test.httpssvc.com", {
    type: Ci.nsIDNSService.RESOLVE_TYPE_HTTPSSVC,
  });

  // Since the HTTPS RR should be served from cache, the DNS record is available
  // before nsHttpChannel::MaybeUseHTTPSRRForUpgrade() is called.
  let chan = makeChan(`http://test.httpssvc.com:80/server-timing`);
  let listener = new EventSinkListener();
  chan.notificationCallbacks = listener;

  let [req] = await channelOpenPromise(chan);

  req.QueryInterface(Ci.nsIHttpChannel);
  Assert.equal(req.getResponseHeader("x-connection-http2"), "yes");

  chan = makeChan(`http://test.httpssvc.com:80/server-timing`);
  listener = new EventSinkListener();
  chan.notificationCallbacks = listener;

  [req] = await channelOpenPromise(chan);

  req.QueryInterface(Ci.nsIHttpChannel);
  Assert.equal(req.getResponseHeader("x-connection-http2"), "yes");
});

// Test the case that we got an invalid DNS response. In this case,
// nsHttpChannel::OnHTTPSRRAvailable is called after
// nsHttpChannel::MaybeUseHTTPSRRForUpgrade.
add_task(async function testInvalidDNSResult() {
  Services.dns.clearCache(true);

  let httpserv = new HttpServer();
  let content = "ok";
  httpserv.registerPathHandler("/", function handler(metadata, response) {
    response.setHeader("Content-Length", `${content.length}`);
    response.bodyOutputStream.write(content, content.length);
  });
  httpserv.start(-1);
  httpserv.identity.setPrimary(
    "http",
    "foo.notexisted.com",
    httpserv.identity.primaryPort
  );

  let chan = makeChan(
    `http://foo.notexisted.com:${httpserv.identity.primaryPort}/`
  );
  let [, response] = await channelOpenPromise(chan);
  Assert.equal(response, content);
  await new Promise(resolve => httpserv.stop(resolve));
});

// The same test as above, but nsHttpChannel::MaybeUseHTTPSRRForUpgrade is
// called after nsHttpChannel::OnHTTPSRRAvailable.
add_task(async function testInvalidDNSResult1() {
  Services.dns.clearCache(true);

  let httpserv = new HttpServer();
  let content = "ok";
  httpserv.registerPathHandler("/", function handler(metadata, response) {
    response.setHeader("Content-Length", `${content.length}`);
    response.bodyOutputStream.write(content, content.length);
  });
  httpserv.start(-1);
  httpserv.identity.setPrimary(
    "http",
    "foo.notexisted.com",
    httpserv.identity.primaryPort
  );

  let chan = makeChan(
    `http://foo.notexisted.com:${httpserv.identity.primaryPort}/`
  );

  let topic = "http-on-modify-request";
  let observer = {
    QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),
    observe(aSubject, aTopic, aData) {
      if (aTopic == topic) {
        Services.obs.removeObserver(observer, topic);
        let channel = aSubject.QueryInterface(Ci.nsIChannel);
        channel.suspend();

        new TRRDNSListener("foo.notexisted.com", {
          type: Ci.nsIDNSService.RESOLVE_TYPE_HTTPSSVC,
          expectedSuccess: false,
        }).then(() => channel.resume());
      }
    },
  };

  let [, response] = await channelOpenPromise(chan, 0, observer);
  Assert.equal(response, content);
  await new Promise(resolve => httpserv.stop(resolve));
});

add_task(async function testLiteralIP() {
  let httpserv = new HttpServer();
  let content = "ok";
  httpserv.registerPathHandler("/", function handler(metadata, response) {
    response.setHeader("Content-Length", `${content.length}`);
    response.bodyOutputStream.write(content, content.length);
  });
  httpserv.start(-1);

  let chan = makeChan(`http://127.0.0.1:${httpserv.identity.primaryPort}/`);
  let [, response] = await channelOpenPromise(chan);
  Assert.equal(response, content);
  await new Promise(resolve => httpserv.stop(resolve));
});

// Test the case that an HTTPS RR is available and the server returns a 307
// for redirecting back to http.
add_task(async function testEndlessUpgradeDowngrade() {
  Services.dns.clearCache(true);

  let httpserv = new HttpServer();
  let content = "okok";
  httpserv.start(-1);
  let port = httpserv.identity.primaryPort;
  httpserv.registerPathHandler(
    `/redirect_to_http`,
    function handler(metadata, response) {
      response.setHeader("Content-Length", `${content.length}`);
      response.bodyOutputStream.write(content, content.length);
    }
  );
  httpserv.identity.setPrimary("http", "test.httpsrr.redirect.com", port);

  let chan = makeChan(
    `http://test.httpsrr.redirect.com:${port}/redirect_to_http?port=${port}`
  );

  let [, response] = await channelOpenPromise(chan);
  Assert.equal(response, content);
  await new Promise(resolve => httpserv.stop(resolve));
});

add_task(async function testHttpRequestBlocked() {
  Services.dns.clearCache(true);

  let dnsRequestObserver = {
    register() {
      this.obs = Services.obs;
      this.obs.addObserver(this, "dns-resolution-request");
    },
    unregister() {
      if (this.obs) {
        this.obs.removeObserver(this, "dns-resolution-request");
      }
    },
    observe(subject, topic, data) {
      if (topic == "dns-resolution-request") {
        Assert.ok(false, "unreachable");
      }
    },
  };

  dnsRequestObserver.register();
  Services.prefs.setBoolPref("network.dns.notifyResolution", true);
  Services.prefs.setBoolPref("network.dns.disablePrefetch", true);

  let httpserv = new HttpServer();
  httpserv.registerPathHandler("/", function handler(metadata, response) {
    Assert.ok(false, "unreachable");
  });
  httpserv.start(-1);
  httpserv.identity.setPrimary(
    "http",
    "foo.blocked.com",
    httpserv.identity.primaryPort
  );

  let chan = makeChan(
    `http://foo.blocked.com:${httpserv.identity.primaryPort}/`
  );

  let topic = "http-on-modify-request";
  let observer = {
    QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),
    observe(aSubject, aTopic, aData) {
      if (aTopic == topic) {
        Services.obs.removeObserver(observer, topic);
        let channel = aSubject.QueryInterface(Ci.nsIChannel);
        channel.cancel(Cr.NS_BINDING_ABORTED);
      }
    },
  };

  let [request] = await channelOpenPromise(chan, CL_EXPECT_FAILURE, observer);
  request.QueryInterface(Ci.nsIHttpChannel);
  Assert.equal(request.status, Cr.NS_BINDING_ABORTED);
  dnsRequestObserver.unregister();
  await new Promise(resolve => httpserv.stop(resolve));
});

function createPrincipal(url) {
  return Services.scriptSecurityManager.createContentPrincipal(
    Services.io.newURI(url),
    {}
  );
}

// Test if the Origin header stays the same after an internal HTTPS upgrade
// caused by HTTPS RR.
add_task(async function testHTTPSRRUpgradeWithOriginHeader() {
  Services.dns.clearCache(true);

  const url = "http://test.httpssvc.com:80/origin_header";
  const originURL = "http://example.com";
  let chan = Services.io
    .newChannelFromURIWithProxyFlags(
      Services.io.newURI(url),
      null,
      Ci.nsIProtocolProxyService.RESOLVE_ALWAYS_TUNNEL,
      null,
      createPrincipal(originURL),
      createPrincipal(url),
      Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
      Ci.nsIContentPolicy.TYPE_DOCUMENT
    )
    .QueryInterface(Ci.nsIHttpChannel);
  chan.referrerInfo = new ReferrerInfo(
    Ci.nsIReferrerInfo.EMPTY,
    true,
    NetUtil.newURI(url)
  );
  chan.setRequestHeader("Origin", originURL, false);

  let [req, buf] = await channelOpenPromise(chan);

  req.QueryInterface(Ci.nsIHttpChannel);
  Assert.equal(req.getResponseHeader("x-connection-http2"), "yes");
  Assert.equal(buf, originURL);
});