summaryrefslogtreecommitdiff
path: root/test/parallel/test-tls-psk-server.js
blob: 434d31380fe2adf180a7f9d39fa96acfb523c658 (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
'use strict';
const common = require('../common');

if (!common.hasCrypto)
  common.skip('missing crypto');
if (!common.opensslCli)
  common.skip('missing openssl cli');

const assert = require('assert');

const tls = require('tls');
const spawn = require('child_process').spawn;

const CIPHERS = 'PSK+HIGH';
const KEY = 'd731ef57be09e5204f0b205b60627028';
const IDENTITY = 'TestUser';

const server = tls.createServer({
  ciphers: CIPHERS,
  pskIdentityHint: IDENTITY,
  pskCallback(socket, identity) {
    assert.ok(socket instanceof tls.TLSSocket);
    assert.ok(typeof identity === 'string');
    if (identity === IDENTITY)
      return Buffer.from(KEY, 'hex');
  }
});

server.on('connection', common.mustCall());

server.on('secureConnection', (socket) => {
  socket.write('hello\r\n');

  socket.on('data', (data) => {
    socket.write(data);
  });
});

let gotHello = false;
let sentWorld = false;
let gotWorld = false;

server.listen(0, () => {
  const client = spawn(common.opensslCli, [
    's_client',
    '-connect', `127.0.0.1:${server.address().port}`,
    '-cipher', CIPHERS,
    '-psk', KEY,
    '-psk_identity', IDENTITY
  ]);

  let out = '';

  client.stdout.setEncoding('utf8');
  client.stdout.on('data', (d) => {
    out += d;

    if (!gotHello && /hello/.test(out)) {
      gotHello = true;
      client.stdin.write('world\r\n');
      sentWorld = true;
    }

    if (!gotWorld && /world/.test(out)) {
      gotWorld = true;
      client.stdin.end();
    }
  });

  client.on('exit', common.mustCall((code) => {
    assert.ok(gotHello);
    assert.ok(sentWorld);
    assert.ok(gotWorld);
    assert.strictEqual(code, 0);
    server.close();
  }));
});