1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23const common = require('../common');
24if (!common.hasCrypto)
25  common.skip('missing crypto');
26
27const fixtures = require('../common/fixtures');
28
29const assert = require('assert');
30const https = require('https');
31
32const options = {
33  key: fixtures.readKey('rsa_private.pem'),
34  cert: fixtures.readKey('rsa_cert.crt')
35};
36
37const server = https.createServer(options, common.mustCall(function(req, res) {
38  res.writeHead(200);
39  res.end();
40  req.resume();
41}, 2)).listen(0, function() {
42  unauthorized();
43});
44
45function unauthorized() {
46  const req = https.request({
47    port: server.address().port,
48    rejectUnauthorized: false
49  }, function(res) {
50    assert(!req.socket.authorized);
51    res.resume();
52    rejectUnauthorized();
53  });
54  req.on('error', function(err) {
55    throw err;
56  });
57  req.end();
58}
59
60function rejectUnauthorized() {
61  const options = {
62    port: server.address().port
63  };
64  options.agent = new https.Agent(options);
65  const req = https.request(options, common.mustNotCall());
66  req.on('error', function(err) {
67    authorized();
68  });
69  req.end();
70}
71
72function authorized() {
73  const options = {
74    port: server.address().port,
75    ca: [fixtures.readKey('rsa_cert.crt')]
76  };
77  options.agent = new https.Agent(options);
78  const req = https.request(options, function(res) {
79    res.resume();
80    assert(req.socket.authorized);
81    server.close();
82  });
83  req.on('error', common.mustNotCall());
84  req.end();
85}
86