mock-tls-server 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Joe Hildebrand
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # mock-tls-server
2
+
3
+ Mock up a plain or TLS-encrypted TCP connection without using any actual
4
+ network facilities or needing any permissions. This is useful for testing,
5
+ particularly playing around with different TLS failure modes.
6
+
7
+ **WARNING**: this package is intended to only be used for testing. It should not
8
+ be used in any sort of production or Internet-connected setting. In
9
+ particular, the included Certificate Authority should NEVER be trusted further
10
+ than individual tests.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ $ npm install --save-dev mock-tls-server
16
+ ```
17
+
18
+ ## API Documentation
19
+
20
+ The intent is that the API is similar to that found in Node's
21
+ [net](https://nodejs.org/api/net.html) and
22
+ [tls](https://nodejs.org/api/tls.html) packages. See full docs
23
+ [here](http://hildjj.github.io/mock-tls-server/).
24
+
25
+ ## Example:
26
+
27
+ ```js
28
+ import {MockTLSServer, connect} from 'mock-tls-server'
29
+
30
+ // Expected output: "Welcome!\nexample\n"
31
+
32
+ const server = new MockTLSServer()
33
+ server.listen(4000, sock => {
34
+ sock.write('Welcome!\n')
35
+ sock.pipe(sock)
36
+ })
37
+
38
+ const cli = connect(4000, () => {
39
+ // Send a string, and end the write side of the socket
40
+ // allowHalfOpen is false on both sides by default, so the
41
+ // server will close it's write side in resonse, leading the
42
+ // client to go to the 'closed' state.
43
+ cli.end('example\n')
44
+ })
45
+ .on('data', chunk => process.stdout.write(chunk.toString()))
46
+ .on('close', () => server.close())
47
+ ```
48
+
49
+ ## Always close the server
50
+
51
+ The server, like a TCP server, will keep the node process from shutting down
52
+ while it is listening. Make sure to call `close()` when you are done with it.
53
+
54
+ If this turns out to be a problem for folks, I'll change it -- please file an
55
+ issue with ideas.
56
+
57
+ ## Use in tests
58
+
59
+ I use [p-event](https://github.com/sindresorhus/p-event#readme) to wait for
60
+ individual events in async functions:
61
+
62
+ ```js
63
+ import pEvent from 'p-event'
64
+
65
+ await pEvent(client, 'secureConnection')
66
+ ```
67
+
68
+ You can call `plainConnect` to get a client socket that hasn't been connected
69
+ with TLS yet, then pass that socket to existing code as a part of its
70
+ parameters for
71
+ [`tls.connect`](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
72
+
73
+ ```js
74
+ import {plainConnect, MockTLSServer} from 'mock-tls-server'
75
+ import tls from 'tls'
76
+
77
+ const server = new MockTLSServer({
78
+ notBefore: new Date(new Date().getTime() + 10000) // Invalid because of time
79
+ })
80
+ server.listen()
81
+ await pEvent(server, 'listening')
82
+ const socket = plainConnect(server.port)
83
+ tls.connect({
84
+ socket,
85
+ host: 'localhost', // Alter this to test name mismatches
86
+ ca: server.ca., // Alter this to test signing failures
87
+ })
88
+ ```
89
+
90
+ See the tests in this package for more ideas.
91
+
92
+ ## Logging
93
+
94
+ While you're testing, you'll wonder if anything is actually happening. All of
95
+ the events that are flowing through the system can be logged by using the
96
+ NODE_DEBUG environment variable and including `mock-tls-server`:
97
+
98
+ ```bash
99
+ NODE_DEBUG=mock-tls-server node examples/echo.js
100
+ ```
101
+
102
+ [![Tests](https://github.com/hildjj/mock-tls-server/actions/workflows/node.js.yml/badge.svg)](https://github.com/hildjj/mock-tls-server/actions/workflows/node.js.yml)
103
+ [![codecov](https://codecov.io/gh/hildjj/mock-tls-server/branch/main/graph/badge.svg?token=86PXRWEHKH)](https://codecov.io/gh/hildjj/mock-tls-server)
package/lib/ca.js ADDED
@@ -0,0 +1,135 @@
1
+ import * as rs from 'jsrsasign'
2
+
3
+ const MINS_5 = 5 * 60 * 1000
4
+ const SECS_1 = 1000
5
+
6
+ // Private map of CertificateAuthority => private key
7
+ const PRIVATE = new WeakMap()
8
+
9
+ /**
10
+ * @typedef {object} CertOpts
11
+ * @property {Date} [notafter='Now + 5m'] Certificate not valid after this
12
+ * date.
13
+ * @property {Date} [notbefore='Now - 1s'] Certificate not valid before this
14
+ * date.
15
+ * @property {string} [subject] Subject Distinguished Name (DN).
16
+ * @property {string[]} [names=['localhost']] DNS Subject Alternative Names
17
+ * for the cert. Ignored for the CA cert.
18
+ */
19
+
20
+ /**
21
+ * @typedef {object} ServerProperties
22
+ * @property {string} cert PEM-encoded server certificate.
23
+ * @property {string} key PEM-encoded server private key.
24
+ * @property {string} ca PEM-encoded CA certificate.
25
+ */
26
+
27
+ /**
28
+ * Very rudimentary Certificate Authority (CA).
29
+ * Warning: DO NOT use this on the Internet. It is only for testing purposes.
30
+ */
31
+ export class CertificateAuthority {
32
+ /**
33
+ * Creates an instance of CertificateAuthority.
34
+ *
35
+ * @param {CertOpts} [opts={}] CA cert options.
36
+ */
37
+ constructor(opts = {}) {
38
+ const now = new Date().getTime()
39
+ opts = {
40
+ notafter: new Date(now + MINS_5),
41
+ notbefore: new Date(now - SECS_1),
42
+ subject: 'C=US/ST=Colorado/L=Denver/CN=Example-Root-CA',
43
+ ...opts,
44
+ }
45
+
46
+ this.subject = opts.subject
47
+
48
+ // Create a self-signed CA cert
49
+ const ca_kp = rs.KEYUTIL.generateKeypair('RSA', 1024)
50
+ PRIVATE.set(this, ca_kp.prvKeyObj)
51
+ const pub = ca_kp.pubKeyObj
52
+
53
+ const ca_cert = new rs.KJUR.asn1.x509.Certificate({
54
+ version: 3,
55
+ serial: {int: now},
56
+ issuer: {str: opts.subject},
57
+ notbefore: {str: rs.datetozulu(opts.notbefore)},
58
+ notafter: {str: rs.datetozulu(opts.notafter)},
59
+ subject: {str: opts.subject},
60
+ sbjpubkey: pub,
61
+ ext: [
62
+ {extname: 'basicConstraints', cA: true},
63
+ ],
64
+ sigalg: 'SHA256withRSA',
65
+ cakey: PRIVATE.get(this),
66
+ })
67
+
68
+ /** @type {string} */
69
+ this.cert_pem = ca_cert.getPEM()
70
+ }
71
+
72
+ /**
73
+ * Creates and signs a server certificate.
74
+ *
75
+ * @param {CertOpts} [opts={}] Server cert options.
76
+ * @returns {ServerProperties} Information about the created certificate.
77
+ * @throws {Error} No subject or names.
78
+ */
79
+ issue(opts) {
80
+ const now = new Date().getTime()
81
+ opts = {
82
+ notafter: new Date(now + MINS_5),
83
+ notbefore: new Date(now - SECS_1),
84
+ subject: null,
85
+ names: ['localhost'],
86
+ ...opts,
87
+ }
88
+
89
+ if (!opts.subject) {
90
+ if (opts.names.length === 0) {
91
+ throw new Error('Must include subject or at least one name in opts')
92
+ }
93
+ opts.subject = `C=US/ST=Colorado/L=Denver/CN=${opts.names[0]}`
94
+ }
95
+
96
+ const srv_kp = rs.KEYUTIL.generateKeypair('RSA', 1024)
97
+ const srv_prv = srv_kp.prvKeyObj
98
+ const srv_pub = srv_kp.pubKeyObj
99
+
100
+ const srv = new rs.KJUR.asn1.x509.Certificate({
101
+ version: 3,
102
+ serial: {int: 2},
103
+ issuer: {str: this.subject},
104
+ notbefore: {str: rs.datetozulu(opts.notbefore)},
105
+ notafter: {str: rs.datetozulu(opts.notafter)},
106
+ subject: {str: opts.subject},
107
+ sbjpubkey: srv_pub,
108
+ ext: [
109
+ {extname: 'authorityKeyIdentifier', kid: this.cert_pem},
110
+ {extname: 'basicConstraints', cA: false},
111
+ {
112
+ extname: 'keyUsage',
113
+ names: [
114
+ 'digitalSignature',
115
+ 'nonRepudiation',
116
+ 'keyEncipherment',
117
+ 'dataEncipherment',
118
+ ],
119
+ },
120
+ {
121
+ extname: 'subjectAltName',
122
+ array: opts.names.map(n => ({dns: n})),
123
+ },
124
+ ],
125
+ sigalg: 'SHA256withRSA',
126
+ cakey: PRIVATE.get(this),
127
+ })
128
+
129
+ return {
130
+ cert: srv.getPEM(),
131
+ key: rs.KEYUTIL.getPEM(srv_prv, 'PKCS1PRV'),
132
+ ca: this.cert_pem,
133
+ }
134
+ }
135
+ }