/
test-quic-client-server.js
355 lines (310 loc) Β· 12.1 KB
/
test-quic-client-server.js
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
351
352
353
354
355
// Flags: --expose-internals --no-warnings
'use strict';
// Tests a simple QUIC client/server round-trip
const common = require('../common');
if (!common.hasQuic)
common.skip('missing quic');
const { internalBinding } = require('internal/test/binding');
const {
constants: {
NGTCP2_NO_ERROR,
QUIC_ERROR_APPLICATION,
}
} = internalBinding('quic');
const { Buffer } = require('buffer');
const Countdown = require('../common/countdown');
const assert = require('assert');
const fs = require('fs');
const {
key,
cert,
ca,
debug,
} = require('../common/quic');
const filedata = fs.readFileSync(__filename, { encoding: 'utf8' });
const { createQuicSocket } = require('net');
const kStatelessResetToken =
Buffer.from('000102030405060708090A0B0C0D0E0F', 'hex');
const unidata = ['I wonder if it worked.', 'test'];
const kServerName = 'agent2'; // Intentionally the wrong servername
const kALPN = 'zzz'; // ALPN can be overriden to whatever we want
const options = { key, cert, ca, alpn: kALPN };
const client = createQuicSocket({ client: options });
const server = createQuicSocket({
validateAddress: true,
statelessResetSecret: kStatelessResetToken,
server: options
});
const countdown = new Countdown(2, () => {
debug('Countdown expired. Destroying sockets');
server.close();
client.close();
});
function onSocketClose() {
debug(`${this.constructor.name} closing. Duration`, this.duration);
debug(' Bound duration:',
this.boundDuration);
debug(' Listen duration:',
this.listenDuration);
debug(' Bytes Sent/Received: %d/%d',
this.bytesSent,
this.bytesReceived);
debug(' Packets Sent/Received: %d/%d',
this.packetsSent,
this.packetsReceived);
debug(' Sessions:', this.serverSessions, this.clientSessions);
}
server.on('listening', common.mustCall());
server.on('ready', common.mustCall());
server.on('close', common.mustCall(onSocketClose.bind(server)));
client.on('endpointClose', common.mustCall());
client.on('close', common.mustCall(onSocketClose.bind(client)));
(async function() {
server.on('session', common.mustCall((session) => {
debug('QuicServerSession Created');
assert.strictEqual(session.maxStreams.bidi, 100);
assert.strictEqual(session.maxStreams.uni, 3);
{
const {
address,
family,
port
} = session.remoteAddress;
const endpoint = client.endpoints[0].address;
assert.strictEqual(port, endpoint.port);
assert.strictEqual(family, endpoint.family);
debug(`QuicServerSession Client ${family} address ${address}:${port}`);
}
session.on('usePreferredAddress', common.mustNotCall());
session.on('clientHello', common.mustCall(
(alpn, servername, ciphers, cb) => {
assert.strictEqual(alpn, kALPN);
assert.strictEqual(servername, kServerName);
assert.strictEqual(ciphers.length, 4);
cb();
}));
session.on('OCSPRequest', common.mustCall(
(servername, context, cb) => {
debug('QuicServerSession received a OCSP request');
assert.strictEqual(servername, kServerName);
// This will be a SecureContext. By default it will
// be the SecureContext used to create the QuicSession.
// If the user wishes to do something with it, it can,
// but if it wishes to pass in a new SecureContext,
// it can pass it in as the second argument to the
// callback below.
assert(context);
debug('QuicServerSession Certificate: ', context.getCertificate());
debug('QuicServerSession Issuer: ', context.getIssuer());
// The callback can be invoked asynchronously
setImmediate(() => {
// The first argument is a potential error,
// in which case the session will be destroyed
// immediately.
// The second is an optional new SecureContext
// The third is the ocsp response.
// All arguments are optional
cb(null, null, Buffer.from('hello'));
});
}));
session.on('secure', common.mustCall(async (servername, alpn, cipher) => {
debug('QuicServerSession TLS Handshake Complete');
debug(' Server name: %s', servername);
debug(' ALPN: %s', alpn);
debug(' Cipher: %s, %s', cipher.name, cipher.version);
assert.strictEqual(session.servername, servername);
assert.strictEqual(servername, kServerName);
assert.strictEqual(session.alpnProtocol, alpn);
assert.strictEqual(session.getPeerCertificate().subject.CN, 'agent1');
assert(session.authenticated);
assert.strictEqual(session.authenticationError, undefined);
const uni = await session.openStream({ halfOpen: true });
assert(uni.unidirectional);
assert(!uni.bidirectional);
assert(uni.serverInitiated);
assert(!uni.clientInitiated);
assert(!uni.pending);
// The data and end events will never emit because
// the unidirectional stream is never readable.
uni.on('end', common.mustNotCall());
uni.on('data', common.mustNotCall());
uni.write(unidata[0], common.mustCall());
uni.end(unidata[1], common.mustCall());
uni.on('finish', common.mustCall());
uni.on('close', common.mustCall(() => {
assert.strictEqual(uni.finalSize, 0);
}));
debug('Unidirectional, Server-initiated stream %d opened', uni.id);
}));
session.on('stream', common.mustCall((stream) => {
debug('Bidirectional, Client-initiated stream %d received', stream.id);
assert.strictEqual(stream.id, 0);
assert.strictEqual(stream.session, session);
assert(stream.bidirectional);
assert(!stream.unidirectional);
assert(stream.clientInitiated);
assert(!stream.serverInitiated);
const file = fs.createReadStream(__filename);
let data = '';
file.pipe(stream);
stream.setEncoding('utf8');
stream.on('blocked', common.mustNotCall());
stream.on('data', (chunk) => {
data += chunk;
debug('Server: min data rate: %f', stream.dataRateHistogram.min);
debug('Server: max data rate: %f', stream.dataRateHistogram.max);
debug('Server: data rate 50%: %f',
stream.dataRateHistogram.percentile(50));
debug('Server: data rate 99%: %f',
stream.dataRateHistogram.percentile(99));
debug('Server: min data size: %f', stream.dataSizeHistogram.min);
debug('Server: max data size: %f', stream.dataSizeHistogram.max);
debug('Server: data size 50%: %f',
stream.dataSizeHistogram.percentile(50));
debug('Server: data size 99%: %f',
stream.dataSizeHistogram.percentile(99));
});
stream.on('end', common.mustCall(() => {
assert.strictEqual(data, filedata);
debug('Server received expected data for stream %d', stream.id);
}));
stream.on('finish', common.mustCall());
stream.on('close', common.mustCall(() => {
assert.strictEqual(typeof stream.duration, 'number');
assert.strictEqual(typeof stream.bytesReceived, 'number');
assert.strictEqual(typeof stream.bytesSent, 'number');
assert.strictEqual(typeof stream.maxExtendedOffset, 'number');
assert.strictEqual(stream.finalSize, filedata.length);
}));
}));
session.on('close', common.mustCall(() => {
const {
code,
family
} = session.closeCode;
debug(`Server session closed with code ${code} (family: ${family})`);
assert.strictEqual(code, NGTCP2_NO_ERROR);
const err = {
code: 'ERR_INVALID_STATE',
name: 'Error'
};
assert.throws(() => session.ping(), err);
assert.throws(() => session.updateKey(), err);
assert.rejects(() => session.openStream(), err);
}));
}));
await server.listen({
requestCert: true,
rejectUnauthorized: false,
});
const endpoints = server.endpoints;
for (const endpoint of endpoints) {
const address = endpoint.address;
debug('Server is listening on address %s:%d',
address.address,
address.port);
}
const endpoint = endpoints[0];
const req = await client.connect({
address: 'localhost',
port: endpoint.address.port,
servername: kServerName,
requestOCSP: true,
});
assert.strictEqual(req.servername, kServerName);
req.on('usePreferredAddress', common.mustNotCall());
req.on('OCSPResponse', common.mustCall((response) => {
debug(`QuicClientSession OCSP response: "${response.toString()}"`);
assert.strictEqual(response.toString(), 'hello');
}));
req.on('sessionTicket', common.mustCall((ticket, params) => {
debug('Session ticket received');
assert(ticket instanceof Buffer);
assert(params instanceof Buffer);
debug(' Ticket: %s', ticket.toString('hex'));
debug(' Params: %s', params.toString('hex'));
}, 2));
req.on('secure', common.mustCall(async (servername, alpn, cipher) => {
debug('QuicClientSession TLS Handshake Complete');
debug(' Server name: %s', servername);
debug(' ALPN: %s', alpn);
debug(' Cipher: %s, %s', cipher.name, cipher.version);
assert.strictEqual(servername, kServerName);
assert.strictEqual(req.servername, kServerName);
assert.strictEqual(alpn, kALPN);
assert.strictEqual(req.alpnProtocol, kALPN);
assert(req.ephemeralKeyInfo);
assert.strictEqual(req.getPeerCertificate().subject.CN, 'agent1');
debug('Client, min handshake ack: %f',
req.handshakeAckHistogram.min);
debug('Client, max handshake ack: %f',
req.handshakeAckHistogram.max);
debug('Client, min handshake rate: %f',
req.handshakeContinuationHistogram.min);
debug('Client, max handshake rate: %f',
req.handshakeContinuationHistogram.max);
// The server's identity won't be valid because the requested
// SNI hostname does not match the certificate used.
debug('QuicClientSession server is %sauthenticated',
req.authenticated ? '' : 'not ');
assert(!req.authenticated);
assert.throws(() => { throw req.authenticationError; }, {
code: 'ERR_QUIC_VERIFY_HOSTNAME_MISMATCH',
message: 'Hostname mismatch'
});
{
const {
address,
family,
port
} = req.remoteAddress;
const endpoint = server.endpoints[0].address;
assert.strictEqual(port, endpoint.port);
assert.strictEqual(family, endpoint.family);
debug(`QuicClientSession Server ${family} address ${address}:${port}`);
}
const file = fs.createReadStream(__filename);
const stream = await req.openStream();
file.pipe(stream);
let data = '';
stream.resume();
stream.setEncoding('utf8');
stream.on('blocked', common.mustNotCall());
stream.on('data', (chunk) => data += chunk);
stream.on('finish', common.mustCall());
stream.on('end', common.mustCall(() => {
assert.strictEqual(data, filedata);
debug('Client received expected data for stream %d', stream.id);
}));
stream.on('close', common.mustCall(() => {
debug('Bidirectional, Client-initiated stream %d closed', stream.id);
assert.strictEqual(stream.finalSize, filedata.length);
countdown.dec();
}));
debug('Bidirectional, Client-initiated stream %d opened', stream.id);
}));
req.on('stream', common.mustCall((stream) => {
debug('Unidirectional, Server-initiated stream %d received', stream.id);
let data = '';
stream.setEncoding('utf8');
stream.on('data', (chunk) => data += chunk);
stream.on('end', common.mustCall(() => {
assert.strictEqual(data, unidata.join(''));
debug('Client received expected data for stream %d', stream.id);
}));
stream.on('close', common.mustCall(() => {
debug('Unidirectional, Server-initiated stream %d closed', stream.id);
assert.strictEqual(stream.finalSize, 26);
countdown.dec();
}));
}));
req.on('close', common.mustCall(() => {
const {
code,
family
} = req.closeCode;
debug(`Client session closed with code ${code} (family: ${family})`);
assert.strictEqual(code, NGTCP2_NO_ERROR);
assert.strictEqual(family, QUIC_ERROR_APPLICATION);
}));
})().then(common.mustCall());